@agimon-ai/doompi-task 0.0.1-alpha.24 → 0.0.1-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +2 -2
  2. package/dist/adapters/pi/extension.cjs +2 -2
  3. package/dist/adapters/pi/extension.cjs.map +1 -1
  4. package/dist/adapters/pi/extension.d.cts +1 -1
  5. package/dist/adapters/pi/extension.d.cts.map +1 -1
  6. package/dist/adapters/pi/extension.d.mts +2 -2
  7. package/dist/adapters/pi/extension.d.mts.map +1 -1
  8. package/dist/adapters/pi/extension.mjs +2 -2
  9. package/dist/adapters/pi/extension.mjs.map +1 -1
  10. package/dist/commands/index.cjs +1 -1
  11. package/dist/commands/index.cjs.map +1 -1
  12. package/dist/commands/index.d.cts +2 -2
  13. package/dist/commands/index.d.cts.map +1 -1
  14. package/dist/commands/index.d.mts +2 -2
  15. package/dist/commands/index.d.mts.map +1 -1
  16. package/dist/commands/index.mjs +1 -1
  17. package/dist/commands/index.mjs.map +1 -1
  18. package/dist/commands/task/taskTool.cjs +1 -1
  19. package/dist/commands/task/taskTool.cjs.map +1 -1
  20. package/dist/commands/task/taskTool.d.cts +2 -1
  21. package/dist/commands/task/taskTool.d.cts.map +1 -1
  22. package/dist/commands/task/taskTool.d.mts +2 -1
  23. package/dist/commands/task/taskTool.d.mts.map +1 -1
  24. package/dist/commands/task/taskTool.mjs +1 -1
  25. package/dist/commands/task/taskTool.mjs.map +1 -1
  26. package/dist/services/delegation/manager.cjs +3 -3
  27. package/dist/services/delegation/manager.cjs.map +1 -1
  28. package/dist/services/delegation/manager.d.cts +15 -11
  29. package/dist/services/delegation/manager.d.cts.map +1 -1
  30. package/dist/services/delegation/manager.d.mts +15 -11
  31. package/dist/services/delegation/manager.d.mts.map +1 -1
  32. package/dist/services/delegation/manager.mjs +3 -3
  33. package/dist/services/delegation/manager.mjs.map +1 -1
  34. package/dist/services/narration/taskNarration.cjs.map +1 -1
  35. package/dist/services/narration/taskNarration.mjs.map +1 -1
  36. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"taskTool.mjs","names":[],"sources":["../../../src/commands/task/taskTool.ts"],"sourcesContent":["import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport {\n MSG_UPSERT_FIELD_MISPLACED,\n TaskParamsSchema,\n TOOL_LABEL,\n TOOL_NAME,\n taskActionAcceptsField,\n} from '../../schemas/task.ts';\nimport type { AssignOptions, DelegationManager, DelegationOutcome } from '../../services/delegation/manager.ts';\nimport { applyTaskMutation, isCommittingOp, type ReducerAction } from '../../services/store/reducer.ts';\nimport type { TaskStore } from '../../adapters/store/taskStore';\nimport type { TaskAction, TaskAssignment, TaskMutationParams } from '../../services/store/types.ts';\nimport { renderTaskCall, renderTaskResult } from '../../tui/format.ts';\nimport { DEFAULT_MAX_TASKS } from '../../types/config.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry.ts';\nimport { DEFAULT_PROMPT_GUIDELINES } from './promptGuidelines.ts';\nimport {\n type AssignmentItemResult,\n buildAssignmentResult,\n buildTextResult,\n buildToolResult,\n formatAssignmentResults,\n formatUpsertFailureText,\n type ToolResult,\n} from './responseEnvelope.ts';\n\nexport { DEFAULT_PROMPT_GUIDELINES } from './promptGuidelines.ts';\n\nexport const DEFAULT_PROMPT_SNIPPET =\n 'Manage a shared task list to track multi-step progress, and delegate tasks to subagents';\n\nexport interface TaskToolDependencies {\n store: TaskStore;\n delegation: DelegationManager;\n maxTasks?: number;\n onChange?: () => void;\n report?: TaskFailureReporter;\n}\n\nconst ACTION_ATTRIBUTE = 'tool.action';\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REDUCER_ACTIONS = new Set<TaskAction>(['upsert', 'list', 'get', 'delete', 'clear']);\n\nclass TaskToolExecutionError extends Error {}\n\nfunction actionableTaskError(action: TaskAction, message: string): TaskToolExecutionError {\n return new TaskToolExecutionError(\n [\n `Task ${action} failed: ${message}`,\n '',\n 'Options:',\n '- List the task board and inspect the current ids, states, and blockers.',\n '- Correct the arguments or state conflict, then retry once.',\n '- Ask the user before cancelling work or changing dependencies to recover.',\n ].join('\\n'),\n );\n}\n\n/**\n * Reject a field that belongs to a different action.\n *\n * The params schema is flat and shared across every action, so this is the only\n * place `{\"action\":\"upsert\",\"id\":3}` can be caught — and it must be, because\n * the entry it carries has no id and would silently create a duplicate task.\n */\nfunction rejectStrayFields(action: TaskAction, params: TaskMutationParams): void {\n const stray = Object.keys(params).filter((key) => params[key] !== undefined && !taskActionAcceptsField(action, key));\n if (stray.length === 0) return;\n const hint = action === 'upsert' ? ` ${MSG_UPSERT_FIELD_MISPLACED}` : '';\n throw actionableTaskError(action, `${action} does not accept ${stray.join(', ')}.${hint}`);\n}\n\n/** assignments[] is the only assign contract, even when it contains one task. */\nfunction resolveAssignments(params: TaskMutationParams): TaskAssignment[] {\n const assignments = params.assignments;\n if (!assignments || assignments.length === 0) {\n throw actionableTaskError('assign', 'assign requires a non-empty assignments[] array');\n }\n return assignments;\n}\n\nfunction assignOptions(request: TaskAssignment, signal: AbortSignal | undefined): AssignOptions {\n return {\n agent: request.agent,\n inlineAgent: request.inlineAgent,\n instructions: request.instructions,\n relevantFiles: request.relevantFiles,\n priorFindings: request.priorFindings,\n model: request.model,\n context: request.context,\n signal,\n };\n}\n\nasync function executeAssignmentBatch(\n delegation: DelegationManager,\n assignments: readonly TaskAssignment[],\n signal: AbortSignal | undefined,\n report: TaskFailureReporter | undefined,\n): Promise<AssignmentItemResult[]> {\n const results: AssignmentItemResult[] = [];\n for (const [index, assignment] of assignments.entries()) {\n let outcome: DelegationOutcome;\n try {\n outcome = await delegation.assign(assignment.id, assignOptions(assignment, signal));\n } catch (error) {\n report?.error(TASK_EVENT.toolFailed, error, {\n [ACTION_ATTRIBUTE]: 'assign',\n [TASK_ID_ATTRIBUTE]: assignment.id,\n });\n outcome = { ok: false, message: error instanceof Error ? error.message : String(error) };\n }\n results.push({ index, id: assignment.id, agent: assignment.agent, ...outcome });\n }\n return results;\n}\n\n/** Run an action through the reducer, persisting only when it produced a change. */\nasync function executeReducerAction(\n store: TaskStore,\n action: ReducerAction,\n params: TaskMutationParams,\n maxTasks: number,\n): Promise<ToolResult> {\n const { document, value } = await store.mutate((current) => {\n const result = applyTaskMutation(current, action, params, undefined, maxTasks);\n return {\n ...(isCommittingOp(result.op) ? { document: result.document } : {}),\n value: result,\n };\n });\n if (value.op.kind === 'error') throw actionableTaskError(action, value.op.message);\n // An upsert that applied nothing is a failed call: it wrote nothing and left\n // `rev` alone, so it must not read to the model as a success. A batch where\n // some entries landed returns normally — that is what partial apply means.\n if (value.op.kind === 'upsert' && value.op.applied === 0) {\n throw actionableTaskError(action, formatUpsertFailureText(value.op));\n }\n // `document` is the committed document, so `details.rev` matches what landed\n // on disk; `value.document` is the pre-write copy and lags by one.\n return buildToolResult(action, params, document, value.op);\n}\n\nexport function registerTaskTool(pi: ExtensionAPI, dependencies: TaskToolDependencies): void {\n const { store, delegation, maxTasks = DEFAULT_MAX_TASKS } = dependencies;\n\n pi.registerTool({\n name: TOOL_NAME,\n label: TOOL_LABEL,\n description:\n 'Manage a shared task list for tracking multi-step progress, and delegate tasks to subagents. Actions: upsert (write tasks — a tasks[] array where an entry with an id changes that task and an entry without an id creates one, so one call can capture a whole plan), list, get, delete (tombstone), clear (close/reset the list), assign (hand one or more tasks through assignments[] to named subagents that work in the background), cancel (stop a delegated run). upsert and assign apply entries independently: successes remain committed or delegated and failures are reported by array index. Batch a plan and independent assignments, but report progress one task at a time. Status: pending → in_progress → completed, plus failed and a deleted tombstone. The list is shared within the current session tree, including delegated subagents, while unrelated sessions start empty. Session stores persist until retention cleanup.',\n promptSnippet: DEFAULT_PROMPT_SNIPPET,\n promptGuidelines: DEFAULT_PROMPT_GUIDELINES,\n parameters: TaskParamsSchema,\n // Task rows carry their own status colors. Owning the shell prevents Pi's\n // pending/success/error background fill from obscuring those row states.\n renderShell: 'self',\n\n async execute(_toolCallId, params, signal, onUpdate, _ctx) {\n const action = params.action as TaskAction;\n const mutationParams = params as TaskMutationParams;\n\n try {\n rejectStrayFields(action, mutationParams);\n if (REDUCER_ACTIONS.has(action)) {\n const result = await executeReducerAction(store, action as ReducerAction, mutationParams, maxTasks);\n dependencies.onChange?.();\n return result;\n }\n\n if (action === 'assign') {\n const assignments = resolveAssignments(mutationParams);\n const first = assignments[0];\n const progress =\n assignments.length === 1 && first\n ? `Delegating task #${first.id}...`\n : `Delegating ${assignments.length} tasks...`;\n onUpdate?.(buildTextResult(action, mutationParams, store.snapshot, progress));\n const results = await executeAssignmentBatch(delegation, assignments, signal, dependencies.report);\n dependencies.onChange?.();\n const text = formatAssignmentResults(results);\n const assigned = results.flatMap((item) => (item.ok ? [item.id] : []));\n if (assigned.length === 0) throw actionableTaskError(action, text);\n return buildAssignmentResult(mutationParams, store.snapshot, text, {\n assigned,\n failed: results.length - assigned.length,\n });\n }\n\n onUpdate?.(\n buildTextResult(\n action,\n mutationParams,\n store.snapshot,\n `Requesting cancellation for task #${mutationParams.id ?? 'unknown'}...`,\n ),\n );\n const outcome = await delegation.cancel(mutationParams.id ?? Number.NaN);\n dependencies.onChange?.();\n if (!outcome.ok) throw actionableTaskError(action, outcome.message);\n return buildTextResult(action, mutationParams, store.snapshot, outcome.message, undefined);\n } catch (error) {\n // Rethrown so pi still renders the failure to the model; recorded\n // because this is where a store fault becomes visible to the user.\n dependencies.report?.error(TASK_EVENT.toolFailed, error, {\n [ACTION_ATTRIBUTE]: action,\n ...(mutationParams.id === undefined ? {} : { [TASK_ID_ATTRIBUTE]: mutationParams.id }),\n });\n if (error instanceof TaskToolExecutionError) throw error;\n throw actionableTaskError(action, error instanceof Error ? error.message : String(error));\n }\n },\n\n // Render hooks receive no session identity, so they read the store snapshot\n // that the executing session last loaded. That is the foreground session's\n // own view, which is exactly what its transcript should show.\n renderCall(args, theme, _context) {\n return renderTaskCall(args as never, theme, store.snapshot.tasks);\n },\n\n renderResult(result, options, theme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,EAAiB,EAAQ,EAAS,CAAK,CAChD,CACF,CAAC,CACH"}
