{"version":3,"file":"index.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/index.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  type InlineAgent,\n} from '@agimon-ai/doompi-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { isBlocked, isTaskListComplete } from '../../models/taskGraph';\nimport { MAX_BRIEF_FILES } from '../../types/delegation';\nimport { TASK_EVENT, type TaskEventName, type TaskFailureReporter } from '../../types/telemetry';\nimport { reconcileOrphanedDelegations } from '../reconcile';\nimport type { TaskStore } from '../taskStore';\n\nexport { MAX_BRIEF_FILES };\nimport { isDelegationActive, type Task, type TaskDelegation, type TaskDocument } from '../../models/task';\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\ninterface PendingTask {\n  readonly taskId: number;\n  readonly sessionId?: string;\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, PendingTask>();\n  private readonly settlingRequests = new Set<string>();\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    return [...this.pendingTasks.entries()].flatMap(([requestId, pending]) =>\n      pending.sessionId ? [{ id: `task-${pending.taskId}:${requestId}`, sessionId: pending.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 sessionId = this.options.getSessionId?.();\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        ...(sessionId ? { sessionId } : {}),\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, sessionId });\n    this.progress.set(requestId, { agent, contextFileCount: context.files.length, contextNotesLength });\n    this.armStartedTimeout(requestId);\n    this.options.onChange?.();\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    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)?.taskId;\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)?.taskId;\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   * The request is claimed in `settlingRequests` while it remains published as\n   * active work. It is removed only after the terminal state and model notification\n   * have been handed off, so an auto-stop observer cannot end the session between\n   * receiving the result and delivering it to the model.\n   */\n  private async settle(requestId: string, state: SettlementState, result: TaskDelegation['result']): Promise<void> {\n    const pending = this.pendingTasks.get(requestId);\n    if (!pending || this.settlingRequests.has(requestId)) return;\n    this.settlingRequests.add(requestId);\n    this.clearTimer(requestId);\n    const { taskId } = pending;\n    const progress = this.progress.get(requestId);\n\n    try {\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      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    } finally {\n      this.pendingTasks.delete(requestId);\n      this.progress.delete(requestId);\n      this.settlingRequests.delete(requestId);\n      this.options.onChange?.();\n    }\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    const changed = this.pendingTasks.size > 0 || this.progress.size > 0;\n    for (const timer of this.timers.values()) clearTimeout(timer);\n    this.timers.clear();\n    this.pendingTasks.clear();\n    this.settlingRequests.clear();\n    this.progress.clear();\n    if (changed) this.options.onChange?.();\n  }\n}\n"],"mappings":";;;;;;;AAuBA,MAAa,qBAAqB;AAClC,MAAa,2BAA2B;AAExC,MAAM,6BAA6B;AACnC,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,oBAAoB;;;;;AAK1B,MAAM,kBAAkB;AACxB,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,iBAAiC;AAEvC,MAAM,oBAAoB;AAC1B,MAAM,uBAAuB;AAG7B,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,4BAA4B;AAClC,MAAM,+BAA+B;AACrC,MAAM,iCAAiC;AACvC,MAAM,yBAAyB;AAC/B,MAAM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