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This module provides a minimal state machine for tracking delegated work\n * within the current session/branch. It is honest that this is ephemeral\n * session state, not provenance or cross-session tracking.\n *\n * Derived from:\n * - Subagent tool call arguments (ToolCallEvent.input for \"subagent\" tool)\n * - Subagent tool results (ToolResultMessage with toolName \"subagent\")\n * - Persisted tool result details (SubagentDetails)\n */\n\nimport type { ToolResultMessage } from \"@apholdings/jensen-ai\";\nimport type { ToolCallEvent } from \"./extensions/index.js\";\n\n/**\n * Execution mode for a delegated task.\n */\nexport type DelegatedMode = \"single\" | \"parallel\" | \"chain\";\n\n/**\n * Status of a delegated work item.\n */\nexport type DelegatedStatus = \"active\" | \"completed\" | \"error\" | \"blocked\";\n\n/**\n * Minimal record of a single delegated subagent child task.\n *\n * For multi-task modes, multiple DelegatedTask records can share the same\n * parent toolCallId. `childIndex` disambiguates individual child work items\n * within one live subagent invocation.\n */\nexport interface DelegatedTask {\n\t/** Parent subagent tool call identifier. */\n\ttoolCallId: string;\n\t/** 1-based child position for parallel child tasks. */\n\tchildIndex?: number;\n\t/** Human-readable agent name. */\n\tagent: string;\n\t/** Source scope of the agent (user, project, both, unknown). */\n\tagentSource: \"user\" | \"project\" | \"both\" | \"unknown\";\n\t/** The task description/prompt delegated to the agent. */\n\ttask: string;\n\t/** Execution mode: single, parallel, or chain. */\n\tmode: DelegatedMode;\n\t/** Current status. */\n\tstatus: DelegatedStatus;\n\t/** Step index for chain mode (1-based, when known). */\n\tstep?: number;\n\t/** Exit code from the child process (if available). */\n\texitCode?: number;\n\t/** Error or diagnostic message if failed. */\n\terrorMessage?: string;\n\t/** Brief output preview extracted from final assistant message. */\n\toutputPreview?: string;\n\t/** Tool call arguments as provided (for inspection). */\n\trawArgs?: Record<string, unknown>;\n\t/** When the tool call was made. */\n\ttimestamp: number;\n}\n\n/**\n * Aggregated summary of delegated work state.\n * Used for UI display and debugging.\n */\nexport interface DelegatedWorkSummary {\n\t/** Tasks that are currently active (no result yet). */\n\tactive: DelegatedTask[];\n\t/** Tasks that completed successfully. */\n\tcompleted: DelegatedTask[];\n\t/** Tasks that failed or were blocked. */\n\tfailed: DelegatedTask[];\n\t/** Total tasks across all categories. */\n\ttotal: number;\n\t/** Whether this is current-branch/session state (always true, for honesty). */\n\tisSessionState: true;\n\t/** Note clarifying this is not provenance tracking. */\n\tnote: \"ephemeral current-session state; not persisted across sessions or branches\";\n}\n\n/**\n * Detailed subagent result structure from persisted tool results.\n * This matches the SubagentDetails interface from the subagent extension.\n */\ninterface SubagentResult {\n\tagent: string;\n\tagentSource: \"user\" | \"project\" | \"unknown\";\n\ttask: string;\n\texitCode: number;\n\tmessages: unknown[];\n\tstderr: string;\n\tusage: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t\tcontextTokens: number;\n\t\tturns: number;\n\t};\n\tmodel?: string;\n\tstopReason?: string;\n\terrorMessage?: string;\n\tstep?: number;\n\tfailureStage?: string;\n\tdiagnosticMessage?: string;\n}\n\ninterface SubagentDetails {\n\tmode: \"single\" | \"parallel\" | \"chain\";\n\tagentScope: string;\n\tprojectAgentsDir: string | null;\n\tdiscoveryErrors: unknown[];\n\tresults: SubagentResult[];\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null;\n}\n\nfunction createDelegatedTask(options: {\n\ttoolCallId: string;\n\tagent: string;\n\ttask: string;\n\tmode: DelegatedMode;\n\tchildIndex?: number;\n\tstep?: number;\n\trawArgs: Record<string, unknown>;\n\ttimestamp: number;\n}): DelegatedTask {\n\treturn {\n\t\ttoolCallId: options.toolCallId,\n\t\tchildIndex: options.childIndex,\n\t\tagent: options.agent,\n\t\tagentSource: \"unknown\",\n\t\ttask: options.task,\n\t\tmode: options.mode,\n\t\tstatus: \"active\",\n\t\tstep: options.step,\n\t\trawArgs: options.rawArgs,\n\t\ttimestamp: options.timestamp,\n\t};\n}\n\n/**\n * Extract delegated work items from a subagent tool call event.\n *\n * Honesty boundary:\n * - single mode -> one active child entry\n * - parallel mode -> one active child entry per requested child task\n * - chain mode -> only the first step is active at tool-call start\n */\nexport function extractDelegatedTasks(event: ToolCallEvent): DelegatedTask[] {\n\tif (event.toolName !== \"subagent\") {\n\t\treturn [];\n\t}\n\n\tconst input = event.input;\n\tif (!isRecord(input)) {\n\t\treturn [];\n\t}\n\n\tconst params = input;\n\tconst timestamp = Date.now();\n\n\tif (Array.isArray(params.tasks) && params.tasks.length > 0) {\n\t\treturn params.tasks.flatMap((item, index) => {\n\t\t\tif (!isRecord(item)) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst agent = typeof item.agent === \"string\" ? item.agent : undefined;\n\t\t\tconst task = typeof item.task === \"string\" ? item.task : undefined;\n\t\t\tif (!agent || !task) {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\treturn [\n\t\t\t\tcreateDelegatedTask({\n\t\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\t\tagent,\n\t\t\t\t\ttask,\n\t\t\t\t\tmode: \"parallel\",\n\t\t\t\t\tchildIndex: index + 1,\n\t\t\t\t\trawArgs: params,\n\t\t\t\t\ttimestamp,\n\t\t\t\t}),\n\t\t\t];\n\t\t});\n\t}\n\n\tif (Array.isArray(params.chain) && params.chain.length > 0) {\n\t\tconst first = params.chain[0];\n\t\tif (!isRecord(first)) {\n\t\t\treturn [];\n\t\t}\n\t\tconst agent = typeof first.agent === \"string\" ? first.agent : undefined;\n\t\tconst task = typeof first.task === \"string\" ? first.task : undefined;\n\t\tif (!agent || !task) {\n\t\t\treturn [];\n\t\t}\n\t\treturn [\n\t\t\tcreateDelegatedTask({\n\t\t\t\ttoolCallId: event.toolCallId,\n\t\t\t\tagent,\n\t\t\t\ttask,\n\t\t\t\tmode: \"chain\",\n\t\t\t\tstep: 1,\n\t\t\t\trawArgs: params,\n\t\t\t\ttimestamp,\n\t\t\t}),\n\t\t];\n\t}\n\n\tconst agent = typeof params.agent === \"string\" ? params.agent : undefined;\n\tconst task = typeof params.task === \"string\" ? params.task : undefined;\n\tif (!agent || !task) {\n\t\treturn [];\n\t}\n\n\treturn [\n\t\tcreateDelegatedTask({\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\tagent,\n\t\t\ttask,\n\t\t\tmode: \"single\",\n\t\t\trawArgs: params,\n\t\t\ttimestamp,\n\t\t}),\n\t];\n}\n\n/**\n * Backwards-compatible singular helper.\n *\n * Returns the first extracted delegated task, which preserves prior single-task\n * helper behavior for callers that only need a representative entry.\n */\nexport function extractDelegatedTask(event: ToolCallEvent): DelegatedTask | undefined {\n\treturn extractDelegatedTasks(event)[0];\n}\n\n/**\n * Extract output preview from subagent messages.\n * Looks for the final assistant text content.\n */\nfunction extractOutputPreview(messages: unknown[]): string | undefined {\n\tif (!Array.isArray(messages) || messages.length === 0) {\n\t\treturn undefined;\n\t}\n\n\t// Find last assistant message with text\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i] as Record<string, unknown>;\n\t\tif (msg.role !== \"assistant\") continue;\n\n\t\tconst content = msg.content;\n\t\tif (!Array.isArray(content)) continue;\n\n\t\tfor (let j = content.length - 1; j >= 0; j--) {\n\t\t\tconst part = content[j] as Record<string, unknown>;\n\t\t\tif (part.type === \"text\" && typeof part.text === \"string\") {\n\t\t\t\tconst text = part.text.trim();\n\t\t\t\tif (text.length > 0) {\n\t\t\t\t\t// Return first 200 chars for preview\n\t\t\t\t\treturn text.length > 200 ? `${text.slice(0, 200)}...` : text;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn undefined;\n}\n\nfunction getTaskIdentity(task: DelegatedTask): string {\n\treturn `${task.toolCallId}:${task.mode}:${task.childIndex ?? \"single\"}:${task.step ?? \"-\"}`;\n}\n\nfunction getMatchingResult(task: DelegatedTask, results: SubagentResult[]): SubagentResult | undefined {\n\tif (task.mode === \"single\") {\n\t\treturn results[0];\n\t}\n\n\tif (task.mode === \"parallel\") {\n\t\treturn task.childIndex ? results[task.childIndex - 1] : undefined;\n\t}\n\n\tif (task.step !== undefined) {\n\t\treturn results.find((result) => result.step === task.step) ?? results[task.step - 1];\n\t}\n\n\treturn results.find((result) => result.agent === task.agent && result.task === task.task);\n}\n\nfunction getToolResultText(toolResult: ToolResultMessage): string | undefined {\n\tconst textContent = toolResult.content.find((content) => content.type === \"text\");\n\tif (!textContent || textContent.type !== \"text\") {\n\t\treturn undefined;\n\t}\n\tconst text = textContent.text.trim();\n\treturn text.length > 0 ? text.slice(0, 200) : undefined;\n}\n\nfunction isBlockedSubagentResult(result: SubagentResult): boolean {\n\treturn result.stopReason === \"aborted\";\n}\n\nfunction isBlockedToolResultWithoutChildResults(toolResult: ToolResultMessage, details: SubagentDetails): boolean {\n\tif (details.results.length > 0) {\n\t\treturn false;\n\t}\n\n\tconst text = getToolResultText(toolResult);\n\tif (!text) {\n\t\treturn false;\n\t}\n\n\treturn /(cancel(?:ed|led)|blocked|denied|refused|not approved|approval required|permission required)/iu.test(text);\n}\n\nfunction getDelegatedStatus(result: SubagentResult): DelegatedStatus {\n\tif (isBlockedSubagentResult(result)) {\n\t\treturn \"blocked\";\n\t}\n\tif (result.exitCode === -1 && !result.failureStage) {\n\t\treturn \"active\";\n\t}\n\tif (result.stopReason === \"error\" || result.exitCode !== 0 || result.failureStage) {\n\t\treturn \"error\";\n\t}\n\treturn \"completed\";\n}\n\nfunction getDelegatedErrorMessage(result: SubagentResult, toolResult: ToolResultMessage): string | undefined {\n\tif (result.diagnosticMessage) {\n\t\treturn result.diagnosticMessage;\n\t}\n\tif (result.errorMessage) {\n\t\treturn result.errorMessage;\n\t}\n\tif (result.stderr?.trim()) {\n\t\treturn result.stderr.trim();\n\t}\n\tif (toolResult.isError || isBlockedSubagentResult(result)) {\n\t\treturn getToolResultText(toolResult);\n\t}\n\treturn undefined;\n}\n\nfunction createDelegatedTaskFromResult(options: {\n\ttoolCallId: string;\n\tmode: DelegatedMode;\n\tresult: SubagentResult;\n\ttoolResult: ToolResultMessage;\n\trawArgs?: Record<string, unknown>;\n\ttimestamp: number;\n\tchildIndex?: number;\n\tstep?: number;\n}): DelegatedTask {\n\treturn {\n\t\ttoolCallId: options.toolCallId,\n\t\tchildIndex: options.childIndex,\n\t\tagent: options.result.agent,\n\t\tagentSource: options.result.agentSource,\n\t\ttask: options.result.task,\n\t\tmode: options.mode,\n\t\tstatus: getDelegatedStatus(options.result),\n\t\tstep: options.step,\n\t\texitCode: options.result.exitCode,\n\t\terrorMessage: getDelegatedErrorMessage(options.result, options.toolResult),\n\t\toutputPreview: extractOutputPreview(options.result.messages),\n\t\trawArgs: options.rawArgs,\n\t\ttimestamp: options.timestamp,\n\t};\n}\n\nfunction extractChainTaskInput(\n\trawArgs: Record<string, unknown> | undefined,\n\tstep: number,\n): Record<string, unknown> | undefined {\n\tconst chain = rawArgs?.chain;\n\tif (!Array.isArray(chain)) {\n\t\treturn undefined;\n\t}\n\tconst item = chain[step - 1];\n\treturn isRecord(item) ? item : undefined;\n}\n\nexport function reconcileDelegatedResult(tasks: DelegatedTask[], result: ToolResultMessage): DelegatedTask[] {\n\tif (result.toolName !== \"subagent\") {\n\t\treturn tasks;\n\t}\n\n\tconst details = result.details as SubagentDetails | undefined;\n\tif (!details || !Array.isArray(details.results)) {\n\t\treturn tasks;\n\t}\n\n\tlet nextTasks = [...tasks];\n\tconst matchingTasks = nextTasks.filter((task) => task.toolCallId === result.toolCallId);\n\tconst parentTask = matchingTasks[0];\n\tconst timestamp = parentTask?.timestamp ?? Date.now();\n\tconst rawArgs = parentTask?.rawArgs;\n\n\tif (isBlockedToolResultWithoutChildResults(result, details)) {\n\t\tconst errorMessage = getToolResultText(result);\n\t\tfor (const task of matchingTasks) {\n\t\t\tif (task.status !== \"active\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tnextTasks = mergeDelegatedTask(nextTasks, {\n\t\t\t\t...task,\n\t\t\t\tstatus: \"blocked\",\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t}\n\t\treturn nextTasks;\n\t}\n\n\tif (details.mode === \"chain\") {\n\t\tfor (let index = 0; index < details.results.length; index++) {\n\t\t\tconst childResult = details.results[index];\n\t\t\tconst step = childResult.step ?? index + 1;\n\t\t\tconst existingTask = matchingTasks.find((task) => task.mode === \"chain\" && task.step === step);\n\t\t\tconst taskInput = extractChainTaskInput(rawArgs, step);\n\t\t\tconst task =\n\t\t\t\texistingTask ??\n\t\t\t\tcreateDelegatedTask({\n\t\t\t\t\ttoolCallId: result.toolCallId,\n\t\t\t\t\tagent: typeof taskInput?.agent === \"string\" ? taskInput.agent : childResult.agent,\n\t\t\t\t\ttask: typeof taskInput?.task === \"string\" ? taskInput.task : childResult.task,\n\t\t\t\t\tmode: \"chain\",\n\t\t\t\t\tstep,\n\t\t\t\t\trawArgs: rawArgs ?? {},\n\t\t\t\t\ttimestamp,\n\t\t\t\t});\n\t\t\tnextTasks = mergeDelegatedTask(\n\t\t\t\tnextTasks,\n\t\t\t\tcreateDelegatedTaskFromResult({\n\t\t\t\t\ttoolCallId: result.toolCallId,\n\t\t\t\t\tmode: \"chain\",\n\t\t\t\t\tresult: childResult,\n\t\t\t\t\ttoolResult: result,\n\t\t\t\t\trawArgs: task.rawArgs,\n\t\t\t\t\ttimestamp: task.timestamp,\n\t\t\t\t\tstep,\n\t\t\t\t}),\n\t\t\t);\n\t\t}\n\t\treturn nextTasks;\n\t}\n\n\tfor (const currentTask of matchingTasks) {\n\t\tconst updatedTask = applyDelegatedResult(currentTask, result);\n\t\tif (updatedTask) {\n\t\t\tnextTasks = mergeDelegatedTask(nextTasks, updatedTask);\n\t\t}\n\t}\n\n\treturn nextTasks;\n}\n\n/**\n * Update a delegated task with result data from a persisted ToolResultMessage.\n * Returns the updated task or undefined if this result doesn't match.\n */\nexport function applyDelegatedResult(task: DelegatedTask, result: ToolResultMessage): DelegatedTask | undefined {\n\t// Only process subagent results\n\tif (result.toolName !== \"subagent\") {\n\t\treturn undefined;\n\t}\n\n\t// Verify this result is for our tool call\n\tif (result.toolCallId !== task.toolCallId) {\n\t\treturn undefined;\n\t}\n\n\tconst details = result.details as SubagentDetails | undefined;\n\tif (!details || !Array.isArray(details.results)) {\n\t\t// Result exists but no details yet (still running)\n\t\treturn task;\n\t}\n\n\tconst matchingResult = getMatchingResult(task, details.results);\n\tif (!matchingResult) {\n\t\t// Still waiting for our result\n\t\treturn task;\n\t}\n\n\treturn {\n\t\t...task,\n\t\tagent: matchingResult.agent,\n\t\ttask: matchingResult.task,\n\t\tagentSource: matchingResult.agentSource,\n\t\texitCode: matchingResult.exitCode,\n\t\tstatus: getDelegatedStatus(matchingResult),\n\t\terrorMessage: getDelegatedErrorMessage(matchingResult, result),\n\t\toutputPreview: extractOutputPreview(matchingResult.messages),\n\t\tstep: task.mode === \"chain\" ? (matchingResult.step ?? task.step) : task.step,\n\t};\n}\n\n/**\n * Build a summary of delegated work state.\n */\nexport function buildDelegatedWorkSummary(tasks: DelegatedTask[]): DelegatedWorkSummary {\n\tconst active: DelegatedTask[] = [];\n\tconst completed: DelegatedTask[] = [];\n\tconst failed: DelegatedTask[] = [];\n\n\tfor (const task of tasks) {\n\t\tif (task.status === \"active\") {\n\t\t\tactive.push(task);\n\t\t} else if (task.status === \"completed\") {\n\t\t\tcompleted.push(task);\n\t\t} else {\n\t\t\tfailed.push(task);\n\t\t}\n\t}\n\n\treturn {\n\t\tactive,\n\t\tcompleted,\n\t\tfailed,\n\t\ttotal: tasks.length,\n\t\tisSessionState: true,\n\t\tnote: \"ephemeral current-session state; not persisted across sessions or branches\",\n\t};\n}\n\n/**\n * Get the most recent tasks, optionally filtered by status.\n */\nexport function getRecentDelegatedTasks(\n\ttasks: DelegatedTask[],\n\toptions?: {\n\t\tstatus?: DelegatedStatus;\n\t\tlimit?: number;\n\t},\n): DelegatedTask[] {\n\tlet filtered = tasks;\n\n\tif (options?.status) {\n\t\tfiltered = tasks.filter((t) => t.status === options.status);\n\t}\n\n\t// Sort by timestamp descending (most recent first)\n\tconst sorted = [...filtered].sort((a, b) => b.timestamp - a.timestamp);\n\n\tif (options?.limit !== undefined && options.limit > 0) {\n\t\treturn sorted.slice(0, options.limit);\n\t}\n\n\treturn sorted;\n}\n\n/**\n * Merge a new task into the existing task list.\n * If a task with the same logical identity exists, it is replaced.\n */\nexport function mergeDelegatedTask(tasks: DelegatedTask[], newTask: DelegatedTask): DelegatedTask[] {\n\tconst newIdentity = getTaskIdentity(newTask);\n\tconst existing = tasks.findIndex((task) => getTaskIdentity(task) === newIdentity);\n\tif (existing >= 0) {\n\t\tconst updated = [...tasks];\n\t\tupdated[existing] = newTask;\n\t\treturn updated;\n\t}\n\treturn [...tasks, newTask];\n}\n\n/**\n * Synchronize task states with persisted tool results.\n * This is the main reconciliation function that:\n * 1. Activates tasks from tool call events\n * 2. Updates tasks with result data\n *\n * Returns the updated task list.\n */\nexport function syncDelegatedWork(\n\ttasks: DelegatedTask[],\n\ttoolCallEvents: ToolCallEvent[],\n\ttoolResultMessages: ToolResultMessage[],\n): DelegatedTask[] {\n\tlet result = [...tasks];\n\n\t// Process tool calls to activate tasks\n\tfor (const event of toolCallEvents) {\n\t\tfor (const task of extractDelegatedTasks(event)) {\n\t\t\tresult = mergeDelegatedTask(result, task);\n\t\t}\n\t}\n\n\t// Process results to update task states\n\tfor (const resultMsg of toolResultMessages) {\n\t\tresult = reconcileDelegatedResult(result, resultMsg);\n\t}\n\n\treturn result;\n}\n"]}