1
+ {"version":3,"file":"taskTool.mjs","names":[],"sources":["../../../src/commands/task/taskTool.ts"],"sourcesContent":["import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport {\n MSG_UPSERT_FIELD_MISPLACED,\n TaskParamsSchema,\n TOOL_LABEL,\n TOOL_NAME,\n taskActionAcceptsField,\n} from '../../schemas/task.ts';\nimport type { AssignOptions, DelegationManager, DelegationOutcome } from '../../services/delegation/manager.ts';\nimport { applyTaskMutation, isCommittingOp, type ReducerAction } from '../../services/store/reducer.ts';\nimport type { TaskStore } from '../../adapters/store/taskStore';\nimport type { TaskAction, TaskAssignment, TaskMutationParams } from '../../services/store/types.ts';\nimport { renderTaskCall, renderTaskResult } from '../../tui/format.ts';\nimport { DEFAULT_MAX_TASKS } from '../../types/config.ts';\nimport { TASK_EVENT, type TaskFailureReporter } from '../../types/telemetry.ts';\nimport { DEFAULT_PROMPT_GUIDELINES } from './promptGuidelines.ts';\nimport {\n type AssignmentItemResult,\n buildAssignmentResult,\n buildTextResult,\n buildToolResult,\n formatAssignmentResults,\n formatUpsertFailureText,\n type ToolResult,\n} from './responseEnvelope.ts';\n\nexport { DEFAULT_PROMPT_GUIDELINES } from './promptGuidelines.ts';\n\nexport const DEFAULT_PROMPT_SNIPPET =\n 'Manage a shared task list to track multi-step progress, and delegate tasks to subagents';\n\nexport interface TaskToolDependencies {\n store: TaskStore;\n delegation: DelegationManager;\n maxTasks?: number;\n onChange?: () => void;\n report?: TaskFailureReporter;\n waitUntilReady?: (context: ExtensionContext, signal?: AbortSignal) => Promise<void>;\n}\n\nconst ACTION_ATTRIBUTE = 'tool.action';\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REDUCER_ACTIONS = new Set<TaskAction>(['upsert', 'list', 'get', 'delete', 'clear']);\n\nclass TaskToolExecutionError extends Error {}\n\nfunction actionableTaskError(action: TaskAction, message: string): TaskToolExecutionError {\n return new TaskToolExecutionError(\n [\n `Task ${action} failed: ${message}`,\n '',\n 'Options:',\n '- List the task board and inspect the current ids, states, and blockers.',\n '- Correct the arguments or state conflict, then retry once.',\n '- Ask the user before cancelling work or changing dependencies to recover.',\n ].join('\\n'),\n );\n}\n\n/**\n * Reject a field that belongs to a different action.\n *\n * The params schema is flat and shared across every action, so this is the only\n * place `{\"action\":\"upsert\",\"id\":3}` can be caught — and it must be, because\n * the entry it carries has no id and would silently create a duplicate task.\n */\nfunction rejectStrayFields(action: TaskAction, params: TaskMutationParams): void {\n const stray = Object.keys(params).filter((key) => params[key] !== undefined && !taskActionAcceptsField(action, key));\n if (stray.length === 0) return;\n const hint = action === 'upsert' ? ` ${MSG_UPSERT_FIELD_MISPLACED}` : '';\n throw actionableTaskError(action, `${action} does not accept ${stray.join(', ')}.${hint}`);\n}\n\n/** assignments[] is the only assign contract, even when it contains one task. */\nfunction resolveAssignments(params: TaskMutationParams): TaskAssignment[] {\n const assignments = params.assignments;\n if (!assignments || assignments.length === 0) {\n throw actionableTaskError('assign', 'assign requires a non-empty assignments[] array');\n }\n return assignments;\n}\n\nfunction assignOptions(request: TaskAssignment, signal: AbortSignal | undefined): AssignOptions {\n return {\n agent: request.agent,\n inlineAgent: request.inlineAgent,\n instructions: request.instructions,\n relevantFiles: request.relevantFiles,\n priorFindings: request.priorFindings,\n model: request.model,\n context: request.context,\n signal,\n };\n}\n\nasync function executeAssignmentBatch(\n delegation: DelegationManager,\n assignments: readonly TaskAssignment[],\n signal: AbortSignal | undefined,\n report: TaskFailureReporter | undefined,\n): Promise<AssignmentItemResult[]> {\n const results: AssignmentItemResult[] = [];\n for (const [index, assignment] of assignments.entries()) {\n let outcome: DelegationOutcome;\n try {\n outcome = await delegation.assign(assignment.id, assignOptions(assignment, signal));\n } catch (error) {\n report?.error(TASK_EVENT.toolFailed, error, {\n [ACTION_ATTRIBUTE]: 'assign',\n [TASK_ID_ATTRIBUTE]: assignment.id,\n });\n outcome = { ok: false, message: error instanceof Error ? error.message : String(error) };\n }\n results.push({ index, id: assignment.id, agent: assignment.agent, ...outcome });\n }\n return results;\n}\n\n/** Run an action through the reducer, persisting only when it produced a change. */\nasync function executeReducerAction(\n store: TaskStore,\n action: ReducerAction,\n params: TaskMutationParams,\n maxTasks: number,\n): Promise<ToolResult> {\n const { document, value } = await store.mutate((current) => {\n const result = applyTaskMutation(current, action, params, undefined, maxTasks);\n return {\n ...(isCommittingOp(result.op) ? { document: result.document } : {}),\n value: result,\n };\n });\n if (value.op.kind === 'error') throw actionableTaskError(action, value.op.message);\n // An upsert that applied nothing is a failed call: it wrote nothing and left\n // `rev` alone, so it must not read to the model as a success. A batch where\n // some entries landed returns normally — that is what partial apply means.\n if (value.op.kind === 'upsert' && value.op.applied === 0) {\n throw actionableTaskError(action, formatUpsertFailureText(value.op));\n }\n // `document` is the committed document, so `details.rev` matches what landed\n // on disk; `value.document` is the pre-write copy and lags by one.\n return buildToolResult(action, params, document, value.op);\n}\n\nexport function registerTaskTool(pi: ExtensionAPI, dependencies: TaskToolDependencies): void {\n const { store, delegation, maxTasks = DEFAULT_MAX_TASKS } = dependencies;\n\n pi.registerTool({\n name: TOOL_NAME,\n label: TOOL_LABEL,\n description:\n 'Manage a shared task list for tracking multi-step progress, and delegate tasks to subagents. Actions: upsert (write tasks — a tasks[] array where an entry with an id changes that task and an entry without an id creates one, so one call can capture a whole plan), list, get, delete (tombstone), clear (close/reset the list), assign (hand one or more tasks through assignments[] to named subagents that work in the background), cancel (stop a delegated run). upsert and assign apply entries independently: successes remain committed or delegated and failures are reported by array index. Batch a plan and independent assignments, but report progress one task at a time. Status: pending → in_progress → completed, plus failed and a deleted tombstone. The list is shared within the current session tree, including delegated subagents, while unrelated sessions start empty. Session stores persist until retention cleanup.',\n promptSnippet: DEFAULT_PROMPT_SNIPPET,\n promptGuidelines: DEFAULT_PROMPT_GUIDELINES,\n parameters: TaskParamsSchema,\n // Task rows carry their own status colors. Owning the shell prevents Pi's\n // pending/success/error background fill from obscuring those row states.\n renderShell: 'self',\n\n async execute(_toolCallId, params, signal, onUpdate, ctx) {\n const action = params.action as TaskAction;\n const mutationParams = params as TaskMutationParams;\n\n try {\n await dependencies.waitUntilReady?.(ctx, signal);\n rejectStrayFields(action, mutationParams);\n if (REDUCER_ACTIONS.has(action)) {\n const result = await executeReducerAction(store, action as ReducerAction, mutationParams, maxTasks);\n dependencies.onChange?.();\n return result;\n }\n\n if (action === 'assign') {\n const assignments = resolveAssignments(mutationParams);\n const first = assignments[0];\n const progress =\n assignments.length === 1 && first\n ? `Delegating task #${first.id}...`\n : `Delegating ${assignments.length} tasks...`;\n onUpdate?.(buildTextResult(action, mutationParams, store.snapshot, progress));\n const results = await executeAssignmentBatch(delegation, assignments, signal, dependencies.report);\n dependencies.onChange?.();\n const text = formatAssignmentResults(results);\n const assigned = results.flatMap((item) => (item.ok ? [item.id] : []));\n if (assigned.length === 0) throw actionableTaskError(action, text);\n return buildAssignmentResult(mutationParams, store.snapshot, text, {\n assigned,\n failed: results.length - assigned.length,\n });\n }\n\n onUpdate?.(\n buildTextResult(\n action,\n mutationParams,\n store.snapshot,\n `Requesting cancellation for task #${mutationParams.id ?? 'unknown'}...`,\n ),\n );\n const outcome = await delegation.cancel(mutationParams.id ?? Number.NaN);\n dependencies.onChange?.();\n if (!outcome.ok) throw actionableTaskError(action, outcome.message);\n return buildTextResult(action, mutationParams, store.snapshot, outcome.message, undefined);\n } catch (error) {\n // Rethrown so pi still renders the failure to the model; recorded\n // because this is where a store fault becomes visible to the user.\n dependencies.report?.error(TASK_EVENT.toolFailed, error, {\n [ACTION_ATTRIBUTE]: action,\n ...(mutationParams.id === undefined ? {} : { [TASK_ID_ATTRIBUTE]: mutationParams.id }),\n });\n if (error instanceof TaskToolExecutionError) throw error;\n throw actionableTaskError(action, error instanceof Error ? error.message : String(error));\n }\n },\n\n // Render hooks receive no session identity, so they read the store snapshot\n // that the executing session last loaded. That is the foreground session's\n // own view, which is exactly what its transcript should show.\n renderCall(args, theme, _context) {\n return renderTaskCall(args as never, theme, store.snapshot.tasks);\n },\n\n renderResult(result, options, theme, _context) {\n return renderTaskResult(result, options, theme);\n },\n });\n}\n"],"mappings":"unBA4BA,MAAa,EACX,0FAWI,EAAmB,cACnB,EAAoB,UACpB,EAAkB,IAAI,IAAgB,CAAC,SAAU,OAAQ,MAAO,SAAU,OAAO,CAAC,EAExF,IAAM,EAAN,cAAqC,KAAM,CAAC,EAE5C,SAAS,EAAoB,EAAoB,EAAyC,CACxF,OAAO,IAAI,EACT,CACE,QAAQ,EAAO,WAAW,IAC1B,GACA,WACA,2EACA,8DACA,4EACF,CAAC,CAAC,KAAK;CAAI,CACb,CACF,CASA,SAAS,EAAkB,EAAoB,EAAkC,CAC/E,IAAM,EAAQ,OAAO,KAAK,CAAM,CAAC,CAAC,OAAQ,GAAQ,EAAO,KAAS,IAAA,IAAa,CAAC,EAAuB,EAAQ,CAAG,CAAC,EACnH,GAAI,EAAM,SAAW,EAAG,OACxB,IAAM,EAAO,IAAW,SAAW,IAAI,IAA+B,GACtE,MAAM,EAAoB,EAAQ,GAAG,EAAO,mBAAmB,EAAM,KAAK,IAAI,EAAE,GAAG,GAAM,CAC3F,CAGA,SAAS,EAAmB,EAA8C,CACxE,IAAM,EAAc,EAAO,YAC3B,GAAI,CAAC,GAAe,EAAY,SAAW,EACzC,MAAM,EAAoB,SAAU,iDAAiD,EAEvF,OAAO,CACT,CAEA,SAAS,EAAc,EAAyB,EAAgD,CAC9F,MAAO,CACL,MAAO,EAAQ,MACf,YAAa,EAAQ,YACrB,aAAc,EAAQ,aACtB,cAAe,EAAQ,cACvB,cAAe,EAAQ,cACvB,MAAO,EAAQ,MACf,QAAS,EAAQ,QACjB,QACF,CACF,CAEA,eAAe,EACb,EACA,EACA,EACA,EACiC,CACjC,IAAM,EAAkC,CAAC,EACzC,IAAK,GAAM,CAAC,EAAO,KAAe,EAAY,QAAQ,EAAG,CACvD,IAAI,EACJ,GAAI,CACF,EAAU,MAAM,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EAAU,CAChC,OAAO,EAAe,EAAe,EAAO,EAAM,SAAS,KAAK,CAClE,EAEA,aAAa,EAAQ,EAAS,EAAO,EAAU,CAC7C,OAAO,EAAiB,EAAQ,EAAS,CAAK,CAChD,CACF,CAAC,CACH"}
@@ -1,6 +1,6 @@
1
- const e=require("../../types/delegation.cjs"),t=require("../store/taskGraph.cjs"),n=require("../store/types.cjs"),r=require("../../types/telemetry.cjs"),i=require("../store/reconcile.cjs");let a=require("@agimon-ai/doompi-extension-contracts/delegation"),o=require("@agimon-ai/doompi-extension-contracts/protocol");const s=`doom-task-notify`,c=`completed`,l=`failed`,u=`cancelled`,d=`task.id`,f=`delegation.request_id`,p=`delegation.agent_name`,m=`delegation.context_present`,h=`delegation.context_file_count`,g=`delegation.context_notes_length`,_=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,v=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,y=`Subagent did not acknowledge the cancel request`;function b(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function x(e){return e instanceof Error?e.message:String(e)}function S(e,t,n){let r=new Set;for(let i of e.relevantFiles??[]){if(r.size>=12)break;let e=n.formatBriefPath(i.trim(),t);e&&e!==`.`&&r.add(e)}return{files:[...r],notes:b(e.priorFindings?.trim(),1500)}}function C(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
1
+ const e=require("../../types/delegation.cjs"),t=require("../store/taskGraph.cjs"),n=require("../store/types.cjs"),r=require("../../types/telemetry.cjs"),i=require("../store/reconcile.cjs");let a=require("@agimon-ai/doompi-extension-contracts/delegation");const o=`doom-task-notify`,s=`completed`,c=`failed`,l=`cancelled`,u=`task.id`,d=`delegation.request_id`,f=`delegation.agent_name`,p=`delegation.context_present`,m=`delegation.context_file_count`,h=`delegation.context_notes_length`,g=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,_=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,v=`Subagent did not acknowledge the cancel request`;function y(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function b(e){return e instanceof Error?e.message:String(e)}function x(e,t,n){let r=new Set;for(let i of e.relevantFiles??[]){if(r.size>=12)break;let e=n.formatBriefPath(i.trim(),t);e&&e!==`.`&&r.add(e)}return{files:[...r],notes:y(e.priorFindings?.trim(),1500)}}function S(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
2
2
  `))}return r.push(`Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.`),r.join(`
3
3
 
4
- `)}var w=class e{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];protocol;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.options.platform.environment.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}start(){if(this.subscriptions.length>0)return;let e=this.options.getSessionId?.();e&&(this.protocol=(0,o.createProtocolRuntime)({bus:this.options.events,source:`@agimon-ai/doompi-task`,sessionId:e}),this.subscriptions.push(this.protocol.onNotification(a.DelegationAccepted,e=>{this.handleAccepted(e)}),this.protocol.onNotification(a.DelegationStarted,e=>{this.handleStarted(e)}),this.protocol.onNotification(a.DelegationUpdated,e=>{this.handleUpdate(e)}),this.protocol.onNotification(a.DelegationFinished,e=>{this.handleResponse(e).catch(t=>{this.report(r.TASK_EVENT.delegationResponseFailed,t,{[f]:e.requestId})})})))}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(e=()=>!0){let{value:t}=await this.options.store.mutate(t=>{if(!e())return{value:[]};let n=i.reconcileOrphanedDelegations(t,this.now(),void 0,{pid:this.options.platform.processId,liveRequestIds:new Set(this.pendingTasks.keys())});return n.orphaned.length===0?{value:[]}:{document:n.document,value:n.orphaned}});if(!e())return[];for(let e of t)this.options.report?.warn(r.TASK_EVENT.delegationOrphaned,Error(e.delegation?.result?.error??``),{[d]:e.id,...e.delegation?.agent?{[p]:e.delegation.agent}:{},...e.delegation?.pid===void 0?{}:{"delegation.pid":e.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(e,i){let o=i.agent?.trim();if(!o)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:v};if(i.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let s=this.options.platform.createRequestId(),u=this.now(),y=S(i,this.options.cwd,this.options.platform),{value:b}=await this.options.store.mutate(r=>{let a=r.tasks.findIndex(t=>t.id===e);if(a===-1)return{value:{ok:!1,message:`#${e} not found`}};let l=r.tasks[a];if(l.status===`deleted`)return{value:{ok:!1,message:`#${e} is deleted`}};if(l.status===c)return{value:{ok:!1,message:`#${e} is already completed`}};if(n.isDelegationActive(l))return{value:{ok:!1,message:`#${e} is already delegated to ${l.delegation?.agent}`}};if(t.isBlocked(r.tasks,l))return{value:{ok:!1,message:`#${e} is blocked by ${(l.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let d={requestId:s,agent:o,state:`requested`,pid:this.options.platform.processId,startedAt:u,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...i.model?{model:i.model}:{}},f=[...r.tasks];return f[a]={...l,owner:o,updatedAt:u,delegation:d},{document:{...r,tasks:f},value:{ok:!0,message:``,task:f[a]}}});if(!b.ok||!b.task)return{ok:!1,message:b.message};let w=y.notes?.length??0;this.pendingTasks.set(s,e),this.progress.set(s,{agent:o,contextFileCount:y.files.length,contextNotesLength:w}),this.armStartedTimeout(s);let T={requestId:s,taskId:e,agent:o,...i.inlineAgent?{inlineAgent:i.inlineAgent}:{},prompt:C(b.task,i.instructions,y),...i.context?{context:i.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(b.task.id),subject:b.task.subject},...i.model?{model:i.model}:{}};try{if(!this.protocol)throw Error(_);this.protocol.notify(a.DelegationRequested,T)}catch(t){this.report(r.TASK_EVENT.delegationRequestFailed,t,{[d]:e,[f]:s,[p]:o});let n=x(t);return await this.settle(s,l,{status:l,error:`Delegation request failed: ${n}`}),{ok:!1,message:`Could not dispatch #${e} to ${o}: ${n}`}}return this.options.report?.event(r.TASK_EVENT.delegationAssigned,{[d]:e,[f]:s,[p]:o,[m]:y.files.length>0||w>0,[h]:y.files.length,[g]:w,"delegation.brief_length":T.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${e} to ${o} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!n.isDelegationActive(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:r}=t.delegation;return this.protocol?.notify(a.DelegationCancelled,{requestId:r}),this.armCancelTimeout(r),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,t,n,i=r.TASK_EVENT.delegationSettleFailed){this.settle(e,t,n).catch(t=>{this.report(i,t,{[f]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,l,{status:l,error:_})})}armRunTimeout(e){let t=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+t,()=>{let t=this.pendingTasks.get(e),n=this.progress.get(e)?.agent,i=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(r.TASK_EVENT.delegationTimedOut,i,{...t===void 0?{}:{[d]:t},[f]:e,...n?{[p]:n}:{}}),this.protocol?.notify(a.DelegationCancelled,{requestId:e,reason:i.message}),this.settleDetached(e,l,{status:`timed_out`,error:i.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,u,{status:u,error:y})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:t}=e,n=this.pendingTasks.get(e.requestId);if(n===void 0)return;this.armRunTimeout(e.requestId);let i=this.progress.get(e.requestId);i&&this.progress.set(e.requestId,{...i,durationMs:i.durationMs??0,durationObservedAt:i.durationObservedAt??this.nowMs()}),this.options.store.mutate(n=>this.patchDelegation(n,e.requestId,(e,n)=>({...e,status:e.status===c?e.status:`in_progress`,delegation:{...n,state:`running`,startedAt:n.startedAt??this.now(),...t?{runId:t}:{}}}))).then(()=>this.options.onChange?.()).catch(t=>{this.report(r.TASK_EVENT.delegationStartFailed,t,{[d]:n,[f]:e.requestId})})}handleUpdate(t){let n=this.progress.get(t.requestId);if(!n)return;let r=this.nowMs(),i=e.elapsedMs(n,r),a=t.durationMs!==void 0;this.progress.set(t.requestId,{...n,currentTool:t.currentTool??n.currentTool,toolCount:t.toolCount===void 0?n.toolCount:Math.max(n.toolCount??0,t.toolCount),tokens:t.tokens===void 0?n.tokens:Math.max(n.tokens??0,t.tokens),durationMs:a?Math.max(i,t.durationMs):n.durationMs,durationObservedAt:a?r:n.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===c&&!e.error?c:e.status===u?u:l;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:b(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,n,i){let a=this.pendingTasks.get(e);if(a===void 0)return;this.pendingTasks.delete(e),this.clearTimer(e);let o=this.progress.get(e);this.progress.delete(e);let s=this.now(),_;try{let{value:t}=await this.options.store.mutate(t=>this.patchDelegation(t,e,(e,t)=>({...e,status:n===c?c:n===u?`pending`:l,updatedAt:s,delegation:{...t,state:n,endedAt:s,...i?{result:i}:{}}})));_=t}catch(t){this.report(r.TASK_EVENT.delegationSettleFailed,t,{[d]:a,[f]:e})}this.options.onChange?.();let v=_?.delegation?.agent??o?.agent??`subagent`,y=_?.subject??`#${a}`;this.options.report?.event(r.TASK_EVENT.delegationCompleted,{[d]:a,[f]:e,[p]:v,"delegation.outcome":n,[m]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[h]:o?.contextFileCount??0,[g]:o?.contextNotesLength??0,...i?.toolCount===void 0?{}:{"delegation.tool_count":i.toolCount},...i?.durationMs===void 0?{}:{"delegation.duration_ms":i.durationMs}});let b=n===c&&_!==void 0&&t.isTaskListComplete(this.options.store.snapshot.tasks);this.notifyModel(n,a,y,v,i,b)}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let l=[e===c?`Subagent ${r} completed task #${t}: ${n}`:e===u?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&l.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&l.push(`Error: ${i.error}`),i?.output&&l.push(``,i.output),i?.outputPath&&l.push(``,`Full output: ${i.outputPath}`);try{o({customType:s,content:l.join(`
5
- `),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,r){let i=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!n.isDelegationActive(a))return{value:a};let o=r(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){for(let e of this.subscriptions)e();this.subscriptions.length=0,this.protocol=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};exports.BACKGROUND_WORK_PROVIDER=`doom-task`,exports.DelegationManager=w,exports.ERR_CANCEL_UNACKNOWLEDGED=y,exports.ERR_CHILD_SESSION=v,exports.ERR_NO_RUNTIME=_,exports.MAX_BRIEF_FILES=e.MAX_BRIEF_FILES,exports.NOTIFY_CUSTOM_TYPE=s;
4
+ `)}var C=class e{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];service;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.options.platform.environment.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}bind(e,t){return this.unbind(),this.service=t,this.subscriptions.push(e.on(a.DOOM_DELEGATION_ACCEPTED_EVENT,e=>{this.handleAccepted(e)}),e.on(a.DOOM_DELEGATION_STARTED_EVENT,e=>{this.handleStarted(e)}),e.on(a.DOOM_DELEGATION_UPDATED_EVENT,e=>{this.handleUpdate(e)}),e.on(a.DOOM_DELEGATION_FINISHED_EVENT,e=>{this.handleResponse(e).catch(t=>{this.report(r.TASK_EVENT.delegationResponseFailed,t,{[d]:e.requestId})})})),()=>{this.service===t&&this.unbind()}}unbind(){for(let e of this.subscriptions.splice(0))e();this.service=void 0}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(e=()=>!0){let{value:t}=await this.options.store.mutate(t=>{if(!e())return{value:[]};let n=i.reconcileOrphanedDelegations(t,this.now(),void 0,{pid:this.options.platform.processId,liveRequestIds:new Set(this.pendingTasks.keys())});return n.orphaned.length===0?{value:[]}:{document:n.document,value:n.orphaned}});if(!e())return[];for(let e of t)this.options.report?.warn(r.TASK_EVENT.delegationOrphaned,Error(e.delegation?.result?.error??``),{[u]:e.id,...e.delegation?.agent?{[f]:e.delegation.agent}:{},...e.delegation?.pid===void 0?{}:{"delegation.pid":e.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(e,i){let a=i.agent?.trim();if(!a)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:_};if(i.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let o=this.options.platform.createRequestId(),l=this.now(),v=x(i,this.options.cwd,this.options.platform),{value:y}=await this.options.store.mutate(r=>{let c=r.tasks.findIndex(t=>t.id===e);if(c===-1)return{value:{ok:!1,message:`#${e} not found`}};let u=r.tasks[c];if(u.status===`deleted`)return{value:{ok:!1,message:`#${e} is deleted`}};if(u.status===s)return{value:{ok:!1,message:`#${e} is already completed`}};if(n.isDelegationActive(u))return{value:{ok:!1,message:`#${e} is already delegated to ${u.delegation?.agent}`}};if(t.isBlocked(r.tasks,u))return{value:{ok:!1,message:`#${e} is blocked by ${(u.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let d={requestId:o,agent:a,state:`requested`,pid:this.options.platform.processId,startedAt:l,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...i.model?{model:i.model}:{}},f=[...r.tasks];return f[c]={...u,owner:a,updatedAt:l,delegation:d},{document:{...r,tasks:f},value:{ok:!0,message:``,task:f[c]}}});if(!y.ok||!y.task)return{ok:!1,message:y.message};let C=v.notes?.length??0;this.pendingTasks.set(o,e),this.progress.set(o,{agent:a,contextFileCount:v.files.length,contextNotesLength:C}),this.armStartedTimeout(o);let w={requestId:o,taskId:e,agent:a,...i.inlineAgent?{inlineAgent:i.inlineAgent}:{},prompt:S(y.task,i.instructions,v),...i.context?{context:i.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(y.task.id),subject:y.task.subject},...i.model?{model:i.model}:{}};try{let t=this.service;if(!t)throw Error(g);t.request(w).catch(t=>{this.report(r.TASK_EVENT.delegationRequestFailed,t,{[u]:e,[d]:o,[f]:a}),this.settleDetached(o,c,{status:c,error:`Delegation request failed: ${b(t)}`})})}catch(t){this.report(r.TASK_EVENT.delegationRequestFailed,t,{[u]:e,[d]:o,[f]:a});let n=b(t);return await this.settle(o,c,{status:c,error:`Delegation request failed: ${n}`}),{ok:!1,message:`Could not dispatch #${e} to ${a}: ${n}`}}return this.options.report?.event(r.TASK_EVENT.delegationAssigned,{[u]:e,[d]:o,[f]:a,[p]:v.files.length>0||C>0,[m]:v.files.length,[h]:C,"delegation.brief_length":w.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${e} to ${a} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!n.isDelegationActive(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:r}=t.delegation;return this.service?.cancel({requestId:r}),this.armCancelTimeout(r),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,t,n,i=r.TASK_EVENT.delegationSettleFailed){this.settle(e,t,n).catch(t=>{this.report(i,t,{[d]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,c,{status:c,error:g})})}armRunTimeout(e){let t=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+t,()=>{let t=this.pendingTasks.get(e),n=this.progress.get(e)?.agent,i=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(r.TASK_EVENT.delegationTimedOut,i,{...t===void 0?{}:{[u]:t},[d]:e,...n?{[f]:n}:{}}),this.service?.cancel({requestId:e,reason:i.message}),this.settleDetached(e,c,{status:`timed_out`,error:i.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,l,{status:l,error:v})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:t}=e,n=this.pendingTasks.get(e.requestId);if(n===void 0)return;this.armRunTimeout(e.requestId);let i=this.progress.get(e.requestId);i&&this.progress.set(e.requestId,{...i,durationMs:i.durationMs??0,durationObservedAt:i.durationObservedAt??this.nowMs()}),this.options.store.mutate(n=>this.patchDelegation(n,e.requestId,(e,n)=>({...e,status:e.status===s?e.status:`in_progress`,delegation:{...n,state:`running`,startedAt:n.startedAt??this.now(),...t?{runId:t}:{}}}))).then(()=>this.options.onChange?.()).catch(t=>{this.report(r.TASK_EVENT.delegationStartFailed,t,{[u]:n,[d]:e.requestId})})}handleUpdate(t){let n=this.progress.get(t.requestId);if(!n)return;let r=this.nowMs(),i=e.elapsedMs(n,r),a=t.durationMs!==void 0;this.progress.set(t.requestId,{...n,currentTool:t.currentTool??n.currentTool,toolCount:t.toolCount===void 0?n.toolCount:Math.max(n.toolCount??0,t.toolCount),tokens:t.tokens===void 0?n.tokens:Math.max(n.tokens??0,t.tokens),durationMs:a?Math.max(i,t.durationMs):n.durationMs,durationObservedAt:a?r:n.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===s&&!e.error?s:e.status===l?l:c;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:y(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,n,i){let a=this.pendingTasks.get(e);if(a===void 0)return;this.pendingTasks.delete(e),this.clearTimer(e);let o=this.progress.get(e);this.progress.delete(e);let g=this.now(),_;try{let{value:t}=await this.options.store.mutate(t=>this.patchDelegation(t,e,(e,t)=>({...e,status:n===s?s:n===l?`pending`:c,updatedAt:g,delegation:{...t,state:n,endedAt:g,...i?{result:i}:{}}})));_=t}catch(t){this.report(r.TASK_EVENT.delegationSettleFailed,t,{[u]:a,[d]:e})}this.options.onChange?.();let v=_?.delegation?.agent??o?.agent??`subagent`,y=_?.subject??`#${a}`;this.options.report?.event(r.TASK_EVENT.delegationCompleted,{[u]:a,[d]:e,[f]:v,"delegation.outcome":n,[p]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[m]:o?.contextFileCount??0,[h]:o?.contextNotesLength??0,...i?.toolCount===void 0?{}:{"delegation.tool_count":i.toolCount},...i?.durationMs===void 0?{}:{"delegation.duration_ms":i.durationMs}});let b=n===s&&_!==void 0&&t.isTaskListComplete(this.options.store.snapshot.tasks);this.notifyModel(n,a,y,v,i,b)}notifyModel(e,t,n,r,i,a){let c=this.options.notify;if(!c)return;let u=[e===s?`Subagent ${r} completed task #${t}: ${n}`:e===l?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&u.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&u.push(`Error: ${i.error}`),i?.output&&u.push(``,i.output),i?.outputPath&&u.push(``,`Full output: ${i.outputPath}`);try{c({customType:o,content:u.join(`
5
+ `),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,r){let i=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!n.isDelegationActive(a))return{value:a};let o=r(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){this.unbind(),this.reset()}reset(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};exports.BACKGROUND_WORK_PROVIDER=`doom-task`,exports.DelegationManager=C,exports.ERR_CANCEL_UNACKNOWLEDGED=v,exports.ERR_CHILD_SESSION=_,exports.ERR_NO_RUNTIME=g,exports.MAX_BRIEF_FILES=e.MAX_BRIEF_FILES,exports.NOTIFY_CUSTOM_TYPE=o;
6
6
  //# sourceMappingURL=manager.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager.cjs","names":["createProtocolRuntime","DelegationAccepted","DelegationStarted","DelegationUpdated","DelegationFinished","TASK_EVENT","reconcileOrphanedDelegations","isDelegationActive","isBlocked","DelegationRequested","DelegationCancelled","isTaskListComplete"],"sources":["../../../src/services/delegation/manager.ts"],"sourcesContent":["import {\n DelegationAccepted,\n type DelegationAccepted as DelegationAcceptedPayload,\n DelegationCancelled,\n DelegationFinished,\n DelegationRequested,\n type DelegationResult,\n DelegationStarted,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n DelegationUpdated,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport {\n createProtocolRuntime,\n type EventBusLike,\n type ProtocolRuntime,\n} from '@agimon-ai/doompi-extension-contracts/protocol';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../../adapters/store/taskStore';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n events: EventBusLike;\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides the Doom Team event bus rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that runtime is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private protocol: ProtocolRuntime | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Idempotent: a session restart re-subscribes without stacking handlers. */\n start(): void {\n if (this.subscriptions.length > 0) return;\n const sessionId = this.options.getSessionId?.();\n if (!sessionId) return;\n this.protocol = createProtocolRuntime({\n bus: this.options.events,\n source: '@agimon-ai/doompi-task',\n sessionId,\n });\n this.subscriptions.push(\n this.protocol.onNotification(DelegationAccepted, (event) => {\n this.handleAccepted(event);\n }),\n this.protocol.onNotification(DelegationStarted, (event) => {\n this.handleStarted(event);\n }),\n this.protocol.onNotification(DelegationUpdated, (event) => {\n this.handleUpdate(event);\n }),\n this.protocol.onNotification(DelegationFinished, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n if (!this.protocol) throw new Error(ERR_NO_RUNTIME);\n this.protocol.notify(DelegationRequested, request);\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Emitted only after the notify succeeds, so it means \"a brief of this\n // shape actually went out\" rather than \"one was assembled\".\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.protocol?.notify(DelegationCancelled, { requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * The bus cannot be probed for listeners, so silence is the only available\n * signal that the subagents runtime is absent. Without this the task would\n * sit in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.protocol?.notify(DelegationCancelled, { requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Emitting the cancel event is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n for (const unsubscribe of this.subscriptions) unsubscribe();\n this.subscriptions.length = 0;\n this.protocol = undefined;\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.progress.clear();\n }\n}\n"],"mappings":"2TA2BA,MAAa,EAAqB,mBAa5B,EAAkB,YAClB,EAAe,SACf,EAAkB,YAIlB,EAAoB,UACpB,EAAuB,wBAGvB,EAAkB,wBAElB,EAA4B,6BAC5B,EAA+B,gCAC/B,EAAiC,kCAQ1B,EACX,kHACW,EACX,uGACW,EAA4B,kDA6EzC,SAAS,EAAS,EAA2B,EAAQ,IAAuC,CACrF,KACL,OAAO,EAAM,QAAU,EAAQ,EAAQ,GAAG,EAAM,MAAM,EAAG,CAAK,EAAE,gBAClE,CAEA,SAAS,EAAU,EAAwB,CACzC,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CASA,SAAS,EAAa,EAAwB,EAAa,EAA4C,CACrG,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAS,EAAQ,eAAiB,CAAC,EAAG,CAC/C,GAAI,EAAM,MAAA,GAAyB,MACnC,IAAM,EAAa,EAAS,gBAAgB,EAAM,KAAK,EAAG,CAAG,EACzD,GAAc,IAAe,KAAK,EAAM,IAAI,CAAU,CAC5D,CACA,MAAO,CAAE,MAAO,CAAC,GAAG,CAAK,EAAG,MAAO,EAAS,EAAQ,eAAe,KAAK,EAAG,IAAe,CAAE,CAC9F,CAcA,SAAS,EAAW,EAAY,EAAkC,EAA+B,CAC/F,IAAM,EAAW,CAAC,SAAS,EAAK,GAAG,IAAI,EAAK,SA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,CAAQ,CAC5D,CAEA,SAAgB,CACd,IAAK,IAAM,KAAe,KAAK,cAAe,EAAY,EAC1D,KAAK,cAAc,OAAS,EAC5B,KAAK,SAAW,IAAA,GAChB,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
1
+ {"version":3,"file":"manager.cjs","names":["DOOM_DELEGATION_ACCEPTED_EVENT","DOOM_DELEGATION_STARTED_EVENT","DOOM_DELEGATION_UPDATED_EVENT","DOOM_DELEGATION_FINISHED_EVENT","TASK_EVENT","reconcileOrphanedDelegations","isDelegationActive","isBlocked","isTaskListComplete"],"sources":["../../../src/services/delegation/manager.ts"],"sourcesContent":["import {\n type DelegationAccepted as DelegationAcceptedPayload,\n DOOM_DELEGATION_ACCEPTED_EVENT,\n DOOM_DELEGATION_FINISHED_EVENT,\n DOOM_DELEGATION_STARTED_EVENT,\n DOOM_DELEGATION_UPDATED_EVENT,\n type DoomDelegationService,\n type DelegationResult,\n type DelegationStarted as DelegationStartedPayload,\n type DelegationUpdate,\n} from '@agimon-ai/doompi-extension-contracts/delegation';\nimport type { InlineAgent } from '@agimon-ai/doompi-extension-contracts/subagent-tool';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry.ts';\nimport { reconcileOrphanedDelegations } from '../store/reconcile.ts';\nimport { isBlocked, isTaskListComplete } from '../store/taskGraph.ts';\nimport type { TaskStore } from '../../adapters/store/taskStore';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../store/types.ts';\n\nexport const NOTIFY_CUSTOM_TYPE = 'doom-task-notify';\nexport const BACKGROUND_WORK_PROVIDER = 'doom-task';\n\nconst DEFAULT_STARTED_TIMEOUT_MS = 5000;\nconst DEFAULT_RUN_TIMEOUT_MS = 20 * 60 * 1000;\nconst DEFAULT_CANCEL_TIMEOUT_MS = 10_000;\nconst MAX_RUN_TIMEOUT_GRACE_MS = 60_000;\nconst MAX_STORED_OUTPUT = 4000;\n/**\n * Cap on files rendered into a brief. Exported so the tool schema can state the\n * same number to the model rather than restating it and drifting.\n */\nconst MAX_BRIEF_NOTES = 1500;\nconst COMPLETED_STATE = 'completed';\nconst FAILED_STATE = 'failed';\nconst CANCELLED_STATE = 'cancelled';\nconst TIMED_OUT_STATUS = 'timed_out';\nconst DELETED_STATUS: Task['status'] = 'deleted';\n\nconst TASK_ID_ATTRIBUTE = 'task.id';\nconst REQUEST_ID_ATTRIBUTE = 'delegation.request_id';\n// `_name` suffix is load-bearing: the telemetry redactor drops string values\n// whose key has no safe meaning, and a bare `delegation.agent` is dropped.\nconst AGENT_ATTRIBUTE = 'delegation.agent_name';\nconst PID_ATTRIBUTE = 'delegation.pid';\nconst CONTEXT_PRESENT_ATTRIBUTE = 'delegation.context_present';\nconst CONTEXT_FILE_COUNT_ATTRIBUTE = 'delegation.context_file_count';\nconst CONTEXT_NOTES_LENGTH_ATTRIBUTE = 'delegation.context_notes_length';\nconst BRIEF_LENGTH_ATTRIBUTE = 'delegation.brief_length';\nconst TOOL_COUNT_ATTRIBUTE = 'delegation.tool_count';\nconst DURATION_MS_ATTRIBUTE = 'delegation.duration_ms';\nconst OUTCOME_ATTRIBUTE = 'delegation.outcome';\n\ntype SettlementState = typeof COMPLETED_STATE | typeof FAILED_STATE | typeof CANCELLED_STATE;\n\nexport const ERR_NO_RUNTIME =\n 'No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.';\nexport const ERR_CHILD_SESSION =\n 'assign is only available in the main session. Update this task directly instead of re-delegating it.';\nexport const ERR_CANCEL_UNACKNOWLEDGED = 'Subagent did not acknowledge the cancel request';\n\n/** Live progress from a running subagent. Kept in memory: persisting per-tool\n * ticks would rewrite the store file every second for no durable benefit. */\nexport interface DelegationProgress {\n agent: string;\n currentTool?: string;\n toolCount?: number;\n tokens?: number;\n /** Latest child-runtime duration baseline, excluding assignment wait. */\n durationMs?: number;\n /** Wall-clock time at which durationMs was observed or rebased. */\n durationObservedAt?: number;\n /** Assign-time context-pack shape, carried so the completion event can be\n * grouped by it without joining back to the assignment event. */\n contextFileCount?: number;\n contextNotesLength?: number;\n}\n\nexport type DelegationNotifier = (\n message: { customType: string; content: string; display: boolean },\n options?: { triggerTurn?: boolean; deliverAs?: 'steer' | 'followUp' | 'nextTurn' },\n) => void;\n\nexport interface DelegationPlatform {\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly processId: number;\n readonly createRequestId: () => string;\n readonly formatBriefPath: (entry: string, cwd: string) => string;\n}\n\nexport interface DelegationManagerOptions {\n store: TaskStore;\n cwd: string;\n platform: DelegationPlatform;\n notify?: DelegationNotifier;\n getSessionId?: () => string | undefined;\n onChange?: () => void;\n startedTimeoutMs?: number;\n /** How long a started run may go without reporting a result. */\n runTimeoutMs?: number;\n /** How long to wait for a cancelled run to report back before forcing it. */\n cancelTimeoutMs?: number;\n now?: () => string;\n nowMs?: () => number;\n /** Called when a completion notification could not be delivered. */\n onNotifyError: (error: unknown, taskId: number) => void;\n /** Where other swallowed delegation failures go. */\n report?: TaskFailureReporter;\n}\n\nexport interface AssignOptions {\n agent?: string;\n inlineAgent?: InlineAgent;\n instructions?: string;\n /** Paths the parent already located, rendered into the brief so the child\n * skips rediscovering them. */\n relevantFiles?: string[];\n /** Facts the parent already established, rendered into the brief so the child\n * does not re-derive them. */\n priorFindings?: string;\n model?: string;\n context?: 'fresh' | 'fork';\n signal?: AbortSignal;\n}\n\nexport interface DelegationOutcome {\n ok: boolean;\n message: string;\n}\n\n/** Result of the guarded store mutation that claims a task for delegation. */\ninterface AssignAttempt extends DelegationOutcome {\n task?: Task;\n}\n\nfunction truncate(value: string | undefined, limit = MAX_STORED_OUTPUT): string | undefined {\n if (!value) return undefined;\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n… (truncated)`;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The assign-time context pack, normalized once for the brief and the telemetry. */\ninterface BriefContext {\n files: string[];\n notes?: string;\n}\n\n/** Normalize the parent context with host-owned path semantics. */\nfunction briefContext(options: AssignOptions, cwd: string, platform: DelegationPlatform): BriefContext {\n const files = new Set<string>();\n for (const entry of options.relevantFiles ?? []) {\n if (files.size >= MAX_BRIEF_FILES) break;\n const normalized = platform.formatBriefPath(entry.trim(), cwd);\n if (normalized && normalized !== '.') files.add(normalized);\n }\n return { files: [...files], notes: truncate(options.priorFindings?.trim(), MAX_BRIEF_NOTES) };\n}\n\n/**\n * Build the brief handed to the subagent.\n *\n * Doom Team owns the child tool surface and the parent owns the task record.\n * Keeping those responsibilities explicit prevents a child from attempting to\n * call a task tool that is not loaded in its runtime, while still giving it a\n * reliable path to ask the parent for a decision.\n *\n * The context pack is the parent's verified discovery handed over. The whole\n * block is omitted when nothing was supplied: this brief is the child's whole\n * starting context, so an empty section header is pure token cost.\n */\nfunction buildBrief(task: Task, instructions: string | undefined, context: BriefContext): string {\n const sections = [`Task #${task.id}: ${task.subject}`];\n if (task.description) sections.push(task.description);\n if (instructions) sections.push(instructions);\n if (context.files.length > 0 || context.notes) {\n const contextLines = ['Parent context — consume before repository discovery:'];\n if (context.files.length > 0) {\n contextLines.push(`- Parent-verified files (read these first with direct reads): ${context.files.join(', ')}`);\n }\n if (context.notes) {\n contextLines.push(\n `- Established facts (do not re-derive unless direct evidence contradicts them): ${context.notes}`,\n );\n }\n contextLines.push(\n 'This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n );\n sections.push(contextLines.join('\\n'));\n }\n sections.push(\n 'Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.',\n );\n return sections.join('\\n\\n');\n}\n\n/**\n * Owns the lifecycle of tasks delegated to subagents.\n *\n * Delegation rides Team's injected Cordis service rather than spawning\n * processes directly, so doom-task stays decoupled from the subagent runtime\n * and degrades to a clear error when that service is not loaded.\n *\n * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so\n * a delegation always has a deadline no matter which phase it is in. Losing\n * that pairing is what previously left tasks running forever.\n */\nexport class DelegationManager {\n private readonly options: DelegationManagerOptions;\n private readonly progress = new Map<string, DelegationProgress>();\n private readonly pendingTasks = new Map<string, number>();\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly subscriptions: Array<() => void> = [];\n private service: DoomDelegationService | undefined;\n\n constructor(options: DelegationManagerOptions) {\n this.options = options;\n }\n\n private now(): string {\n return this.options.now?.() ?? new Date().toISOString();\n }\n\n private nowMs(): number {\n return this.options.nowMs?.() ?? Date.now();\n }\n\n private get runTimeoutMs(): number {\n return this.options.runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS;\n }\n\n private report(event: TaskEventName, error: unknown, attributes?: Record<string, string | number | boolean>): void {\n this.options.report?.error(event, error, attributes);\n }\n\n /** True in a session that is itself a subagent child. */\n get isChildSession(): boolean {\n return Boolean(this.options.platform.environment.PI_SUBAGENT_CHILD);\n }\n\n /** Live progress for a task, for the overlay to render. */\n progressFor(task: Task): DelegationProgress | undefined {\n const requestId = task.delegation?.requestId;\n return requestId ? this.progress.get(requestId) : undefined;\n }\n\n /** Displayed runtime duration, rebased from the latest child observation. */\n static elapsedMs(progress: DelegationProgress, nowMs = Date.now()): number {\n const baseline = progress.durationMs ?? 0;\n const observedAt = progress.durationObservedAt ?? nowMs;\n return baseline + Math.max(0, nowMs - observedAt);\n }\n\n /** Rebind to the active Team service without stacking lifecycle listeners. */\n bind(ctx: Context, service: DoomDelegationService): () => void {\n this.unbind();\n this.service = service;\n this.subscriptions.push(\n ctx.on(DOOM_DELEGATION_ACCEPTED_EVENT, (event) => {\n this.handleAccepted(event);\n }),\n ctx.on(DOOM_DELEGATION_STARTED_EVENT, (event) => {\n this.handleStarted(event);\n }),\n ctx.on(DOOM_DELEGATION_UPDATED_EVENT, (event) => {\n this.handleUpdate(event);\n }),\n ctx.on(DOOM_DELEGATION_FINISHED_EVENT, (event) => {\n void this.handleResponse(event).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationResponseFailed, error, { [REQUEST_ID_ATTRIBUTE]: event.requestId });\n });\n }),\n );\n return () => {\n if (this.service === service) this.unbind();\n };\n }\n\n /** Remove only the cross-package binding; task state and watchdogs remain live. */\n unbind(): void {\n for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();\n this.service = undefined;\n }\n\n /** Items still in flight, surfaced so auto-stop will not kill the harness. */\n listActiveWork(): Array<{ id: string; sessionId: string }> {\n const sessionId = this.options.getSessionId?.() ?? '';\n return [...this.pendingTasks.entries()].map(([requestId, taskId]) => ({\n id: `task-${taskId}:${requestId}`,\n sessionId,\n }));\n }\n\n /**\n * Return tasks nothing can finish to `pending`.\n *\n * The live request set is read inside the mutation so a delegation assigned\n * while the lock was contended is not mistaken for a leftover.\n */\n async reconcile(isCurrent: () => boolean = () => true): Promise<Task[]> {\n const { value } = await this.options.store.mutate((document) => {\n if (!isCurrent()) return { value: [] as Task[] };\n const result = reconcileOrphanedDelegations(document, this.now(), undefined, {\n pid: this.options.platform.processId,\n liveRequestIds: new Set(this.pendingTasks.keys()),\n });\n if (result.orphaned.length === 0) return { value: [] as Task[] };\n return { document: result.document, value: result.orphaned };\n });\n\n if (!isCurrent()) return [];\n for (const task of value) {\n this.options.report?.warn(TASK_EVENT.delegationOrphaned, new Error(task.delegation?.result?.error ?? ''), {\n [TASK_ID_ATTRIBUTE]: task.id,\n ...(task.delegation?.agent ? { [AGENT_ATTRIBUTE]: task.delegation.agent } : {}),\n ...(task.delegation?.pid === undefined ? {} : { [PID_ATTRIBUTE]: task.delegation.pid }),\n });\n }\n\n if (value.length > 0) this.options.onChange?.();\n return value;\n }\n\n async assign(taskId: number, options: AssignOptions): Promise<DelegationOutcome> {\n const agent = options.agent?.trim();\n if (!agent) return { ok: false, message: 'agent required for assign' };\n if (this.isChildSession) return { ok: false, message: ERR_CHILD_SESSION };\n if (options.signal?.aborted) return { ok: false, message: 'delegation cancelled before it started' };\n\n const requestId = this.options.platform.createRequestId();\n const startedAt = this.now();\n const context = briefContext(options, this.options.cwd, this.options.platform);\n\n const { value: outcome } = await this.options.store.mutate<AssignAttempt>((current) => {\n const index = current.tasks.findIndex((task) => task.id === taskId);\n if (index === -1) return { value: { ok: false, message: `#${taskId} not found` } };\n\n const task = current.tasks[index];\n if (task.status === DELETED_STATUS) return { value: { ok: false, message: `#${taskId} is deleted` } };\n if (task.status === COMPLETED_STATE) {\n return { value: { ok: false, message: `#${taskId} is already completed` } };\n }\n if (isDelegationActive(task)) {\n return { value: { ok: false, message: `#${taskId} is already delegated to ${task.delegation?.agent}` } };\n }\n if (isBlocked(current.tasks, task)) {\n const blockers = (task.blockedBy ?? []).map((id) => `#${id}`).join(', ');\n return { value: { ok: false, message: `#${taskId} is blocked by ${blockers}` } };\n }\n\n const delegation: TaskDelegation = {\n requestId,\n agent,\n state: 'requested',\n pid: this.options.platform.processId,\n startedAt,\n ...(this.options.getSessionId?.() ? { sessionId: this.options.getSessionId!() } : {}),\n ...(options.model ? { model: options.model } : {}),\n };\n\n const tasks = [...current.tasks];\n tasks[index] = { ...task, owner: agent, updatedAt: startedAt, delegation };\n return {\n document: { ...current, tasks },\n value: { ok: true, message: '', task: tasks[index] },\n };\n });\n\n if (!outcome.ok || !outcome.task) return { ok: false, message: outcome.message };\n\n const contextNotesLength = context.notes?.length ?? 0;\n this.pendingTasks.set(requestId, taskId);\n this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n this.armStartedTimeout(requestId);\n\n const request = {\n requestId,\n taskId,\n agent,\n ...(options.inlineAgent ? { inlineAgent: options.inlineAgent } : {}),\n prompt: buildBrief(outcome.task, options.instructions, context),\n ...(options.context ? { context: options.context } : {}),\n cwd: this.options.cwd,\n artifacts: true,\n timeoutMs: this.runTimeoutMs,\n runMode: 'detached' as const,\n teamTask: { id: String(outcome.task.id), subject: outcome.task.subject },\n ...(options.model ? { model: options.model } : {}),\n };\n\n try {\n const service = this.service;\n if (!service) throw new Error(ERR_NO_RUNTIME);\n void service.request(request).catch((error: unknown) => {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n this.settleDetached(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${messageOf(error)}`,\n });\n });\n } catch (error) {\n this.report(TASK_EVENT.delegationRequestFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n });\n const detail = messageOf(error);\n await this.settle(requestId, FAILED_STATE, {\n status: FAILED_STATE,\n error: `Delegation request failed: ${detail}`,\n });\n return { ok: false, message: `Could not dispatch #${taskId} to ${agent}: ${detail}` };\n }\n\n // Recorded only after the service accepted the request call, so it means a\n // brief actually entered Team's state machine rather than merely being assembled.\n this.options.report?.event(TASK_EVENT.delegationAssigned, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [CONTEXT_PRESENT_ATTRIBUTE]: context.files.length > 0 || contextNotesLength > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: context.files.length,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: contextNotesLength,\n [BRIEF_LENGTH_ATTRIBUTE]: request.prompt.length,\n });\n\n this.options.onChange?.();\n\n return {\n ok: true,\n message: `Delegated #${taskId} to ${agent} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`,\n };\n }\n\n async cancel(taskId: number): Promise<DelegationOutcome> {\n const document = this.options.store.read();\n const task = document.tasks.find((candidate) => candidate.id === taskId);\n if (!task) return { ok: false, message: `#${taskId} not found` };\n if (!task.delegation || !isDelegationActive(task)) {\n return { ok: false, message: `#${taskId} has no running delegation` };\n }\n\n const { requestId } = task.delegation;\n this.service?.cancel({ requestId });\n // Only this session can force the outcome; a delegation owned elsewhere\n // gets the request and nothing more.\n this.armCancelTimeout(requestId);\n return { ok: true, message: `Cancelling delegation for #${taskId} (${task.delegation.agent})` };\n }\n\n /** Settle without awaiting, reporting rather than dropping a failure. */\n private settleDetached(\n requestId: string,\n state: SettlementState,\n result: TaskDelegation['result'],\n event: TaskEventName = TASK_EVENT.delegationSettleFailed,\n ): void {\n void this.settle(requestId, state, result).catch((error: unknown) => {\n this.report(event, error, { [REQUEST_ID_ATTRIBUTE]: requestId });\n });\n }\n\n /**\n * Fail a delegation that nobody acknowledged.\n *\n * Provider loss or a stalled Team runtime can still leave a dispatched\n * request silent. Without this acknowledgement deadline the task would sit\n * in `requested` forever.\n */\n private armStartedTimeout(requestId: string): void {\n this.armTimer(requestId, this.options.startedTimeoutMs ?? DEFAULT_STARTED_TIMEOUT_MS, () => {\n this.settleDetached(requestId, FAILED_STATE, { status: FAILED_STATE, error: ERR_NO_RUNTIME });\n });\n }\n\n /**\n * Bound a run that already started.\n *\n * The request carries the same budget, so in the normal case the runtime ends\n * the run itself and reports a richer result. The grace period biases toward\n * that answer; this timer only covers a runtime that goes silent, which is\n * precisely the case where no response event will ever arrive.\n */\n private armRunTimeout(requestId: string): void {\n const grace = Math.min(MAX_RUN_TIMEOUT_GRACE_MS, this.runTimeoutMs);\n this.armTimer(requestId, this.runTimeoutMs + grace, () => {\n const taskId = this.pendingTasks.get(requestId);\n const agent = this.progress.get(requestId)?.agent;\n const error = new Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);\n this.options.report?.warn(TASK_EVENT.delegationTimedOut, error, {\n ...(taskId === undefined ? {} : { [TASK_ID_ATTRIBUTE]: taskId }),\n [REQUEST_ID_ATTRIBUTE]: requestId,\n ...(agent ? { [AGENT_ATTRIBUTE]: agent } : {}),\n });\n this.service?.cancel({ requestId, reason: error.message });\n this.settleDetached(requestId, FAILED_STATE, { status: TIMED_OUT_STATUS, error: error.message });\n });\n }\n\n /**\n * Guarantee a cancel reaches a terminal state.\n *\n * Calling the service is a request, not an outcome: a runtime that has\n * already forgotten the request answers nothing at all. The window still\n * favours a real response, which carries the run's partial output.\n */\n private armCancelTimeout(requestId: string): void {\n if (!this.pendingTasks.has(requestId)) return;\n this.armTimer(requestId, this.options.cancelTimeoutMs ?? DEFAULT_CANCEL_TIMEOUT_MS, () => {\n this.settleDetached(requestId, CANCELLED_STATE, {\n status: CANCELLED_STATE,\n error: ERR_CANCEL_UNACKNOWLEDGED,\n });\n });\n }\n\n private armTimer(requestId: string, delayMs: number, onFire: () => void): void {\n this.clearTimer(requestId);\n const timer = setTimeout(onFire, delayMs);\n timer.unref?.();\n this.timers.set(requestId, timer);\n }\n\n private clearTimer(requestId: string): void {\n const timer = this.timers.get(requestId);\n if (timer) clearTimeout(timer);\n this.timers.delete(requestId);\n }\n\n /** Runtime acknowledgement moves the request off the short extension-presence watchdog while launch is in flight. */\n private handleAccepted(event: DelegationAcceptedPayload): void {\n if (!this.pendingTasks.has(event.requestId)) return;\n this.armRunTimeout(event.requestId);\n }\n\n private handleStarted(event: DelegationStartedPayload): void {\n const { runId } = event;\n const taskId = this.pendingTasks.get(event.requestId);\n if (taskId === undefined) return;\n this.armRunTimeout(event.requestId);\n const existing = this.progress.get(event.requestId);\n if (existing) {\n this.progress.set(event.requestId, {\n ...existing,\n durationMs: existing.durationMs ?? 0,\n durationObservedAt: existing.durationObservedAt ?? this.nowMs(),\n });\n }\n\n void this.options.store\n .mutate((document) =>\n this.patchDelegation(document, event.requestId, (task, delegation) => ({\n ...task,\n status: task.status === COMPLETED_STATE ? task.status : 'in_progress',\n delegation: {\n ...delegation,\n state: 'running',\n startedAt: delegation.startedAt ?? this.now(),\n ...(runId ? { runId } : {}),\n },\n })),\n )\n .then(() => this.options.onChange?.())\n .catch((error: unknown) => {\n this.report(TASK_EVENT.delegationStartFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: event.requestId,\n });\n });\n }\n\n private handleUpdate(event: DelegationUpdate): void {\n const existing = this.progress.get(event.requestId);\n if (!existing) return;\n\n const observedAt = this.nowMs();\n const currentElapsed = DelegationManager.elapsedMs(existing, observedAt);\n const hasDuration = event.durationMs !== undefined;\n this.progress.set(event.requestId, {\n // Spread, not field-by-field: anything carried on progress that this\n // event does not report (the assign-time context shape) must survive the\n // first update, or the completion event reports it as absent.\n ...existing,\n currentTool: event.currentTool ?? existing.currentTool,\n toolCount:\n event.toolCount === undefined ? existing.toolCount : Math.max(existing.toolCount ?? 0, event.toolCount),\n tokens: event.tokens === undefined ? existing.tokens : Math.max(existing.tokens ?? 0, event.tokens),\n durationMs: hasDuration ? Math.max(currentElapsed, event.durationMs!) : existing.durationMs,\n durationObservedAt: hasDuration ? observedAt : existing.durationObservedAt,\n });\n this.options.onChange?.();\n }\n\n private async handleResponse(event: DelegationResult): Promise<void> {\n if (!this.pendingTasks.has(event.requestId)) return;\n\n const succeeded = event.status === COMPLETED_STATE && !event.error;\n const state = succeeded ? COMPLETED_STATE : event.status === CANCELLED_STATE ? CANCELLED_STATE : FAILED_STATE;\n await this.settle(event.requestId, state, {\n status: event.status,\n error: event.error,\n output: truncate(event.output),\n outputPath: event.outputPath,\n sessionFile: event.sessionFile,\n durationMs: event.durationMs,\n toolCount: event.toolCount,\n });\n }\n\n /**\n * Apply the terminal state of a delegation and tell the model about it.\n *\n * A cancelled run returns the task to `pending` (the work is still wanted,\n * just not by that agent); a failure marks it `failed` so it stays visible\n * rather than silently rejoining the backlog.\n *\n * Dropping the pending entry first makes this single-shot: a response racing\n * the watchdog cannot settle the same run twice. A failed write therefore\n * must not abort the rest — the model still gets told, the run stops counting\n * as active work, and `reconcile` repairs the file at the next session start.\n */\n private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n const taskId = this.pendingTasks.get(requestId);\n if (taskId === undefined) return;\n this.pendingTasks.delete(requestId);\n this.clearTimer(requestId);\n const progress = this.progress.get(requestId);\n this.progress.delete(requestId);\n\n const endedAt = this.now();\n let task: Task | undefined;\n try {\n const { value } = await this.options.store.mutate((document) =>\n this.patchDelegation(document, requestId, (current, delegation) => ({\n ...current,\n status: state === COMPLETED_STATE ? COMPLETED_STATE : state === CANCELLED_STATE ? 'pending' : FAILED_STATE,\n updatedAt: endedAt,\n delegation: { ...delegation, state, endedAt, ...(result ? { result } : {}) },\n })),\n );\n task = value;\n } catch (error) {\n this.report(TASK_EVENT.delegationSettleFailed, error, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n });\n }\n\n this.options.onChange?.();\n\n const agent = task?.delegation?.agent ?? progress?.agent ?? 'subagent';\n const subject = task?.subject ?? `#${taskId}`;\n\n // Repeats the assign-time context shape so the cost question (\"did packs\n // reduce child tool calls?\") is one grouping rather than a self-join.\n // A run that never started reports neither metric, keeping the medians clean.\n this.options.report?.event(TASK_EVENT.delegationCompleted, {\n [TASK_ID_ATTRIBUTE]: taskId,\n [REQUEST_ID_ATTRIBUTE]: requestId,\n [AGENT_ATTRIBUTE]: agent,\n [OUTCOME_ATTRIBUTE]: state,\n [CONTEXT_PRESENT_ATTRIBUTE]: (progress?.contextFileCount ?? 0) > 0 || (progress?.contextNotesLength ?? 0) > 0,\n [CONTEXT_FILE_COUNT_ATTRIBUTE]: progress?.contextFileCount ?? 0,\n [CONTEXT_NOTES_LENGTH_ATTRIBUTE]: progress?.contextNotesLength ?? 0,\n ...(result?.toolCount === undefined ? {} : { [TOOL_COUNT_ATTRIBUTE]: result.toolCount }),\n ...(result?.durationMs === undefined ? {} : { [DURATION_MS_ATTRIBUTE]: result.durationMs }),\n });\n const listComplete =\n state === COMPLETED_STATE && task !== undefined && isTaskListComplete(this.options.store.snapshot.tasks);\n this.notifyModel(state, taskId, subject, agent, result, listComplete);\n }\n\n private notifyModel(\n state: SettlementState,\n taskId: number,\n subject: string,\n agent: string,\n result: TaskDelegation['result'],\n listComplete: boolean,\n ): void {\n const notify = this.options.notify;\n if (!notify) return;\n\n const headline =\n state === COMPLETED_STATE\n ? `Subagent ${agent} completed task #${taskId}: ${subject}`\n : state === CANCELLED_STATE\n ? `Subagent ${agent} was cancelled on task #${taskId}: ${subject} (returned to pending)`\n : `Subagent ${agent} failed task #${taskId}: ${subject}`;\n\n const lines = [headline];\n if (listComplete) {\n lines.push(\n '',\n 'All tasks are completed. Review the full task list once more, then close it with task {\"action\":\"clear\"}.',\n );\n }\n if (result?.error) lines.push(`Error: ${result.error}`);\n if (result?.output) lines.push('', result.output);\n if (result?.outputPath) lines.push('', `Full output: ${result.outputPath}`);\n\n try {\n notify(\n { customType: NOTIFY_CUSTOM_TYPE, content: lines.join('\\n'), display: true },\n { triggerTurn: true, deliverAs: 'steer' },\n );\n } catch (error) {\n // The delegation state is already committed to the store, so a failed\n // notification costs the model its wake-up, not the result. Report it\n // rather than rethrowing, which would strand the settled run.\n this.options.onNotifyError(error, taskId);\n }\n }\n\n /**\n * Rewrite the task carrying `requestId`, returning the updated task as the mutation value.\n *\n * Terminal delegations are left alone. The document here is the freshest one,\n * read under the store lock, which is the only place the check is meaningful:\n * a `started` event can land after a cancel already settled the run, and\n * without this guard its write would resurrect a delegation that nothing is\n * tracking any more.\n */\n private patchDelegation(\n document: TaskDocument,\n requestId: string,\n patch: (task: Task, delegation: TaskDelegation) => Task,\n ): { document?: TaskDocument; value: Task | undefined } {\n const index = document.tasks.findIndex((task) => task.delegation?.requestId === requestId);\n if (index === -1) return { value: undefined };\n\n const task = document.tasks[index];\n if (!isDelegationActive(task)) return { value: task };\n\n const updated = patch(task, task.delegation!);\n if (updated === task) return { value: task };\n const tasks = [...document.tasks];\n tasks[index] = updated;\n return { document: { ...document, tasks }, value: updated };\n }\n\n dispose(): void {\n this.unbind();\n this.reset();\n }\n\n /** Clear one Pi session's transient delegation state without losing service injection. */\n reset(): void {\n for (const timer of this.timers.values()) clearTimeout(timer);\n this.timers.clear();\n this.pendingTasks.clear();\n this.progress.clear();\n }\n}\n"],"mappings":"+PAsBA,MAAa,EAAqB,mBAa5B,EAAkB,YAClB,EAAe,SACf,EAAkB,YAIlB,EAAoB,UACpB,EAAuB,wBAGvB,EAAkB,wBAElB,EAA4B,6BAC5B,EAA+B,gCAC/B,EAAiC,kCAQ1B,EACX,kHACW,EACX,uGACW,EAA4B,kDA4EzC,SAAS,EAAS,EAA2B,EAAQ,IAAuC,CACrF,KACL,OAAO,EAAM,QAAU,EAAQ,EAAQ,GAAG,EAAM,MAAM,EAAG,CAAK,EAAE,gBAClE,CAEA,SAAS,EAAU,EAAwB,CACzC,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D,CASA,SAAS,EAAa,EAAwB,EAAa,EAA4C,CACrG,IAAM,EAAQ,IAAI,IAClB,IAAK,IAAM,KAAS,EAAQ,eAAiB,CAAC,EAAG,CAC/C,GAAI,EAAM,MAAA,GAAyB,MACnC,IAAM,EAAa,EAAS,gBAAgB,EAAM,KAAK,EAAG,CAAG,EACzD,GAAc,IAAe,KAAK,EAAM,IAAI,CAAU,CAC5D,CACA,MAAO,CAAE,MAAO,CAAC,GAAG,CAAK,EAAG,MAAO,EAAS,EAAQ,eAAe,KAAK,EAAG,IAAe,CAAE,CAC9F,CAcA,SAAS,EAAW,EAAY,EAAkC,EAA+B,CAC/F,IAAM,EAAW,CAAC,SAAS,EAAK,GAAG,IAAI,EAAK,SAAS,EAGrD,GAFI,EAAK,aAAa,EAAS,KAAK,EAAK,WAAW,EAChD,GAAc,EAAS,KAAK,CAAY,EACxC,EAAQ,MAAM,OAAS,GAAK,EAAQ,MAAO,CAC7C,IAAM,EAAe,CAAC,uDAAuD,EACzE,EAAQ,MAAM,OAAS,GACzB,EAAa,KAAK,iEAAiE,EAAQ,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,OAAO,EACZ,KAAK,MAAM,CACb,CAGA,OAAc,CACZ,IAAK,IAAM,KAAS,KAAK,OAAO,OAAO,EAAG,aAAa,CAAK,EAC5D,KAAK,OAAO,MAAM,EAClB,KAAK,aAAa,MAAM,EACxB,KAAK,SAAS,MAAM,CACtB,CACF"}
@@ -3,7 +3,8 @@ import { TaskFailureReporter } from "../../types/telemetry.cjs";
3
3
  import { TaskStore } from "../../adapters/store/taskStore.cjs";
4
4
  import { MAX_BRIEF_FILES } from "../../types/delegation.cjs";
5
5
  import { InlineAgent } from "@agimon-ai/doompi-extension-contracts/subagent-tool";
6
- import { EventBusLike } from "@agimon-ai/doompi-extension-contracts/protocol";
6
+ import { DoomDelegationService } from "@agimon-ai/doompi-extension-contracts/delegation";
7
+ import { Context } from "@deepseek-ai/cordis";
7
8
  //#region src/services/delegation/manager.d.ts
8
9
  declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
9
10
  declare const BACKGROUND_WORK_PROVIDER = "doom-task";
@@ -41,7 +42,6 @@ interface DelegationPlatform {
41
42
  readonly formatBriefPath: (entry: string, cwd: string) => string;
42
43
  }
43
44
  interface DelegationManagerOptions {
44
- events: EventBusLike;
45
45
  store: TaskStore;
46
46
  cwd: string;
47
47
  platform: DelegationPlatform;
@@ -81,9 +81,9 @@ interface DelegationOutcome {
81
81
  /**
82
82
  * Owns the lifecycle of tasks delegated to subagents.
83
83
  *
84
- * Delegation rides the Doom Team event bus rather than spawning
84
+ * Delegation rides Team's injected Cordis service rather than spawning
85
85
  * processes directly, so doom-task stays decoupled from the subagent runtime
86
- * and degrades to a clear error when that runtime is not loaded.
86
+ * and degrades to a clear error when that service is not loaded.
87
87
  *
88
88
  * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
89
89
  * a delegation always has a deadline no matter which phase it is in. Losing
@@ -95,7 +95,7 @@ declare class DelegationManager {
95
95
  private readonly pendingTasks;
96
96
  private readonly timers;
97
97
  private readonly subscriptions;
98
- private protocol;
98
+ private service;
99
99
  constructor(options: DelegationManagerOptions);
100
100
  private now;
101
101
  private nowMs;
@@ -107,8 +107,10 @@ declare class DelegationManager {
107
107
  progressFor(task: Task): DelegationProgress | undefined;
108
108
  /** Displayed runtime duration, rebased from the latest child observation. */
109
109
  static elapsedMs(progress: DelegationProgress, nowMs?: number): number;
110
- /** Idempotent: a session restart re-subscribes without stacking handlers. */
111
- start(): void;
110
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
111
+ bind(ctx: Context, service: DoomDelegationService): () => void;
112
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
113
+ unbind(): void;
112
114
  /** Items still in flight, surfaced so auto-stop will not kill the harness. */
113
115
  listActiveWork(): Array<{
114
116
  id: string;
@@ -128,9 +130,9 @@ declare class DelegationManager {
128
130
  /**
129
131
  * Fail a delegation that nobody acknowledged.
130
132
  *
131
- * The bus cannot be probed for listeners, so silence is the only available
132
- * signal that the subagents runtime is absent. Without this the task would
133
- * sit in `requested` forever.
133
+ * Provider loss or a stalled Team runtime can still leave a dispatched
134
+ * request silent. Without this acknowledgement deadline the task would sit
135
+ * in `requested` forever.
134
136
  */
135
137
  private armStartedTimeout;
136
138
  /**
@@ -145,7 +147,7 @@ declare class DelegationManager {
145
147
  /**
146
148
  * Guarantee a cancel reaches a terminal state.
147
149
  *
148
- * Emitting the cancel event is a request, not an outcome: a runtime that has
150
+ * Calling the service is a request, not an outcome: a runtime that has
149
151
  * already forgotten the request answers nothing at all. The window still
150
152
  * favours a real response, which carries the run's partial output.
151
153
  */
@@ -182,6 +184,8 @@ declare class DelegationManager {
182
184
  */
183
185
  private patchDelegation;
184
186
  dispose(): void;
187
+ /** Clear one Pi session's transient delegation state without losing service injection. */
188
+ reset(): void;
185
189
  }
186
190
  //#endregion
187
191
  export { AssignOptions, BACKGROUND_WORK_PROVIDER, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationPlatform, DelegationProgress, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.cts","names":[],"sources":["../../../src/services/delegation/manager.ts"],"mappings":";;;;;;;cA2Ba;cACA;cAkCA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;KAGU,sBACV;EAAW;EAAoB;EAAiB;GAChD;EAAY;EAAuB;;UAGpB;WACN,aAAa,SAAS;WACtB;WACA;WACA,kBAAkB,eAAe;;UAG3B;EACf,QAAQ;EACR,OAAO;EACP;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;cAkFW;mBACM;mBACA;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,SAAS;UAIb;UAIA;cAII;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C;;EA4BA,kBAAkB;IAAQ;IAAY;;;;;;;;EAchC,UAAU,4BAAwC,QAAQ;EAwB1D,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAwGxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAmDN;;;;;;;;;;UAmDA;EAkBR"}
1
+ {"version":3,"file":"manager.d.cts","names":[],"sources":["../../../src/services/delegation/manager.ts"],"mappings":";;;;;;;;cAsBa;cACA;cAkCA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;KAGU,sBACV;EAAW;EAAoB;EAAiB;GAChD;EAAY;EAAuB;;UAGpB;WACN,aAAa,SAAS;WACtB;WACA;WACA,kBAAkB,eAAe;;UAG3B;EACf,OAAO;EACP;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;cAkFW;mBACM;mBACA;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,SAAS;UAIb;UAIA;cAII;UAIJ;;MAKJ;;EAKJ,YAAY,MAAM,OAAO;;SAMlB,UAAU,UAAU,oBAAoB;;EAO/C,KAAK,KAAK,SAAS,SAAS;;EAyB5B;;EAMA,kBAAkB;IAAQ;IAAY;;;;;;;;EAchC,UAAU,4BAAwC,QAAQ;EAwB1D,OAAO,gBAAgB,SAAS,gBAAgB,QAAQ;EAmHxD,OAAO,iBAAiB,QAAQ;;UAiB9B;;;;;;;;UAkBA;;;;;;;;;UAcA;;;;;;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAmDN;;;;;;;;;;UAmDA;EAkBR;;EAMA"}
@@ -3,7 +3,8 @@ import { TaskFailureReporter } from "../../types/telemetry.mjs";
3
3
  import { TaskStore } from "../../adapters/store/taskStore.mjs";
4
4
  import { MAX_BRIEF_FILES } from "../../types/delegation.mjs";
5
5
  import { InlineAgent } from "@agimon-ai/doompi-extension-contracts/subagent-tool";
6
- import { EventBusLike } from "@agimon-ai/doompi-extension-contracts/protocol";
6
+ import { DoomDelegationService } from "@agimon-ai/doompi-extension-contracts/delegation";
7
+ import { Context } from "@deepseek-ai/cordis";
7
8
  //#region src/services/delegation/manager.d.ts
8
9
  declare const NOTIFY_CUSTOM_TYPE = "doom-task-notify";
9
10
  declare const BACKGROUND_WORK_PROVIDER = "doom-task";
@@ -41,7 +42,6 @@ interface DelegationPlatform {
41
42
  readonly formatBriefPath: (entry: string, cwd: string) => string;
42
43
  }
43
44
  interface DelegationManagerOptions {
44
- events: EventBusLike;
45
45
  store: TaskStore;
46
46
  cwd: string;
47
47
  platform: DelegationPlatform;
@@ -81,9 +81,9 @@ interface DelegationOutcome {
81
81
  /**
82
82
  * Owns the lifecycle of tasks delegated to subagents.
83
83
  *
84
- * Delegation rides the Doom Team event bus rather than spawning
84
+ * Delegation rides Team's injected Cordis service rather than spawning
85
85
  * processes directly, so doom-task stays decoupled from the subagent runtime
86
- * and degrades to a clear error when that runtime is not loaded.
86
+ * and degrades to a clear error when that service is not loaded.
87
87
  *
88
88
  * Liveness rule: every entry in `pendingTasks` has a timer armed against it, so
89
89
  * a delegation always has a deadline no matter which phase it is in. Losing
@@ -95,7 +95,7 @@ declare class DelegationManager {
95
95
  private readonly pendingTasks;
96
96
  private readonly timers;
97
97
  private readonly subscriptions;
98
- private protocol;
98
+ private service;
99
99
  constructor(options: DelegationManagerOptions);
100
100
  private now;
101
101
  private nowMs;
@@ -107,8 +107,10 @@ declare class DelegationManager {
107
107
  progressFor(task: Task): DelegationProgress | undefined;
108
108
  /** Displayed runtime duration, rebased from the latest child observation. */
109
109
  static elapsedMs(progress: DelegationProgress, nowMs?: number): number;
110
- /** Idempotent: a session restart re-subscribes without stacking handlers. */
111
- start(): void;
110
+ /** Rebind to the active Team service without stacking lifecycle listeners. */
111
+ bind(ctx: Context, service: DoomDelegationService): () => void;
112
+ /** Remove only the cross-package binding; task state and watchdogs remain live. */
113
+ unbind(): void;
112
114
  /** Items still in flight, surfaced so auto-stop will not kill the harness. */
113
115
  listActiveWork(): Array<{
114
116
  id: string;
@@ -128,9 +130,9 @@ declare class DelegationManager {
128
130
  /**
129
131
  * Fail a delegation that nobody acknowledged.
130
132
  *
131
- * The bus cannot be probed for listeners, so silence is the only available
132
- * signal that the subagents runtime is absent. Without this the task would
133
- * sit in `requested` forever.
133
+ * Provider loss or a stalled Team runtime can still leave a dispatched
134
+ * request silent. Without this acknowledgement deadline the task would sit
135
+ * in `requested` forever.
134
136
  */
135
137
  private armStartedTimeout;
136
138
  /**
@@ -145,7 +147,7 @@ declare class DelegationManager {
145
147
  /**
146
148
  * Guarantee a cancel reaches a terminal state.
147
149
  *
148
- * Emitting the cancel event is a request, not an outcome: a runtime that has
150
+ * Calling the service is a request, not an outcome: a runtime that has
149
151
  * already forgotten the request answers nothing at all. The window still
150
152
  * favours a real response, which carries the run's partial output.
151
153
  */
@@ -182,6 +184,8 @@ declare class DelegationManager {
182
184
  */
183
185
  private patchDelegation;
184
186
  dispose(): void;
187
+ /** Clear one Pi session's transient delegation state without losing service injection. */
188
+ reset(): void;
185
189
  }
186
190
  //#endregion
187
191
  export { AssignOptions, BACKGROUND_WORK_PROVIDER, DelegationManager, DelegationManagerOptions, DelegationNotifier, DelegationOutcome, DelegationPlatform, DelegationProgress, ERR_CANCEL_UNACKNOWLEDGED, ERR_CHILD_SESSION, ERR_NO_RUNTIME, MAX_BRIEF_FILES, NOTIFY_CUSTOM_TYPE };
@@ -1 +1 @@
1
- {"version":3,"file":"manager.d.mts","names":[],"sources":["../../../src/services/delegation/manager.ts"],"mappings":";;;;;;;cA2Ba;cACA;cAkCA;cAEA;cAEA;;;UAII;EACf;EACA;EACA;EACA;;EAEA;;EAEA;;;EAGA;EACA;;KAGU,sBACV;EAAW;EAAoB;EAAiB;GAChD;EAAY;EAAuB;;UAGpB;WACN,aAAa,SAAS;WACtB;WACA;WACA,kBAAkB,eAAe;;UAG3B;EACf,QAAQ;EACR,OAAO;EACP;EACA,UAAU;EACV,SAAS;EACT;EACA;EACA;;EAEA;;EAEA;EACA;EACA;;EAEA,gBAAgB,gBAAgB;;EAEhC,SAAS;;UAGM;EACf;EACA,cAAc;EACd;;;EAGA;;;EAGA;EACA;EACA;EACA,SAAS;;UAGM;EACf;EACA;;;;;;;;;;;;;cAkFW;mBACM;mBACA;mBACA;mBACA;mBACA;UACT;EAEI,YAAA,SAAS;UAIb;UAIA;cAII;UAI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;;;UAuBA;UAUA;UAOA;;UAOA;UAKA;UAoCA;UAsBM;;;;;;;;;;;;;UA4BA;UAmDN;;;;;;;;;;UAmDA;EAkBR;;EAMA"}
@@ -1,6 +1,6 @@
1
- import{MAX_BRIEF_FILES as e}from"../../types/delegation.mjs";import{isBlocked as t,isTaskListComplete as n}from"../store/taskGraph.mjs";import{isDelegationActive as r}from"../store/types.mjs";import{TASK_EVENT as i}from"../../types/telemetry.mjs";import{reconcileOrphanedDelegations as a}from"../store/reconcile.mjs";import{DelegationAccepted as o,DelegationCancelled as s,DelegationFinished as c,DelegationRequested as l,DelegationStarted as u,DelegationUpdated as d}from"@agimon-ai/doompi-extension-contracts/delegation";import{createProtocolRuntime as f}from"@agimon-ai/doompi-extension-contracts/protocol";const p=`doom-task-notify`,m=`doom-task`,h=`completed`,g=`failed`,_=`cancelled`,v=`task.id`,y=`delegation.request_id`,b=`delegation.agent_name`,x=`delegation.context_present`,S=`delegation.context_file_count`,C=`delegation.context_notes_length`,w=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,T=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,E=`Subagent did not acknowledge the cancel request`;function D(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function O(e){return e instanceof Error?e.message:String(e)}function k(e,t,n){let r=new Set;for(let i of e.relevantFiles??[]){if(r.size>=12)break;let e=n.formatBriefPath(i.trim(),t);e&&e!==`.`&&r.add(e)}return{files:[...r],notes:D(e.priorFindings?.trim(),1500)}}function A(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
1
+ import{MAX_BRIEF_FILES as e}from"../../types/delegation.mjs";import{isBlocked as t,isTaskListComplete as n}from"../store/taskGraph.mjs";import{isDelegationActive as r}from"../store/types.mjs";import{TASK_EVENT as i}from"../../types/telemetry.mjs";import{reconcileOrphanedDelegations as a}from"../store/reconcile.mjs";import{DOOM_DELEGATION_ACCEPTED_EVENT as o,DOOM_DELEGATION_FINISHED_EVENT as s,DOOM_DELEGATION_STARTED_EVENT as c,DOOM_DELEGATION_UPDATED_EVENT as l}from"@agimon-ai/doompi-extension-contracts/delegation";const u=`doom-task-notify`,d=`doom-task`,f=`completed`,p=`failed`,m=`cancelled`,h=`task.id`,g=`delegation.request_id`,_=`delegation.agent_name`,v=`delegation.context_present`,y=`delegation.context_file_count`,b=`delegation.context_notes_length`,x=`No subagent runtime responded. Delegation needs the subagents extension — relaunch doom-pi with agents enabled.`,S=`assign is only available in the main session. Update this task directly instead of re-delegating it.`,C=`Subagent did not acknowledge the cancel request`;function w(e,t=4e3){if(e)return e.length<=t?e:`${e.slice(0,t)}\n… (truncated)`}function T(e){return e instanceof Error?e.message:String(e)}function E(e,t,n){let r=new Set;for(let i of e.relevantFiles??[]){if(r.size>=12)break;let e=n.formatBriefPath(i.trim(),t);e&&e!==`.`&&r.add(e)}return{files:[...r],notes:w(e.priorFindings?.trim(),1500)}}function D(e,t,n){let r=[`Task #${e.id}: ${e.subject}`];if(e.description&&r.push(e.description),t&&r.push(t),n.files.length>0||n.notes){let e=[`Parent context — consume before repository discovery:`];n.files.length>0&&e.push(`- Parent-verified files (read these first with direct reads): ${n.files.join(`, `)}`),n.notes&&e.push(`- Established facts (do not re-derive unless direct evidence contradicts them): ${n.notes}`),e.push(`This pack satisfies initial repository/context exploration. Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`),r.push(e.join(`
2
2
  `))}return r.push(`Coordination: work directly without changing the task record; ask main through intercom only for blockers or decisions; report changed files and verification when done.`),r.join(`
3
3
 
4
- `)}var j=class e{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];protocol;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.options.platform.environment.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}start(){if(this.subscriptions.length>0)return;let e=this.options.getSessionId?.();e&&(this.protocol=f({bus:this.options.events,source:`@agimon-ai/doompi-task`,sessionId:e}),this.subscriptions.push(this.protocol.onNotification(o,e=>{this.handleAccepted(e)}),this.protocol.onNotification(u,e=>{this.handleStarted(e)}),this.protocol.onNotification(d,e=>{this.handleUpdate(e)}),this.protocol.onNotification(c,e=>{this.handleResponse(e).catch(t=>{this.report(i.delegationResponseFailed,t,{[y]:e.requestId})})})))}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(e=()=>!0){let{value:t}=await this.options.store.mutate(t=>{if(!e())return{value:[]};let n=a(t,this.now(),void 0,{pid:this.options.platform.processId,liveRequestIds:new Set(this.pendingTasks.keys())});return n.orphaned.length===0?{value:[]}:{document:n.document,value:n.orphaned}});if(!e())return[];for(let e of t)this.options.report?.warn(i.delegationOrphaned,Error(e.delegation?.result?.error??``),{[v]:e.id,...e.delegation?.agent?{[b]:e.delegation.agent}:{},...e.delegation?.pid===void 0?{}:{"delegation.pid":e.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(e,n){let a=n.agent?.trim();if(!a)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:T};if(n.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let o=this.options.platform.createRequestId(),s=this.now(),c=k(n,this.options.cwd,this.options.platform),{value:u}=await this.options.store.mutate(i=>{let c=i.tasks.findIndex(t=>t.id===e);if(c===-1)return{value:{ok:!1,message:`#${e} not found`}};let l=i.tasks[c];if(l.status===`deleted`)return{value:{ok:!1,message:`#${e} is deleted`}};if(l.status===h)return{value:{ok:!1,message:`#${e} is already completed`}};if(r(l))return{value:{ok:!1,message:`#${e} is already delegated to ${l.delegation?.agent}`}};if(t(i.tasks,l))return{value:{ok:!1,message:`#${e} is blocked by ${(l.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let u={requestId:o,agent:a,state:`requested`,pid:this.options.platform.processId,startedAt:s,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...n.model?{model:n.model}:{}},d=[...i.tasks];return d[c]={...l,owner:a,updatedAt:s,delegation:u},{document:{...i,tasks:d},value:{ok:!0,message:``,task:d[c]}}});if(!u.ok||!u.task)return{ok:!1,message:u.message};let d=c.notes?.length??0;this.pendingTasks.set(o,e),this.progress.set(o,{agent:a,contextFileCount:c.files.length,contextNotesLength:d}),this.armStartedTimeout(o);let f={requestId:o,taskId:e,agent:a,...n.inlineAgent?{inlineAgent:n.inlineAgent}:{},prompt:A(u.task,n.instructions,c),...n.context?{context:n.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(u.task.id),subject:u.task.subject},...n.model?{model:n.model}:{}};try{if(!this.protocol)throw Error(w);this.protocol.notify(l,f)}catch(t){this.report(i.delegationRequestFailed,t,{[v]:e,[y]:o,[b]:a});let n=O(t);return await this.settle(o,g,{status:g,error:`Delegation request failed: ${n}`}),{ok:!1,message:`Could not dispatch #${e} to ${a}: ${n}`}}return this.options.report?.event(i.delegationAssigned,{[v]:e,[y]:o,[b]:a,[x]:c.files.length>0||d>0,[S]:c.files.length,[C]:d,"delegation.brief_length":f.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${e} to ${a} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!r(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:n}=t.delegation;return this.protocol?.notify(s,{requestId:n}),this.armCancelTimeout(n),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,t,n,r=i.delegationSettleFailed){this.settle(e,t,n).catch(t=>{this.report(r,t,{[y]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,g,{status:g,error:w})})}armRunTimeout(e){let t=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+t,()=>{let t=this.pendingTasks.get(e),n=this.progress.get(e)?.agent,r=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(i.delegationTimedOut,r,{...t===void 0?{}:{[v]:t},[y]:e,...n?{[b]:n}:{}}),this.protocol?.notify(s,{requestId:e,reason:r.message}),this.settleDetached(e,g,{status:`timed_out`,error:r.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,_,{status:_,error:E})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:t}=e,n=this.pendingTasks.get(e.requestId);if(n===void 0)return;this.armRunTimeout(e.requestId);let r=this.progress.get(e.requestId);r&&this.progress.set(e.requestId,{...r,durationMs:r.durationMs??0,durationObservedAt:r.durationObservedAt??this.nowMs()}),this.options.store.mutate(n=>this.patchDelegation(n,e.requestId,(e,n)=>({...e,status:e.status===h?e.status:`in_progress`,delegation:{...n,state:`running`,startedAt:n.startedAt??this.now(),...t?{runId:t}:{}}}))).then(()=>this.options.onChange?.()).catch(t=>{this.report(i.delegationStartFailed,t,{[v]:n,[y]:e.requestId})})}handleUpdate(t){let n=this.progress.get(t.requestId);if(!n)return;let r=this.nowMs(),i=e.elapsedMs(n,r),a=t.durationMs!==void 0;this.progress.set(t.requestId,{...n,currentTool:t.currentTool??n.currentTool,toolCount:t.toolCount===void 0?n.toolCount:Math.max(n.toolCount??0,t.toolCount),tokens:t.tokens===void 0?n.tokens:Math.max(n.tokens??0,t.tokens),durationMs:a?Math.max(i,t.durationMs):n.durationMs,durationObservedAt:a?r:n.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===h&&!e.error?h:e.status===_?_:g;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:D(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,t,r){let a=this.pendingTasks.get(e);if(a===void 0)return;this.pendingTasks.delete(e),this.clearTimer(e);let o=this.progress.get(e);this.progress.delete(e);let s=this.now(),c;try{let{value:n}=await this.options.store.mutate(n=>this.patchDelegation(n,e,(e,n)=>({...e,status:t===h?h:t===_?`pending`:g,updatedAt:s,delegation:{...n,state:t,endedAt:s,...r?{result:r}:{}}})));c=n}catch(t){this.report(i.delegationSettleFailed,t,{[v]:a,[y]:e})}this.options.onChange?.();let l=c?.delegation?.agent??o?.agent??`subagent`,u=c?.subject??`#${a}`;this.options.report?.event(i.delegationCompleted,{[v]:a,[y]:e,[b]:l,"delegation.outcome":t,[x]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[S]:o?.contextFileCount??0,[C]:o?.contextNotesLength??0,...r?.toolCount===void 0?{}:{"delegation.tool_count":r.toolCount},...r?.durationMs===void 0?{}:{"delegation.duration_ms":r.durationMs}});let d=t===h&&c!==void 0&&n(this.options.store.snapshot.tasks);this.notifyModel(t,a,u,l,r,d)}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let s=[e===h?`Subagent ${r} completed task #${t}: ${n}`:e===_?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&s.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&s.push(`Error: ${i.error}`),i?.output&&s.push(``,i.output),i?.outputPath&&s.push(``,`Full output: ${i.outputPath}`);try{o({customType:p,content:s.join(`
5
- `),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,n){let i=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!r(a))return{value:a};let o=n(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){for(let e of this.subscriptions)e();this.subscriptions.length=0,this.protocol=void 0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};export{m as BACKGROUND_WORK_PROVIDER,j as DelegationManager,E as ERR_CANCEL_UNACKNOWLEDGED,T as ERR_CHILD_SESSION,w as ERR_NO_RUNTIME,e as MAX_BRIEF_FILES,p as NOTIFY_CUSTOM_TYPE};
4
+ `)}var O=class e{options;progress=new Map;pendingTasks=new Map;timers=new Map;subscriptions=[];service;constructor(e){this.options=e}now(){return this.options.now?.()??new Date().toISOString()}nowMs(){return this.options.nowMs?.()??Date.now()}get runTimeoutMs(){return this.options.runTimeoutMs??12e5}report(e,t,n){this.options.report?.error(e,t,n)}get isChildSession(){return!!this.options.platform.environment.PI_SUBAGENT_CHILD}progressFor(e){let t=e.delegation?.requestId;return t?this.progress.get(t):void 0}static elapsedMs(e,t=Date.now()){let n=e.durationMs??0,r=e.durationObservedAt??t;return n+Math.max(0,t-r)}bind(e,t){return this.unbind(),this.service=t,this.subscriptions.push(e.on(o,e=>{this.handleAccepted(e)}),e.on(c,e=>{this.handleStarted(e)}),e.on(l,e=>{this.handleUpdate(e)}),e.on(s,e=>{this.handleResponse(e).catch(t=>{this.report(i.delegationResponseFailed,t,{[g]:e.requestId})})})),()=>{this.service===t&&this.unbind()}}unbind(){for(let e of this.subscriptions.splice(0))e();this.service=void 0}listActiveWork(){let e=this.options.getSessionId?.()??``;return[...this.pendingTasks.entries()].map(([t,n])=>({id:`task-${n}:${t}`,sessionId:e}))}async reconcile(e=()=>!0){let{value:t}=await this.options.store.mutate(t=>{if(!e())return{value:[]};let n=a(t,this.now(),void 0,{pid:this.options.platform.processId,liveRequestIds:new Set(this.pendingTasks.keys())});return n.orphaned.length===0?{value:[]}:{document:n.document,value:n.orphaned}});if(!e())return[];for(let e of t)this.options.report?.warn(i.delegationOrphaned,Error(e.delegation?.result?.error??``),{[h]:e.id,...e.delegation?.agent?{[_]:e.delegation.agent}:{},...e.delegation?.pid===void 0?{}:{"delegation.pid":e.delegation.pid}});return t.length>0&&this.options.onChange?.(),t}async assign(e,n){let a=n.agent?.trim();if(!a)return{ok:!1,message:`agent required for assign`};if(this.isChildSession)return{ok:!1,message:S};if(n.signal?.aborted)return{ok:!1,message:`delegation cancelled before it started`};let o=this.options.platform.createRequestId(),s=this.now(),c=E(n,this.options.cwd,this.options.platform),{value:l}=await this.options.store.mutate(i=>{let c=i.tasks.findIndex(t=>t.id===e);if(c===-1)return{value:{ok:!1,message:`#${e} not found`}};let l=i.tasks[c];if(l.status===`deleted`)return{value:{ok:!1,message:`#${e} is deleted`}};if(l.status===f)return{value:{ok:!1,message:`#${e} is already completed`}};if(r(l))return{value:{ok:!1,message:`#${e} is already delegated to ${l.delegation?.agent}`}};if(t(i.tasks,l))return{value:{ok:!1,message:`#${e} is blocked by ${(l.blockedBy??[]).map(e=>`#${e}`).join(`, `)}`}};let u={requestId:o,agent:a,state:`requested`,pid:this.options.platform.processId,startedAt:s,...this.options.getSessionId?.()?{sessionId:this.options.getSessionId()}:{},...n.model?{model:n.model}:{}},d=[...i.tasks];return d[c]={...l,owner:a,updatedAt:s,delegation:u},{document:{...i,tasks:d},value:{ok:!0,message:``,task:d[c]}}});if(!l.ok||!l.task)return{ok:!1,message:l.message};let u=c.notes?.length??0;this.pendingTasks.set(o,e),this.progress.set(o,{agent:a,contextFileCount:c.files.length,contextNotesLength:u}),this.armStartedTimeout(o);let d={requestId:o,taskId:e,agent:a,...n.inlineAgent?{inlineAgent:n.inlineAgent}:{},prompt:D(l.task,n.instructions,c),...n.context?{context:n.context}:{},cwd:this.options.cwd,artifacts:!0,timeoutMs:this.runTimeoutMs,runMode:`detached`,teamTask:{id:String(l.task.id),subject:l.task.subject},...n.model?{model:n.model}:{}};try{let t=this.service;if(!t)throw Error(x);t.request(d).catch(t=>{this.report(i.delegationRequestFailed,t,{[h]:e,[g]:o,[_]:a}),this.settleDetached(o,p,{status:p,error:`Delegation request failed: ${T(t)}`})})}catch(t){this.report(i.delegationRequestFailed,t,{[h]:e,[g]:o,[_]:a});let n=T(t);return await this.settle(o,p,{status:p,error:`Delegation request failed: ${n}`}),{ok:!1,message:`Could not dispatch #${e} to ${a}: ${n}`}}return this.options.report?.event(i.delegationAssigned,{[h]:e,[g]:o,[_]:a,[v]:c.files.length>0||u>0,[y]:c.files.length,[b]:u,"delegation.brief_length":d.prompt.length}),this.options.onChange?.(),{ok:!0,message:`Delegated #${e} to ${a} in the background. It runs independently of this turn and will notify you when it finishes. Continue non-overlapping work, or end your turn.`}}async cancel(e){let t=this.options.store.read().tasks.find(t=>t.id===e);if(!t)return{ok:!1,message:`#${e} not found`};if(!t.delegation||!r(t))return{ok:!1,message:`#${e} has no running delegation`};let{requestId:n}=t.delegation;return this.service?.cancel({requestId:n}),this.armCancelTimeout(n),{ok:!0,message:`Cancelling delegation for #${e} (${t.delegation.agent})`}}settleDetached(e,t,n,r=i.delegationSettleFailed){this.settle(e,t,n).catch(t=>{this.report(r,t,{[g]:e})})}armStartedTimeout(e){this.armTimer(e,this.options.startedTimeoutMs??5e3,()=>{this.settleDetached(e,p,{status:p,error:x})})}armRunTimeout(e){let t=Math.min(6e4,this.runTimeoutMs);this.armTimer(e,this.runTimeoutMs+t,()=>{let t=this.pendingTasks.get(e),n=this.progress.get(e)?.agent,r=Error(`Delegation produced no result within ${this.runTimeoutMs}ms`);this.options.report?.warn(i.delegationTimedOut,r,{...t===void 0?{}:{[h]:t},[g]:e,...n?{[_]:n}:{}}),this.service?.cancel({requestId:e,reason:r.message}),this.settleDetached(e,p,{status:`timed_out`,error:r.message})})}armCancelTimeout(e){this.pendingTasks.has(e)&&this.armTimer(e,this.options.cancelTimeoutMs??1e4,()=>{this.settleDetached(e,m,{status:m,error:C})})}armTimer(e,t,n){this.clearTimer(e);let r=setTimeout(n,t);r.unref?.(),this.timers.set(e,r)}clearTimer(e){let t=this.timers.get(e);t&&clearTimeout(t),this.timers.delete(e)}handleAccepted(e){this.pendingTasks.has(e.requestId)&&this.armRunTimeout(e.requestId)}handleStarted(e){let{runId:t}=e,n=this.pendingTasks.get(e.requestId);if(n===void 0)return;this.armRunTimeout(e.requestId);let r=this.progress.get(e.requestId);r&&this.progress.set(e.requestId,{...r,durationMs:r.durationMs??0,durationObservedAt:r.durationObservedAt??this.nowMs()}),this.options.store.mutate(n=>this.patchDelegation(n,e.requestId,(e,n)=>({...e,status:e.status===f?e.status:`in_progress`,delegation:{...n,state:`running`,startedAt:n.startedAt??this.now(),...t?{runId:t}:{}}}))).then(()=>this.options.onChange?.()).catch(t=>{this.report(i.delegationStartFailed,t,{[h]:n,[g]:e.requestId})})}handleUpdate(t){let n=this.progress.get(t.requestId);if(!n)return;let r=this.nowMs(),i=e.elapsedMs(n,r),a=t.durationMs!==void 0;this.progress.set(t.requestId,{...n,currentTool:t.currentTool??n.currentTool,toolCount:t.toolCount===void 0?n.toolCount:Math.max(n.toolCount??0,t.toolCount),tokens:t.tokens===void 0?n.tokens:Math.max(n.tokens??0,t.tokens),durationMs:a?Math.max(i,t.durationMs):n.durationMs,durationObservedAt:a?r:n.durationObservedAt}),this.options.onChange?.()}async handleResponse(e){if(!this.pendingTasks.has(e.requestId))return;let t=e.status===f&&!e.error?f:e.status===m?m:p;await this.settle(e.requestId,t,{status:e.status,error:e.error,output:w(e.output),outputPath:e.outputPath,sessionFile:e.sessionFile,durationMs:e.durationMs,toolCount:e.toolCount})}async settle(e,t,r){let a=this.pendingTasks.get(e);if(a===void 0)return;this.pendingTasks.delete(e),this.clearTimer(e);let o=this.progress.get(e);this.progress.delete(e);let s=this.now(),c;try{let{value:n}=await this.options.store.mutate(n=>this.patchDelegation(n,e,(e,n)=>({...e,status:t===f?f:t===m?`pending`:p,updatedAt:s,delegation:{...n,state:t,endedAt:s,...r?{result:r}:{}}})));c=n}catch(t){this.report(i.delegationSettleFailed,t,{[h]:a,[g]:e})}this.options.onChange?.();let l=c?.delegation?.agent??o?.agent??`subagent`,u=c?.subject??`#${a}`;this.options.report?.event(i.delegationCompleted,{[h]:a,[g]:e,[_]:l,"delegation.outcome":t,[v]:(o?.contextFileCount??0)>0||(o?.contextNotesLength??0)>0,[y]:o?.contextFileCount??0,[b]:o?.contextNotesLength??0,...r?.toolCount===void 0?{}:{"delegation.tool_count":r.toolCount},...r?.durationMs===void 0?{}:{"delegation.duration_ms":r.durationMs}});let d=t===f&&c!==void 0&&n(this.options.store.snapshot.tasks);this.notifyModel(t,a,u,l,r,d)}notifyModel(e,t,n,r,i,a){let o=this.options.notify;if(!o)return;let s=[e===f?`Subagent ${r} completed task #${t}: ${n}`:e===m?`Subagent ${r} was cancelled on task #${t}: ${n} (returned to pending)`:`Subagent ${r} failed task #${t}: ${n}`];a&&s.push(``,`All tasks are completed. Review the full task list once more, then close it with task {"action":"clear"}.`),i?.error&&s.push(`Error: ${i.error}`),i?.output&&s.push(``,i.output),i?.outputPath&&s.push(``,`Full output: ${i.outputPath}`);try{o({customType:u,content:s.join(`
5
+ `),display:!0},{triggerTurn:!0,deliverAs:`steer`})}catch(e){this.options.onNotifyError(e,t)}}patchDelegation(e,t,n){let i=e.tasks.findIndex(e=>e.delegation?.requestId===t);if(i===-1)return{value:void 0};let a=e.tasks[i];if(!r(a))return{value:a};let o=n(a,a.delegation);if(o===a)return{value:a};let s=[...e.tasks];return s[i]=o,{document:{...e,tasks:s},value:o}}dispose(){this.unbind(),this.reset()}reset(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear(),this.pendingTasks.clear(),this.progress.clear()}};export{d as BACKGROUND_WORK_PROVIDER,O as DelegationManager,C as ERR_CANCEL_UNACKNOWLEDGED,S as ERR_CHILD_SESSION,x as ERR_NO_RUNTIME,e as MAX_BRIEF_FILES,u as NOTIFY_CUSTOM_TYPE};
6
6
  //# sourceMappingURL=manager.mjs.map