{"version":3,"file":"teamRuntime-DtprPI0M.mjs","names":["isTerminal","PROVIDER_SEPARATOR","DEFAULT_TIMEOUT_MS","HASH_ALGORITHM"],"sources":["../src/services/asyncJobTracker/index.ts","../src/services/config/index.ts","../src/services/admissionGate/index.ts","../src/services/versioned/index.ts","../src/services/agentIdentity/index.ts","../src/services/agentSkills/index.ts","../src/services/depthGuard/index.ts","../src/services/errors/index.ts","../src/services/modelInfo/index.ts","../src/services/modelResolution/index.ts","../src/services/modelScope/index.ts","../src/services/modelFallback/index.ts","../src/services/runtimeRegistry/index.ts","../src/services/runWithConcurrency/index.ts","../src/services/spawnPlan/index.ts","../src/services/delegationBridge/index.ts","../src/services/spawnHandshake/index.ts","../src/services/asyncExecution/index.ts","../src/services/suspendedRuns/index.ts","../src/services/sessionLifecycle/index.ts","../src/services/directRunBackgroundWork/index.ts","../src/services/subagentPolicyService/index.ts","../src/services/managementActions/index.ts","../src/services/mcpDirectToolAllowlist/index.ts","../src/services/nativeRunCoordinator/index.ts","../src/services/boundedKeySet/index.ts","../src/services/nativeTeamChannel/index.ts","../src/services/completionBatcher/index.ts","../src/services/notify/index.ts","../src/services/pollScheduler/index.ts","../src/services/operationJournal/index.ts","../src/services/displayFormat/index.ts","../src/services/fleetTranscript/index.ts","../src/services/statusViews/index.ts","../src/services/subagentTool/index.ts","../src/services/subagentWait/index.ts","../src/services/teamRuntime/index.ts"],"sourcesContent":["import type { ActivityState } from '../../types';\nimport type { ExternalRunProjection } from '../externalProcessIpc';\nimport type { SessionScope } from '../sessionPaths';\n\nexport const TERMINAL_ASYNC_JOB_STATES = new Set(['complete', 'completed', 'failed', 'paused', 'stopped']);\nconst DEFAULT_RETENTION_MS = 10 * 60_000;\n\ntype ExternalResult = Record<string, unknown>;\n\nexport interface TrackedAsyncJob {\n  runId: string;\n  agent?: string;\n  /** Generated addressable identity, for example `alan-reviewer-3`. */\n  identity?: string;\n  /** True when this run came from a one-shot inline agent definition. */\n  inline?: boolean;\n  status: string | undefined;\n  startedAt?: number;\n  updatedAt?: number;\n  error?: string;\n  activityState?: ActivityState;\n  attentionReason?: string;\n  runtime?: string;\n  task?: string;\n  cwd?: string;\n  sessionFile?: string;\n  transcriptPath?: string;\n  summary?: string;\n  native?: boolean;\n  tokens?: number;\n  cost?: number;\n  currentTool?: string;\n  toolCount?: number;\n}\n\nexport interface NativeAsyncJobProjection {\n  runId: string;\n  agent: string;\n  identity?: string;\n  inline?: boolean;\n  task: string;\n  cwd: string;\n  runtime: string;\n  status: string;\n  startedAt: number;\n  updatedAt: number;\n  error?: string;\n  sessionFile?: string;\n  transcriptPath?: string;\n  cost?: number;\n  summary?: string;\n}\n\nexport type TrackedAsyncJobsContract = {\n  track(runId: string, identity?: { identity: string; inline: boolean }): void;\n  untrack(runId: string): void;\n  list(): TrackedAsyncJob[];\n  get(runId: string): TrackedAsyncJob | undefined;\n  reset(): void;\n};\n\nexport type AsyncJobTrackerContract = {\n  forSession(sessionId: string, scope: SessionScope): TrackedAsyncJobsContract;\n  stop(): void;\n};\n\n/**\n * Resolve a caller-supplied id to a tracked run id.\n *\n * Order matters. An exact run id wins, then a unique run-id prefix, and only\n * then a generated identity. A name is checked last so that a friendly name\n * which happens to look like a hex prefix can never shadow a real run.\n */\nexport function resolveTrackedRunId(jobs: TrackedAsyncJobsContract, id: string): string {\n  const runs = jobs.list();\n  const matches = runs.map((job) => job.runId).filter((runId) => runId === id || runId.startsWith(id));\n  const exact = matches.find((runId) => runId === id);\n  if (exact) return exact;\n  if (matches.length === 1) return matches[0]!;\n  if (matches.length === 0) {\n    const wanted = id.trim().toLowerCase();\n    const named = runs.filter((job) => job.identity?.toLowerCase() === wanted);\n    if (named.length === 1) return named[0]!.runId;\n    if (named.length > 1) throw new Error(`Multiple current-session runs are named '${id}'.`);\n    throw new Error(`No current-session run found for '${id}'.`);\n  }\n  throw new Error(`Multiple current-session runs match '${id}'. Use a longer id.`);\n}\n\ninterface SessionJobs {\n  scope: SessionScope;\n  jobs: Map<string, TrackedAsyncJob>;\n  terminalAt: Map<string, number>;\n  handedOff: Set<string>;\n  cleanupTimers: Map<string, ReturnType<typeof setTimeout>>;\n}\n\nfunction isTerminal(status: string | undefined): boolean {\n  return status !== undefined && TERMINAL_ASYNC_JOB_STATES.has(status);\n}\n\nfunction changed(previous: TrackedAsyncJob | undefined, next: TrackedAsyncJob): boolean {\n  if (!previous) return true;\n  return JSON.stringify(previous) !== JSON.stringify(next);\n}\n\nconst ACTIVITY_STATES: ReadonlySet<string> = new Set([\n  'starting',\n  'working',\n  'tool',\n  'waiting_for_reply',\n  'needs_attention',\n  'finalizing',\n  'active_long_running',\n]);\n\nfunction activityState(value: string | undefined): ActivityState | undefined {\n  return value !== undefined && ACTIVITY_STATES.has(value) ? (value as ActivityState) : undefined;\n}\n\nexport class AsyncJobTracker implements AsyncJobTrackerContract {\n  protected readonly retentionMs = DEFAULT_RETENTION_MS;\n  private readonly sessions = new Map<string, SessionJobs>();\n  private readonly listeners = new Map<string, Set<() => void>>();\n\n  private session(sessionId: string, scope: SessionScope): SessionJobs {\n    const existing = this.sessions.get(sessionId);\n    if (existing) {\n      if (existing.scope.scopeKey !== scope.scopeKey)\n        throw new Error(`Session '${sessionId}' is already bound to another scope.`);\n      return existing;\n    }\n    const created: SessionJobs = {\n      scope,\n      jobs: new Map(),\n      terminalAt: new Map(),\n      handedOff: new Set(),\n      cleanupTimers: new Map(),\n    };\n    this.sessions.set(sessionId, created);\n    return created;\n  }\n\n  private invalidate(sessionId: string): void {\n    for (const listener of this.listeners.get(sessionId) ?? []) listener();\n  }\n\n  forSession(sessionId: string, scope: SessionScope): TrackedAsyncJobsContract {\n    if (!sessionId.trim()) throw new Error('Pi session identity is required to track subagent runs.');\n    this.session(sessionId, scope);\n    return {\n      track: (runId, identity) => this.trackInSession(sessionId, runId, identity),\n      untrack: (runId) => this.untrackInSession(sessionId, runId),\n      list: () => this.listInSession(sessionId),\n      get: (runId) => this.getInSession(sessionId, runId),\n      reset: () => this.resetSession(sessionId),\n    };\n  }\n\n  upsertNative(sessionId: string, scope: SessionScope, projection: NativeAsyncJobProjection): void {\n    const session = this.session(sessionId, scope);\n    const previous = session.jobs.get(projection.runId);\n    // `projection` replaces the record wholesale, so anything the tracker knows\n    // and the projection does not carry has to be restated here or it is lost\n    // on the first child event.\n    const next: TrackedAsyncJob = {\n      ...projection,\n      ...((projection.identity ?? previous?.identity) ? { identity: projection.identity ?? previous?.identity } : {}),\n      ...((projection.inline ?? previous?.inline) ? { inline: projection.inline ?? previous?.inline } : {}),\n      native: true,\n    };\n    this.install(sessionId, session, next, previous);\n  }\n\n  getNative(sessionId: string, runId: string): NativeAsyncJobProjection | undefined {\n    const job = this.sessions.get(sessionId)?.jobs.get(runId);\n    return job?.native ? (job as NativeAsyncJobProjection) : undefined;\n  }\n\n  upsertExternal(sessionId: string, scope: SessionScope, projection: ExternalRunProjection): void {\n    const session = this.session(sessionId, scope);\n    const previous = session.jobs.get(projection.runId);\n    const next: TrackedAsyncJob = {\n      runId: projection.runId,\n      agent: projection.agent,\n      // An external runner writes status.json and has never heard of the\n      // identity, so it can only come from what the parent already tracked.\n      ...(previous?.identity === undefined ? {} : { identity: previous.identity }),\n      ...(previous?.inline === undefined ? {} : { inline: previous.inline }),\n      task: projection.task,\n      cwd: projection.cwd,\n      runtime: projection.runtime,\n      status: projection.state,\n      startedAt: projection.startedAt,\n      updatedAt: projection.updatedAt,\n      ...(projection.error === undefined ? {} : { error: projection.error }),\n      ...(projection.summary === undefined ? {} : { summary: projection.summary }),\n      ...(projection.tokens === undefined ? {} : { tokens: projection.tokens }),\n      ...(projection.cost === undefined ? {} : { cost: projection.cost }),\n      ...(projection.currentTool === undefined ? {} : { currentTool: projection.currentTool }),\n      ...(projection.toolCount === undefined ? {} : { toolCount: projection.toolCount }),\n      ...(activityState(projection.activityState) === undefined\n        ? {}\n        : { activityState: activityState(projection.activityState) }),\n      ...(projection.attentionReason === undefined ? {} : { attentionReason: projection.attentionReason }),\n      ...(projection.sessionFile === undefined ? {} : { sessionFile: projection.sessionFile }),\n      ...(projection.transcriptPath === undefined ? {} : { transcriptPath: projection.transcriptPath }),\n    };\n    this.install(sessionId, session, next, previous);\n  }\n\n  markExternalFailed(sessionId: string, scope: SessionScope, runId: string, error: string): void {\n    const session = this.session(sessionId, scope);\n    const previous = session.jobs.get(runId);\n    const now = Date.now();\n    const next: TrackedAsyncJob = {\n      ...(previous ?? { runId }),\n      runId,\n      status: 'failed',\n      error,\n      updatedAt: now,\n    };\n    this.install(sessionId, session, next, previous);\n  }\n\n  acceptExternalResult(sessionId: string, scope: SessionScope, runId: string, result: ExternalResult): boolean {\n    const session = this.session(sessionId, scope);\n    const previous = session.jobs.get(runId);\n    if (!previous) return false;\n    const success = result.success;\n    const state = typeof result.state === 'string' ? result.state : success === false ? 'failed' : 'completed';\n    const summary = typeof result.summary === 'string' ? result.summary : previous.summary;\n    const next: TrackedAsyncJob = {\n      ...previous,\n      status: state,\n      updatedAt: typeof result.updatedAt === 'number' ? result.updatedAt : Date.now(),\n      ...(summary === undefined ? {} : { summary }),\n      ...(typeof result.error === 'string' ? { error: result.error } : {}),\n    };\n    this.install(sessionId, session, next, previous);\n    return true;\n  }\n\n  private install(\n    sessionId: string,\n    session: SessionJobs,\n    next: TrackedAsyncJob,\n    previous: TrackedAsyncJob | undefined,\n  ): void {\n    session.jobs.set(next.runId, next);\n    const terminal = isTerminal(next.status);\n    if (terminal && !isTerminal(previous?.status)) session.terminalAt.set(next.runId, Date.now());\n    if (!terminal) {\n      session.terminalAt.delete(next.runId);\n      session.handedOff.delete(next.runId);\n      this.clearCleanupTimer(session, next.runId);\n    }\n    if (changed(previous, next)) this.invalidate(sessionId);\n  }\n\n  acknowledgeHandoff(sessionId: string, runId: string): void {\n    const session = this.sessions.get(sessionId);\n    const status = session?.jobs.get(runId)?.status;\n    if (!session || !isTerminal(status) || session.handedOff.has(runId)) return;\n    session.handedOff.add(runId);\n    this.invalidate(sessionId);\n    const timer = setTimeout(() => {\n      this.removeIfRetained(sessionId, runId);\n    }, this.retentionMs);\n    timer.unref?.();\n    session.cleanupTimers.set(runId, timer);\n  }\n\n  listBackgroundWork(sessionId: string): TrackedAsyncJob[] {\n    const session = this.sessions.get(sessionId);\n    if (!session) return [];\n    return [...session.jobs.values()].filter((job) => !isTerminal(job.status) || !session.handedOff.has(job.runId));\n  }\n\n  subscribe(sessionId: string, listener: () => void): () => void {\n    if (!sessionId.trim()) throw new Error('Pi session identity is required to subscribe to subagent runs.');\n    const listeners = this.listeners.get(sessionId) ?? new Set<() => void>();\n    listeners.add(listener);\n    this.listeners.set(sessionId, listeners);\n    return () => {\n      listeners.delete(listener);\n      if (listeners.size === 0) this.listeners.delete(sessionId);\n    };\n  }\n\n  private trackInSession(sessionId: string, runId: string, identity?: { identity: string; inline: boolean }): void {\n    const session = this.sessions.get(sessionId);\n    if (!session) throw new Error(`Session '${sessionId}' must be bound to an explicit scope before tracking runs.`);\n    if (!session.jobs.has(runId)) {\n      session.jobs.set(runId, {\n        runId,\n        status: undefined,\n        ...(identity ? { identity: identity.identity, inline: identity.inline } : {}),\n      });\n      this.invalidate(sessionId);\n    }\n  }\n\n  private untrackInSession(sessionId: string, runId: string): void {\n    const session = this.sessions.get(sessionId);\n    if (!session) return;\n    this.clearCleanupTimer(session, runId);\n    const deleted = session.jobs.delete(runId);\n    session.terminalAt.delete(runId);\n    session.handedOff.delete(runId);\n    if (session.jobs.size === 0) this.sessions.delete(sessionId);\n    if (deleted) this.invalidate(sessionId);\n  }\n\n  private removeIfRetained(sessionId: string, runId: string): void {\n    const session = this.sessions.get(sessionId);\n    if (!session || !session.handedOff.has(runId)) return;\n    session.cleanupTimers.delete(runId);\n    this.untrackInSession(sessionId, runId);\n  }\n\n  private clearCleanupTimer(session: SessionJobs, runId: string): void {\n    const timer = session.cleanupTimers.get(runId);\n    if (timer !== undefined) {\n      clearTimeout(timer);\n      session.cleanupTimers.delete(runId);\n    }\n  }\n\n  private resetSession(sessionId: string): void {\n    const session = this.sessions.get(sessionId);\n    if (!session) return;\n    for (const timer of session.cleanupTimers.values()) clearTimeout(timer);\n    const hadJobs = session.jobs.size > 0;\n    this.sessions.delete(sessionId);\n    if (hadJobs) this.invalidate(sessionId);\n  }\n\n  private listInSession(sessionId: string): TrackedAsyncJob[] {\n    return [...(this.sessions.get(sessionId)?.jobs.values() ?? [])];\n  }\n\n  private getInSession(sessionId: string, runId: string): TrackedAsyncJob | undefined {\n    return this.sessions.get(sessionId)?.jobs.get(runId);\n  }\n\n  stop(): void {\n    for (const session of this.sessions.values()) {\n      for (const timer of session.cleanupTimers.values()) clearTimeout(timer);\n    }\n    this.sessions.clear();\n    this.listeners.clear();\n  }\n}\n","/**\n * `subagent` tool config file: read/write, and the scoped `ExtensionConfig`\n * shape this v1 tool surface actually consumes.\n *\n * PORTED FROM `doom-pi-subagents/src/extension/config.ts`, WITH THE CONFIG\n * SHAPE DELIBERATELY NARROWED, NOT COPIED WHOLESALE:\n * The predecessor's `ExtensionConfig` also carries TUI-rendering fields\n * (`fleetView`, `fleetViewPlacement`, `asyncWidget`) and fields owned by\n * ports still in progress elsewhere (`intercomBridge` is G5's,\n * `proactiveSkillSubagents` has no owner in this package yet). Modeling\n * those here would mean guessing a shape for something this task does not\n * read and cannot verify, rather than the domain that actually owns each\n * field defining it when it lands. `asyncByDefault`/`forceTopLevelAsync`\n * are dropped outright, the config-level twin of `schemas.ts` dropping the\n * `async` parameter - there is no other mode to default toward or force\n * away from.\n *\n * `toolDescriptionMode` IS kept, unlike the TUI fields above: it selects\n * which markdown text becomes the `ToolDefinition.description` this tool\n * registers - what the MODEL reads to decide how to call the tool, not\n * anything rendered for a human. That is this tool's own concern, not G8's.\n *\n * A config file written by the predecessor may still contain any of those\n * fields; `readConfigForUpdate`/`saveConfig` round-trip through\n * `JSON.parse`/`JSON.stringify` on the whole object, so fields this type\n * does not declare survive a read-modify-write cycle untouched rather than\n * being silently dropped - they are simply invisible to this tool's own\n * logic until whoever owns them ports the corresponding reader.\n *\n * `loadConfig`'s failure path reports through a plain return value, not\n * `console.*` - the child's stdout is the captured transcript (a standing\n * rule across this package), and this reader also runs in-process for the\n * parent/main session, where `console.error` would still be an ad hoc,\n * unstructured side channel outside whatever this package's own log sink is.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { ArtifactDirPreference, ToolBudgetConfig } from '../../types';\nimport type { CompletionBatchConfig } from '../completionBatcher';\nimport { getAgentDir } from '../configDir';\nimport type { RuntimeTable } from '../runtimeRegistry';\n\nconst ARTIFACT_DIR_PREFERENCES = new Set<ArtifactDirPreference>(['project', 'session', 'temp']);\n\nexport interface TopLevelParallelConfig {\n  /**\n   * Hard cap on how many children one top-level PARALLEL call may DECLARE.\n   * Defaults to 8. This bounds one call's width only - see\n   * `DEFAULT_PARALLEL_MAX_TASKS` in `spawnPlan.ts` for why `concurrency`\n   * cannot serve that purpose, and `maxLiveRuns` for the bound that survives\n   * concurrent calls.\n   */\n  maxTasks?: number;\n  /** How many children may be started at once. Throttles launch rate, not the number running. Defaults to 4. */\n  concurrency?: number;\n  /**\n   * Process-wide ceiling on children ALIVE at once, across every concurrent\n   * call. Defaults to 8, the same as `maxTasks`, so a single call behaves\n   * exactly as it did before admission control existed. Lower it on a small\n   * machine (each Pi child was measured at 82-218 MB RSS); raise it when the\n   * host can carry more.\n   */\n  maxLiveRuns?: number;\n  /**\n   * How long a queued child waits for a free slot before it is refused as a\n   * per-child error. Defaults to 300000 (5 minutes).\n   */\n  admissionTimeoutMs?: number;\n}\n\nexport type ToolDescriptionMode = 'full' | 'compact' | 'custom';\n\n/**\n * The `subagent` config surface this tool's dispatch (`spawnPlan.ts`,\n * `managementActions.ts`) actually reads. See the module header for what\n * is deliberately not modeled yet and why.\n */\nexport interface ExtensionConfig {\n  /**\n   * External agent CLIs a run may target, merged over the shipped defaults\n   * (`claude`, `antigravity`). Keyed by the name callers pass as `runtime`;\n   * `pi` is not listed because it is the in-process SDK path, not a command.\n   */\n  runtimes?: RuntimeTable;\n  defaultSessionDir?: string;\n  maxSubagentDepth?: number;\n  completionBatch?: CompletionBatchConfig;\n  toolBudget?: ToolBudgetConfig;\n  parallel?: TopLevelParallelConfig;\n  /** Where to store subagent artifact files. Defaults to \"session\" beside the Pi transcript. Set to \"project\" for cwd/.doom-team, or \"temp\" for OS temp. */\n  artifactDir?: ArtifactDirPreference;\n  /**\n   * How long a spawn waits for a child to signal it started before giving up.\n   * Defaults to 10s. Deliberately NOT derived from the caller's `timeoutMs`:\n   * that conflates \"the child failed to boot\" with \"the work takes a while\",\n   * so a generous run timeout used to turn a dead child into a multi-minute\n   * hang. Internal-only - a model has no useful basis for setting it.\n   */\n  handshakeTimeoutMs?: number;\n  /**\n   * Whether to append the orchestration addendum to the parent session's\n   * system prompt. Defaults to enabled; set `false` to get the tools without\n   * the guidance. See `orchestratorPrompt.ts` for why this is default-on.\n   */\n  orchestratorPrompt?: boolean;\n  /** Tool description variant registered for the parent-facing subagent tool. Defaults to full. */\n  toolDescriptionMode?: ToolDescriptionMode;\n}\n\nexport function getConfigPath(): string {\n  return path.join(getAgentDir(), 'extensions', 'subagent', 'config.json');\n}\n\nfunction readConfigForUpdate(configPath = getConfigPath()): ExtensionConfig {\n  if (!fs.existsSync(configPath)) return {};\n  const parsed = JSON.parse(fs.readFileSync(configPath, 'utf-8')) as unknown;\n  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n    throw new Error(`Subagent config at '${configPath}' must be a JSON object`);\n  }\n  const config = parsed as Record<string, unknown>;\n  if (config.artifactDir !== undefined && !ARTIFACT_DIR_PREFERENCES.has(config.artifactDir as ArtifactDirPreference)) {\n    throw new Error(`config.artifactDir must be \"project\", \"session\", or \"temp\"`);\n  }\n  return parsed as ExtensionConfig;\n}\n\nexport function saveConfig(config: ExtensionConfig, configPath = getConfigPath()): void {\n  fs.mkdirSync(path.dirname(configPath), { recursive: true });\n  fs.writeFileSync(configPath, `${JSON.stringify(config, null, '\\t')}\\n`, 'utf-8');\n}\n\nexport function updateConfig(updater: (config: ExtensionConfig) => ExtensionConfig): ExtensionConfig {\n  const configPath = getConfigPath();\n  const next = updater(readConfigForUpdate(configPath));\n  saveConfig(next, configPath);\n  return next;\n}\n\nexport interface LoadedConfig {\n  config: ExtensionConfig;\n  /** Present only when the file existed but could not be parsed/validated; `config` is `{}` in that case. */\n  loadError?: string;\n}\n\n/**\n * Memoized `loadConfig` result, invalidated by the config file's own identity\n * (path) and revision (mtime + size).\n *\n * WHY THIS IS WORTH A CACHE: `loadConfig()` is called on every spawn, every\n * delegation request, every slash command and at tool-registration time, and\n * each call was a `readFileSync` plus a `JSON.parse` of a file that changes\n * approximately never. The stamp check replaces that with one `statSync`.\n *\n * WHY MTIME AND SIZE RATHER THAN A TTL: a TTL is wrong in both directions -\n * it serves stale config for the length of the window and re-reads an\n * unchanged file forever after. `saveConfig`/`updateConfig` both write through\n * `fs.writeFileSync`, which moves mtime, so the next `loadConfig` sees a new\n * stamp and re-reads. `updateConfig` reads through `readConfigForUpdate`\n * directly rather than this cache, so a read-modify-write cycle can never\n * round-trip a cached object.\n *\n * The cached `LoadedConfig` is handed out by reference. Every caller in this\n * package treats it as read-only; a caller that mutated it would poison\n * subsequent reads, which is why nothing here should start doing that.\n */\nlet configCache: { path: string; stamp: string; loaded: LoadedConfig } | undefined;\n\n/** `undefined` for a file that is absent or unstattable; both are a stable \"no config\" stamp. */\nfunction configStamp(configPath: string): string {\n  try {\n    const stat = fs.statSync(configPath);\n    return `${stat.mtimeMs}:${stat.size}`;\n  } catch {\n    return 'absent';\n  }\n}\n\n/** Never throws. A malformed config degrades to defaults, reported via `loadError` rather than `console.*`. */\nexport function loadConfig(): LoadedConfig {\n  const configPath = getConfigPath();\n  const stamp = configStamp(configPath);\n  if (configCache?.path === configPath && configCache.stamp === stamp) return configCache.loaded;\n\n  let loaded: LoadedConfig;\n  try {\n    loaded = { config: readConfigForUpdate(configPath) };\n  } catch (error) {\n    loaded = {\n      config: {},\n      loadError: `Failed to load subagent config from '${configPath}': ${(error as Error).message}`,\n    };\n  }\n  configCache = { path: configPath, stamp, loaded };\n  return loaded;\n}\n","/**\n * Serial admission control for child spawns.\n *\n * The owning session runtime injects an in-memory live-run counter backed by\n * direct child events. No process ids or durable files participate in liveness.\n */\n\nimport type { ConcurrencyEventReporter } from '../runWithConcurrency';\nimport type { SessionScope } from '../sessionPaths';\n\n/** How often a waiting spawn re-checks for a free slot. */\nexport const DEFAULT_ADMISSION_POLL_INTERVAL_MS = 250;\n\n/**\n * How long a spawn waits for a slot before it is refused.\n *\n * Generous on purpose: children are long-lived, so a queued child behind a\n * saturated machine is normal, and turning that into an error too eagerly\n * would be a worse regression than the wait it replaces.\n */\nexport const DEFAULT_ADMISSION_TIMEOUT_MS = 300_000;\n\n/** Live children, counted however the caller can count them. */\nexport type LiveRunCounter = (scope: SessionScope) => number | Promise<number>;\n\nexport interface AdmissionRequest {\n  /** Session whose child runs are being admitted. */\n  sessionScope: SessionScope;\n  /** Maximum children alive at once, across every concurrent call in this process. */\n  maxLiveRuns: number;\n  /** How long to wait for a slot before refusing. */\n  timeoutMs: number;\n  report?: ConcurrencyEventReporter;\n}\n\nexport interface AdmissionTicket {\n  /** Give the slot back. Idempotent; safe to call from a `finally`. */\n  release(): void;\n}\n\nexport interface AdmissionGateContract {\n  admit(request: AdmissionRequest): Promise<AdmissionTicket>;\n}\n\nfunction sleep(ms: number): Promise<void> {\n  return new Promise((resolve) => {\n    const timer = setTimeout(resolve, ms);\n    timer.unref?.();\n  });\n}\n\nexport interface AdmissionGateOptions {\n  countLiveRuns: LiveRunCounter;\n  wait?: (ms: number) => Promise<void>;\n  pollIntervalMs?: number;\n  now?: () => number;\n}\n\nexport class AdmissionGate implements AdmissionGateContract {\n  private readonly countLiveRuns: LiveRunCounter;\n  private readonly wait: (ms: number) => Promise<void>;\n  private readonly pollIntervalMs: number;\n  private readonly now: () => number;\n  /** Admitted spawns that have not registered themselves yet. */\n  private reserved = 0;\n  /** Serializes admissions so no two callers can read the same free slot. */\n  private queue: Promise<unknown> = Promise.resolve();\n\n  constructor(options: AdmissionGateOptions) {\n    this.countLiveRuns = options.countLiveRuns;\n    this.wait = options.wait ?? sleep;\n    this.pollIntervalMs = options.pollIntervalMs ?? DEFAULT_ADMISSION_POLL_INTERVAL_MS;\n    this.now = options.now ?? Date.now;\n  }\n\n  admit(request: AdmissionRequest): Promise<AdmissionTicket> {\n    const admission = this.queue.then(\n      () => this.waitForSlot(request),\n      () => this.waitForSlot(request),\n    );\n    this.queue = admission.then(\n      () => undefined,\n      () => undefined,\n    );\n    return admission;\n  }\n\n  private async waitForSlot(request: AdmissionRequest): Promise<AdmissionTicket> {\n    const deadline = this.now() + request.timeoutMs;\n    const waitStartedAt = this.now();\n    let waited = false;\n\n    for (;;) {\n      const live = (await this.countLiveRuns(request.sessionScope)) + this.reserved;\n      if (live < request.maxLiveRuns) {\n        this.reserved += 1;\n        return this.ticket();\n      }\n      if (!waited) {\n        waited = true;\n        request.report?.('doom_team.admission_wait', {\n          'team.live_runs': live,\n          'team.max_live_runs': request.maxLiveRuns,\n        });\n      }\n      if (this.now() >= deadline) {\n        request.report?.('doom_team.admission_timeout', {\n          'team.live_runs': live,\n          'team.max_live_runs': request.maxLiveRuns,\n          duration_ms: this.now() - waitStartedAt,\n        });\n        throw new Error(\n          `No child slot became available within ${request.timeoutMs}ms: ${live} of at most ${request.maxLiveRuns} children are already running. Wait for running children to finish, or raise parallel.maxLiveRuns in the subagent config.`,\n        );\n      }\n      await this.wait(this.pollIntervalMs);\n    }\n  }\n\n  private ticket(): AdmissionTicket {\n    let released = false;\n    return {\n      release: () => {\n        if (released) return;\n        released = true;\n        this.reserved -= 1;\n      },\n    };\n  }\n}\n","/**\n * Version envelope shared by every artifact this package writes to disk.\n *\n * DESIGN PATTERNS:\n * - Every record carries `version` from the day it is created, so a later format\n *   change can be detected rather than guessed at\n * - Readers reject an unknown version instead of coercing it: a run directory\n *   written by a newer build is skipped, not misread\n *\n * WHY THIS EXISTS:\n * Several predecessor artifacts had no version field at all, which left no way\n * to change their shape without a silent misparse in a mixed-version session.\n *\n * AVOID:\n * - Bumping a version to add an optional field; additive changes stay compatible\n * - Reading a record without going through `parseVersioned`\n */\n\nexport interface VersionedRecord {\n  version: number;\n}\n\nexport type VersionedParseFailure =\n  | { reason: 'not-an-object' }\n  | { reason: 'missing-version' }\n  | { reason: 'unsupported-version'; found: number };\n\nexport type VersionedParseResult<T> = { ok: true; value: T } | { ok: false; failure: VersionedParseFailure };\n\n/**\n * Validate that `value` is an object carrying one of `supportedVersions`.\n *\n * Returns a result rather than throwing because most callers are scanning a\n * directory and want to skip a bad record, not abort the sweep.\n */\nexport function parseVersioned<T extends VersionedRecord>(\n  value: unknown,\n  supportedVersions: readonly number[],\n): VersionedParseResult<T> {\n  if (!value || typeof value !== 'object' || Array.isArray(value)) {\n    return { ok: false, failure: { reason: 'not-an-object' } };\n  }\n  const found = (value as Partial<VersionedRecord>).version;\n  if (typeof found !== 'number' || !Number.isInteger(found)) {\n    return { ok: false, failure: { reason: 'missing-version' } };\n  }\n  if (!supportedVersions.includes(found)) {\n    return { ok: false, failure: { reason: 'unsupported-version', found } };\n  }\n  return { ok: true, value: value as T };\n}\n\n/** Human-readable explanation for a rejected record, for logs and diagnostics. */\nexport function describeVersionedFailure(failure: VersionedParseFailure, label: string): string {\n  switch (failure.reason) {\n    case 'not-an-object':\n      return `${label} is not an object.`;\n    case 'missing-version':\n      return `${label} has no integer version field.`;\n    case 'unsupported-version':\n      return `${label} has unsupported version ${failure.found}.`;\n  }\n}\n","/**\n * A readable, unique, addressable name for every spawned agent.\n *\n * An identity looks like `alan-reviewer-3`: a friendly name, the role it is\n * playing, and a session-wide sequence number. It replaces the previous\n * `<agent>-<runId prefix>` member id, which was unique but unreadable, and\n * which made a fan-out of four identical agents indistinguishable on screen.\n *\n * WHY A COUNTER RATHER THAN A HASH OF THE RUN ID:\n * Hashing a run id into a name list is cheap and needs no state, and the colour\n * picked by `agentIdentityColor` does exactly that. It is wrong here. A colour\n * that repeats is cosmetic; an address that repeats routes an intercom message\n * to the wrong agent. With 128 names, six concurrent runs collide about 11% of\n * the time. A counter collides never, and the number stays useful as a spawn\n * order marker.\n *\n * WHY A CLAIM FILE PER IDENTITY RATHER THAN ONE REGISTRY JSON:\n * `atomicJson` states plainly that an atomic write prevents torn reads but not\n * lost updates, and this package has no lease service. A single `names.json`\n * would be read-modify-write, which is precisely that hazard: two concurrent\n * spawns would both read counter N and both claim N. Creating a file with the\n * `wx` flag makes the filesystem itself the arbiter, so exactly one caller wins\n * and the loser simply tries the next number. `operationJournal` already uses\n * this primitive for the same reason.\n *\n * WHY THE SHAPE IS LOWERCASE AND HYPHENATED:\n * `normalizeTeamMemberName` lowercases, replaces anything outside\n * `[a-z0-9._-]`, and trims separators. An identity in this shape survives it\n * unchanged, so it can BE the intercom member id rather than an alias beside\n * one, and a model that copies it out of a members listing can address it\n * verbatim. It also can never equal the reserved `main`, because it always\n * carries a numeric suffix.\n *\n * AVOID:\n * - Failing a spawn because a claim could not be written; an unwritable scope\n *   directory degrades to the old run-id shape, it does not lose the run\n * - Releasing an identity when a run ends; a recycled name would label a live\n *   agent and a finished one in the same transcript\n * - Deriving the identity again downstream; it is minted once and carried\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { type SessionScope, sessionScopeDir } from '../sessionPaths';\nimport { parseVersioned } from '../versioned';\n\nconst IDENTITIES_DIR_NAME = 'agent-identities';\nconst IDENTITY_RECORD_VERSION = 1;\nconst MAX_ROLE_LENGTH = 24;\nconst FALLBACK_ROLE = 'agent';\nconst UNSAFE_IDENTITY_CHARS = /[^a-z0-9]+/g;\n/** A spawn burst is small; this only bounds a pathological retry loop. */\nconst MAX_CLAIM_ATTEMPTS = 4096;\n\n/**\n * Short, unambiguous first names. Deliberately ASCII and 3 to 6 characters, so\n * a narrow fleet roster row loses as little as possible to truncation.\n *\n * The list repeats once the counter passes its length, which is harmless: the\n * number keeps climbing, so `alan-reviewer-1` and `alan-tester-129` are still\n * distinct. There is therefore no exhaustion case to handle.\n */\nexport const AGENT_NAMES: readonly string[] = Object.freeze([\n  'alan',\n  'bea',\n  'cyrus',\n  'dara',\n  'elin',\n  'faris',\n  'gita',\n  'hugo',\n  'ines',\n  'jonas',\n  'kira',\n  'liam',\n  'mira',\n  'nadia',\n  'omar',\n  'petra',\n  'quinn',\n  'rosa',\n  'said',\n  'tessa',\n  'uma',\n  'viktor',\n  'wren',\n  'xenia',\n  'yusuf',\n  'zara',\n  'anika',\n  'bruno',\n  'clara',\n  'dmitri',\n  'esme',\n  'felix',\n  'greta',\n  'hana',\n  'idris',\n  'juno',\n  'kasper',\n  'lena',\n  'mateo',\n  'nora',\n  'oskar',\n  'pilar',\n  'rafiq',\n  'sonia',\n  'tomas',\n  'ulla',\n  'vera',\n  'wade',\n  'yara',\n  'zane',\n  'amara',\n  'bodhi',\n  'celia',\n  'darian',\n  'edda',\n  'fiona',\n  'gunnar',\n  'helia',\n  'ivan',\n  'jasmin',\n  'kaito',\n  'lucia',\n  'milan',\n  'nilsa',\n  'otto',\n  'paloma',\n  'rhea',\n  'stellan',\n  'tariq',\n  'ursula',\n  'vidal',\n  'wilma',\n  'yannis',\n  'zoya',\n  'adele',\n  'basim',\n  'cato',\n  'delia',\n  'emil',\n  'freya',\n  'gabor',\n  'hilda',\n  'ismael',\n  'janna',\n  'kuno',\n  'leif',\n  'maren',\n  'niall',\n  'odette',\n  'pavel',\n  'rania',\n  'sixten',\n  'thea',\n  'urban',\n  'vesna',\n  'wolf',\n  'yestin',\n  'zelda',\n  'agnes',\n  'boris',\n  'cosima',\n  'dario',\n  'elias',\n  'fatima',\n  'gilles',\n  'hedda',\n  'ilan',\n  'jorja',\n  'kemal',\n  'linnea',\n  'matias',\n  'noor',\n  'olen',\n  'petros',\n  'rilla',\n  'soren',\n  'tova',\n  'ugo',\n  'valdis',\n  'wanda',\n  'yosef',\n  'zinnia',\n  'arlo',\n  'birta',\n  'ciaran',\n  'dagny',\n  'eero',\n  'fabia',\n]);\n\n/** One claimed identity, written before the run it names is spawned. */\nexport interface AgentIdentityClaim {\n  version: typeof IDENTITY_RECORD_VERSION;\n  identity: string;\n  name: string;\n  role: string;\n  number: number;\n  agent: string;\n  inline: boolean;\n  runId: string;\n  claimedAt: number;\n}\n\nexport interface AgentIdentity {\n  /** The addressable token, for example `alan-reviewer-3`. */\n  identity: string;\n  name: string;\n  role: string;\n  number: number;\n  inline: boolean;\n  /** False when the claim could not be written and the fallback shape was used. */\n  persisted: boolean;\n}\n\nexport interface AgentIdentityInput {\n  agent: string;\n  inline: boolean;\n  runId: string;\n}\n\nexport function agentIdentitiesDir(scope: SessionScope): string {\n  return path.join(sessionScopeDir(scope), IDENTITIES_DIR_NAME);\n}\n\n/**\n * The role an identity advertises, taken from the last segment of the agent\n * name: `doompi-reviewer` reads as `reviewer`. The package prefix is shared by\n * every agent a package ships, so it is the part that carries no information.\n */\nexport function roleFromAgent(agent: string): string {\n  const segments = agent\n    .toLowerCase()\n    .split(/[^a-z0-9]+/)\n    .filter(Boolean);\n  const role = (segments.at(-1) ?? '').slice(0, MAX_ROLE_LENGTH);\n  return role || FALLBACK_ROLE;\n}\n\nexport function composeIdentity(role: string, sequence: number): string {\n  const name = AGENT_NAMES[(sequence - 1) % AGENT_NAMES.length]!;\n  return `${name}-${role}-${sequence}`;\n}\n\n/** The pre-identity member id, kept as the degraded shape when a claim cannot be written. */\nfunction fallbackIdentity(input: AgentIdentityInput): string {\n  const base = input.agent\n    .toLowerCase()\n    .replace(UNSAFE_IDENTITY_CHARS, '-')\n    .replace(/^-+|-+$/g, '');\n  return `${base || FALLBACK_ROLE}-${input.runId.slice(0, 8)}`;\n}\n\nfunction readClaim(file: string): AgentIdentityClaim | undefined {\n  try {\n    const parsed = parseVersioned<AgentIdentityClaim>(JSON.parse(fs.readFileSync(file, 'utf-8')), [\n      IDENTITY_RECORD_VERSION,\n    ]);\n    return parsed.ok ? parsed.value : undefined;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction toIdentity(claim: AgentIdentityClaim, persisted: boolean): AgentIdentity {\n  return {\n    identity: claim.identity,\n    name: claim.name,\n    role: claim.role,\n    number: claim.number,\n    inline: claim.inline,\n    persisted,\n  };\n}\n\n/**\n * Claim the next free identity in this session.\n *\n * A run id that already holds a claim gets it back rather than a second one.\n * That lookup has to happen before allocation, not as a side effect of\n * colliding during it: allocation starts past the existing claims, so it would\n * never meet the run's own file and would quietly mint a duplicate identity\n * for a replayed operation.\n */\nexport function claimAgentIdentity(scope: SessionScope, input: AgentIdentityInput): AgentIdentity {\n  const role = roleFromAgent(input.agent);\n  const directory = agentIdentitiesDir(scope);\n  const degraded: AgentIdentity = {\n    identity: fallbackIdentity(input),\n    name: '',\n    role,\n    number: 0,\n    inline: input.inline,\n    persisted: false,\n  };\n\n  let entries: string[];\n  try {\n    fs.mkdirSync(directory, { recursive: true });\n    entries = fs.readdirSync(directory);\n  } catch {\n    return degraded;\n  }\n\n  for (const entry of entries) {\n    const existing = readClaim(path.join(directory, entry));\n    if (existing?.runId === input.runId) return toIdentity(existing, true);\n  }\n\n  let sequence = entries.length + 1;\n  for (let attempt = 0; attempt < MAX_CLAIM_ATTEMPTS; attempt += 1, sequence += 1) {\n    const identity = composeIdentity(role, sequence);\n    const file = path.join(directory, `${identity}.json`);\n    const claim: AgentIdentityClaim = {\n      version: IDENTITY_RECORD_VERSION,\n      identity,\n      name: AGENT_NAMES[(sequence - 1) % AGENT_NAMES.length]!,\n      role,\n      number: sequence,\n      agent: input.agent,\n      inline: input.inline,\n      runId: input.runId,\n      claimedAt: Date.now(),\n    };\n    try {\n      fs.writeFileSync(file, `${JSON.stringify(claim)}\\n`, { flag: 'wx', mode: 0o600 });\n      return toIdentity(claim, true);\n    } catch (error) {\n      // Anything but a taken number is a real filesystem problem, and a run\n      // must not fail because it could not be given a pretty name.\n      if ((error as NodeJS.ErrnoException).code !== 'EEXIST') return degraded;\n      const existing = readClaim(file);\n      if (existing?.runId === input.runId) return toIdentity(existing, true);\n    }\n  }\n  return degraded;\n}\n\n/**\n * Point an existing identity at a new run id.\n *\n * Restore mints a fresh run id for what is conceptually the same agent, so the\n * identity has to be carried across rather than derived again. This is a\n * single-writer rewrite of one claim, so the lost-update hazard that rules out\n * a shared registry file does not apply.\n */\nexport function adoptAgentIdentity(scope: SessionScope, identity: string, runId: string): void {\n  const file = path.join(agentIdentitiesDir(scope), `${identity}.json`);\n  const existing = readClaim(file);\n  if (!existing) return;\n  try {\n    fs.writeFileSync(file, `${JSON.stringify({ ...existing, runId, claimedAt: Date.now() })}\\n`, { mode: 0o600 });\n  } catch {\n    // A stale owner in the claim is cosmetic; the identity itself still holds.\n  }\n}\n\n/** Render an identity for display, marking the inline case that has no agent file on disk. */\nexport function formatAgentIdentity(identity: string | undefined, inline?: boolean): string | undefined {\n  if (!identity) return undefined;\n  return inline ? `${identity} (inline)` : identity;\n}\n","/**\n * Resolving skill files by name and rendering them into a child system prompt.\n *\n * A skill is a markdown file, either `<dir>/SKILL.md` or a bare `<name>.md`,\n * found by sweeping a fixed list of search roots. The same name can appear in\n * several roots, so the sweep records where each hit came from and the highest\n * priority source wins.\n *\n * WHY THIS IS A SERVICE AND NOT A MODULE OF FUNCTIONS:\n * Resolution walks every skill root and reads the frontmatter of every markdown\n * file it finds. Prompt assembly asks for the catalogue on each launch and\n * completion asks on each keystroke, so the answers have to be cached, and a\n * cache needs an owner that can be invalidated and swapped in a test.\n *\n * DESIGN PATTERNS:\n * - Two caches with different lifetimes. Listing answers \"does this name exist\n *   and where\", reading answers \"what does it say\"; the first goes stale on any\n *   directory change, the second only when one file's mtime moves\n * - Both are bounded LRUs. The predecessor held the listing in a single mutable\n *   slot keyed by cwd, which thrashed the moment two working directories were in\n *   play, and evicted parsed files in insertion order regardless of use\n * - Every filesystem call is best-effort. A skill root that cannot be read is\n *   skipped, never fatal: a missing skill surfaces to the caller as `missing`\n * - Symlinked and repeated directories are visited at most once per priority, so\n *   a cycle in the skill tree terminates\n *\n * AVOID:\n * - Walking the skill roots on a completion path without going through the cache\n * - Deriving a config directory here instead of asking `configDir.ts`\n */\n\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nimport { EXTRA_SKILL_DIRS_ENV } from '../../types/environment';\nimport { canonicalizeDiscoveryCwd } from '../agentProjectRoot';\nimport { getAgentDir, getProjectConfigDir } from '../configDir';\nimport { LruCache } from '../lruCache';\n\n/**\n * Where a skill file was found.\n *\n * Deliberately not `AgentSource`: a skill can also come from a settings list or\n * from an extension directory, neither of which can hold an agent definition.\n */\nexport type SkillSource =\n  | 'project'\n  | 'user'\n  | 'project-settings'\n  | 'user-settings'\n  | 'extension'\n  | 'builtin'\n  | 'unknown';\n\nexport interface ResolvedSkill {\n  name: string;\n  path: string;\n  content: string;\n  description?: string;\n  source: SkillSource;\n}\n\nexport interface SkillLocation {\n  path: string;\n  source: SkillSource;\n}\n\nexport interface SkillResolution {\n  resolved: ResolvedSkill[];\n  missing: string[];\n}\n\nexport interface DiscoveredSkill {\n  name: string;\n  source: SkillSource;\n  description?: string;\n}\n\n/**\n * Discovery and reading of skill files.\n *\n * Behind an interface for the same reason agent discovery is: the results are\n * cached and invalidated, and callers on the completion path must be able to ask\n * repeatedly without paying for a directory walk each time.\n */\nexport type SkillDiscoveryContract = {\n  /** Locate one skill by name, or undefined when no root holds it. */\n  resolveSkillPath(skillName: string, cwd: string): SkillLocation | undefined;\n  /** Read the named skills, reporting any that could not be resolved. */\n  resolveSkills(skillNames: string[], cwd: string, localSkillPaths?: string[], localBaseDir?: string): SkillResolution;\n  /** Resolve against `primaryCwd`, retrying whatever is missing in `fallbackCwd`. */\n  resolveSkillsWithFallback(\n    skillNames: string[],\n    primaryCwd: string,\n    fallbackCwd?: string,\n    localSkillPaths?: string[],\n    localBaseDir?: string,\n  ): SkillResolution;\n  /** Every skill visible from `cwd`, sorted by name. */\n  discoverAvailableSkills(cwd: string): DiscoveredSkill[];\n  /** Drop cached results. Call after writing or removing a skill file. */\n  invalidate(): void;\n};\n\n/** One entry in a listing sweep: located, but not yet read. */\ninterface CachedSkillEntry {\n  name: string;\n  filePath: string;\n  source: SkillSource;\n  description?: string;\n  /** Discovery order, used to break ties between equal-priority sources. */\n  order: number;\n}\n\ninterface SkillFileCacheEntry {\n  mtimeMs: number;\n  skill: ResolvedSkill;\n}\n\ninterface SkillListingCacheEntry {\n  skills: CachedSkillEntry[];\n  expiresAt: number;\n}\n\ninterface SkillSearchPath {\n  path: string;\n  source: SkillSource;\n}\n\n/** Roughly the number of distinct skills one session touches. */\nconst SKILL_FILE_CACHE_CAPACITY = 50;\n/** One entry per (cwd, agentDir) pair; a session rarely spans more than a few. */\nconst SKILL_LISTING_CACHE_CAPACITY = 8;\n/**\n * How long a listing stays valid.\n *\n * Short enough that a skill added mid-session appears without a restart, long\n * enough that a burst of completions does not re-walk the roots per keystroke.\n */\nconst SKILL_LISTING_TTL_MS = 5_000;\n\n/** Cache keys join two paths, so use a separator that cannot occur in either. */\nconst CACHE_KEY_SEPARATOR = '\\0';\n\n/**\n * The orchestration skill, excluded from every listing and injection.\n *\n * A subagent already has the orchestration tools wired in, so handing it the\n * skill that explains how to reach for them wastes context and invites a child\n * to fan out again. The name is the published skill's, not this package's.\n */\nconst SUBAGENT_ORCHESTRATION_SKILL = 'pi-subagents';\n\nconst SKILL_FILE_NAME = 'SKILL.md';\nconst MARKDOWN_EXTENSION = '.md';\nconst FRONTMATTER_FENCE = '---';\nconst NODE_MODULES_DIR = 'node_modules';\nconst HOME_ALIAS_PREFIX = '~/';\n\n/** Sources a listing can report, most authoritative first. */\nconst SOURCE_PRIORITY: Record<SkillSource, number> = {\n  project: 700,\n  'project-settings': 650,\n  user: 300,\n  'user-settings': 250,\n  extension: 150,\n  builtin: 100,\n  unknown: 0,\n};\n\nfunction priorityOf(source: SkillSource): number {\n  return SOURCE_PRIORITY[source] ?? SOURCE_PRIORITY.unknown;\n}\n\n/** Index of the first character after a closing frontmatter fence, or -1. */\nfunction findFrontmatterEnd(normalized: string): number {\n  if (!normalized.startsWith(FRONTMATTER_FENCE)) return -1;\n  return normalized.indexOf(`\\n${FRONTMATTER_FENCE}`, FRONTMATTER_FENCE.length);\n}\n\nexport function stripSkillFrontmatter(content: string): string {\n  const normalized = content.replace(/\\r\\n/g, '\\n');\n  const endIndex = findFrontmatterEnd(normalized);\n  if (endIndex === -1) return normalized;\n  return normalized.slice(endIndex + 1 + FRONTMATTER_FENCE.length).trim();\n}\n\nexport function parseSkillDescription(content: string): string | undefined {\n  const normalized = content.replace(/\\r\\n/g, '\\n');\n  const endIndex = findFrontmatterEnd(normalized);\n  if (endIndex === -1) return undefined;\n\n  const frontmatter = normalized.slice(FRONTMATTER_FENCE.length, endIndex).trim();\n  const match = frontmatter.match(/^description:\\s*(.+)$/m);\n  return match?.[1]?.trim().replace(/^['\"]|['\"]$/g, '');\n}\n\nfunction maybeReadSkillDescription(filePath: string): string | undefined {\n  try {\n    return parseSkillDescription(fs.readFileSync(filePath, 'utf-8'));\n  } catch {\n    // The description is optional metadata; an unreadable file still lists by name.\n    return undefined;\n  }\n}\n\nfunction isWithinPath(filePath: string, dir: string): boolean {\n  const relative = path.relative(dir, filePath);\n  return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));\n}\n\n/** Read a JSON file that is allowed to be absent, but not allowed to be corrupt. */\nfunction readOptionalJsonFile(filePath: string, label: string): unknown {\n  try {\n    const parsed: unknown = JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n    return parsed;\n  } catch (error) {\n    const code =\n      typeof error === 'object' && error !== null && 'code' in error ? (error as { code?: unknown }).code : undefined;\n    if (code === 'ENOENT') return null;\n    const message = error instanceof Error ? error.message : String(error);\n    throw new Error(`Failed to read ${label} '${filePath}': ${message}`, {\n      cause: error instanceof Error ? error : undefined,\n    });\n  }\n}\n\n/** Extract the string entries of a settings file's `skills` array. */\nfunction readSettingsSkillList(settings: unknown): string[] {\n  if (typeof settings !== 'object' || settings === null || Array.isArray(settings)) return [];\n  const skills = (settings as { skills?: unknown }).skills;\n  if (!Array.isArray(skills)) return [];\n  return skills.filter((entry): entry is string => typeof entry === 'string');\n}\n\nfunction collectSettingsSkillPaths(cwd: string, agentDir: string): SkillSearchPath[] {\n  const results: SkillSearchPath[] = [];\n  const projectConfigDir = getProjectConfigDir(cwd);\n  const settingsFiles = [\n    { file: path.join(projectConfigDir, 'settings.json'), base: projectConfigDir, source: 'project-settings' as const },\n    { file: path.join(agentDir, 'settings.json'), base: agentDir, source: 'user-settings' as const },\n  ];\n\n  for (const { file, base, source } of settingsFiles) {\n    for (const entry of readSettingsSkillList(readOptionalJsonFile(file, 'skills settings file'))) {\n      let resolved = entry;\n      if (resolved.startsWith(HOME_ALIAS_PREFIX)) {\n        resolved = path.join(os.homedir(), resolved.slice(HOME_ALIAS_PREFIX.length));\n      } else if (!path.isAbsolute(resolved)) {\n        resolved = path.resolve(base, resolved);\n      }\n      results.push({ path: resolved, source });\n    }\n  }\n\n  return results;\n}\n\nfunction extraSkillPaths(): SkillSearchPath[] {\n  return (process.env[EXTRA_SKILL_DIRS_ENV] ?? '')\n    .split(path.delimiter)\n    .map((directory) => directory.trim())\n    .filter(Boolean)\n    .map((directory) => ({ path: directory, source: 'extension' as const }));\n}\n\nfunction buildSkillPaths(cwd: string, agentDir: string): SkillSearchPath[] {\n  const projectConfigDir = getProjectConfigDir(cwd);\n  return [\n    ...extraSkillPaths(),\n    { path: path.join(projectConfigDir, 'skills'), source: 'project' },\n    { path: path.join(cwd, '.agents', 'skills'), source: 'project' },\n    { path: path.join(agentDir, 'skills'), source: 'user' },\n    { path: path.join(os.homedir(), '.agents', 'skills'), source: 'user' },\n    ...collectSettingsSkillPaths(cwd, agentDir),\n  ];\n}\n\n/** Classify a hit that arrived without a source hint, by which root contains it. */\nfunction inferSkillSource(filePath: string, cwd: string, agentDir: string, sourceHint?: SkillSource): SkillSource {\n  if (sourceHint) return sourceHint;\n\n  const projectConfigRoot = path.resolve(getProjectConfigDir(cwd));\n  const projectSkillsRoot = path.resolve(projectConfigRoot, 'skills');\n  const projectAgentsRoot = path.resolve(cwd, '.agents');\n  const userSkillsRoot = path.resolve(agentDir, 'skills');\n  const userAgentRoot = path.resolve(agentDir);\n  const userAgentsRoot = path.resolve(os.homedir(), '.agents');\n\n  if (isWithinPath(filePath, projectSkillsRoot) || isWithinPath(filePath, projectAgentsRoot)) return 'project';\n  if (isWithinPath(filePath, projectConfigRoot)) return 'project-settings';\n\n  if (isWithinPath(filePath, userSkillsRoot) || isWithinPath(filePath, userAgentsRoot)) return 'user';\n  if (isWithinPath(filePath, userAgentRoot)) return 'user-settings';\n\n  return 'unknown';\n}\n\nfunction chooseHigherPrioritySkill(\n  existing: CachedSkillEntry | undefined,\n  candidate: CachedSkillEntry,\n): CachedSkillEntry {\n  if (!existing) return candidate;\n  const existingPriority = priorityOf(existing.source);\n  const candidatePriority = priorityOf(candidate.source);\n  if (candidatePriority > existingPriority) return candidate;\n  if (candidatePriority < existingPriority) return existing;\n  return candidate.order < existing.order ? candidate : existing;\n}\n\nfunction isMarkdownFile(fileName: string): boolean {\n  return fileName.toLowerCase().endsWith(MARKDOWN_EXTENSION);\n}\n\n/** Directory names never worth descending into while hunting for skills. */\nfunction shouldSkipDirectory(name: string): boolean {\n  return name.startsWith('.') || name === NODE_MODULES_DIR;\n}\n\nfunction statOrUndefined(target: string): fs.Stats | undefined {\n  try {\n    return fs.statSync(target);\n  } catch {\n    // A dangling symlink or a path removed mid-sweep is simply not a skill.\n    return undefined;\n  }\n}\n\nfunction readDirOrEmpty(dirPath: string): fs.Dirent[] {\n  try {\n    return fs.readdirSync(dirPath, { withFileTypes: true });\n  } catch {\n    // An unreadable root must not abort the sweep over the remaining roots.\n    return [];\n  }\n}\n\n/**\n * Sweep the given roots for skill files.\n *\n * Pure with respect to the caches, which is what lets it serve both the cached\n * catalogue and an agent's own uncached `skillPath` list.\n */\nfunction collectFilesystemSkills(cwd: string, agentDir: string, skillPaths: SkillSearchPath[]): CachedSkillEntry[] {\n  const entries: CachedSkillEntry[] = [];\n  const seen = new Map<string, number>();\n  const visitedDirectories = new Map<string, number>();\n  let order = 0;\n\n  const pushEntry = (name: string, filePath: string, sourceHint?: SkillSource) => {\n    const resolvedFile = path.resolve(filePath);\n    if (!fs.existsSync(resolvedFile)) return;\n    const source = inferSkillSource(resolvedFile, cwd, agentDir, sourceHint);\n    const existingIndex = seen.get(resolvedFile);\n    if (existingIndex !== undefined) {\n      const existing = entries[existingIndex];\n      if (existing && priorityOf(source) > priorityOf(existing.source)) {\n        entries[existingIndex] = {\n          ...existing,\n          name,\n          source,\n          description: maybeReadSkillDescription(resolvedFile),\n        };\n      }\n      return;\n    }\n    seen.set(resolvedFile, entries.length);\n    entries.push({\n      name,\n      filePath: resolvedFile,\n      source,\n      description: maybeReadSkillDescription(resolvedFile),\n      order: order++,\n    });\n  };\n\n  /** False when this directory was already walked at an equal or better priority. */\n  const markDirectoryVisited = (dirPath: string, sourceHint?: SkillSource): boolean => {\n    let resolvedDir: string;\n    try {\n      resolvedDir = fs.realpathSync(dirPath);\n    } catch {\n      // Symlink resolution is only needed to detect cycles; the lexical path is\n      // a sound fallback that at worst walks one directory twice.\n      resolvedDir = path.resolve(dirPath);\n    }\n    const priority = sourceHint ? priorityOf(sourceHint) : SOURCE_PRIORITY.unknown;\n    const previousPriority = visitedDirectories.get(resolvedDir);\n    if (previousPriority !== undefined && previousPriority >= priority) return false;\n    visitedDirectories.set(resolvedDir, priority);\n    return true;\n  };\n\n  const walkSkillDirectories = (dirPath: string, sourceHint?: SkillSource) => {\n    if (!markDirectoryVisited(dirPath, sourceHint)) return;\n\n    // A directory holding SKILL.md is itself the skill; do not descend further.\n    const skillFile = path.join(dirPath, SKILL_FILE_NAME);\n    if (fs.existsSync(skillFile)) {\n      pushEntry(path.basename(dirPath), skillFile, sourceHint);\n      return;\n    }\n\n    for (const entry of readDirOrEmpty(dirPath)) {\n      if (shouldSkipDirectory(entry.name)) continue;\n      if (!entry.isDirectory() && !entry.isSymbolicLink()) continue;\n\n      const entryPath = path.join(dirPath, entry.name);\n      if (statOrUndefined(entryPath)?.isDirectory()) walkSkillDirectories(entryPath, sourceHint);\n    }\n  };\n\n  for (const skillPath of skillPaths) {\n    if (!fs.existsSync(skillPath.path)) continue;\n\n    const stat = statOrUndefined(skillPath.path);\n    if (!stat) continue;\n\n    // A root may point straight at a markdown file rather than a directory.\n    if (stat.isFile()) {\n      const fileName = path.basename(skillPath.path);\n      if (!isMarkdownFile(fileName)) continue;\n      const skillName =\n        fileName.toLowerCase() === SKILL_FILE_NAME.toLowerCase()\n          ? path.basename(path.dirname(skillPath.path))\n          : path.basename(fileName, path.extname(fileName));\n      pushEntry(skillName, skillPath.path, skillPath.source);\n      continue;\n    }\n\n    if (!stat.isDirectory()) continue;\n\n    const rootSkillFile = path.join(skillPath.path, SKILL_FILE_NAME);\n    if (fs.existsSync(rootSkillFile)) {\n      pushEntry(path.basename(skillPath.path), rootSkillFile, skillPath.source);\n      continue;\n    }\n\n    markDirectoryVisited(skillPath.path, skillPath.source);\n\n    for (const child of readDirOrEmpty(skillPath.path)) {\n      if (child.name.startsWith('.')) continue;\n      const childPath = path.join(skillPath.path, child.name);\n      if (child.isDirectory() || child.isSymbolicLink()) {\n        if (shouldSkipDirectory(child.name)) continue;\n        if (statOrUndefined(childPath)?.isDirectory()) walkSkillDirectories(childPath, skillPath.source);\n        continue;\n      }\n      if (child.isFile() && isMarkdownFile(child.name)) {\n        pushEntry(path.basename(child.name, path.extname(child.name)), childPath, skillPath.source);\n      }\n    }\n  }\n\n  return entries;\n}\n\nexport class SkillDiscoveryService implements SkillDiscoveryContract {\n  /** Parsed skill bodies, keyed by resolved file path and validated by mtime. */\n  private readonly fileCache = new LruCache<string, SkillFileCacheEntry>(SKILL_FILE_CACHE_CAPACITY);\n  /** Located-but-unread catalogues, keyed by the (cwd, agentDir) pair. */\n  private readonly listingCache = new LruCache<string, SkillListingCacheEntry>(SKILL_LISTING_CACHE_CAPACITY);\n\n  /**\n   * Seams for tests, as protected members rather than constructor arguments.\n   *\n   * Runtime tuning is not part of this service's dependency contract. A test\n   * subclass overrides these values without abstracting the clock.\n   */\n  protected readonly listingTtlMs: number = SKILL_LISTING_TTL_MS;\n\n  protected now(): number {\n    return Date.now();\n  }\n\n  resolveSkillPath(skillName: string, cwd: string): SkillLocation | undefined {\n    const skill = this.listSkills(cwd).find((candidate) => candidate.name === skillName);\n    if (!skill) return undefined;\n    return { path: skill.filePath, source: skill.source };\n  }\n\n  resolveSkills(skillNames: string[], cwd: string, localSkillPaths?: string[], localBaseDir?: string): SkillResolution {\n    const resolved: ResolvedSkill[] = [];\n    const missing: string[] = [];\n    const localByName = localSkillPaths?.length\n      ? collectLocalSkills(cwd, localSkillPaths, localBaseDir)\n      : new Map<string, CachedSkillEntry>();\n\n    for (const name of skillNames) {\n      const trimmed = name.trim();\n      if (!trimmed) continue;\n      if (trimmed === SUBAGENT_ORCHESTRATION_SKILL) {\n        missing.push(trimmed);\n        continue;\n      }\n\n      // An agent's own skillPath outranks anything found in the shared roots.\n      const local = localByName.get(trimmed);\n      let skill = local ? this.readSkill(trimmed, local.filePath, local.source) : undefined;\n      if (!skill) {\n        const location = this.resolveSkillPath(trimmed, cwd);\n        if (location) skill = this.readSkill(trimmed, location.path, location.source);\n      }\n      if (skill) resolved.push(skill);\n      else missing.push(trimmed);\n    }\n\n    return { resolved, missing };\n  }\n\n  /**\n   * Resolve against `primaryCwd`, then retry whatever is still missing elsewhere.\n   *\n   * A child launched into a worktree still needs the skills configured in the\n   * repository it was launched from.\n   */\n  resolveSkillsWithFallback(\n    skillNames: string[],\n    primaryCwd: string,\n    fallbackCwd?: string,\n    localSkillPaths?: string[],\n    localBaseDir?: string,\n  ): SkillResolution {\n    const resolvedPrimaryCwd = path.resolve(primaryCwd);\n    const primary = this.resolveSkills(skillNames, resolvedPrimaryCwd, localSkillPaths, localBaseDir);\n    if (!fallbackCwd || primary.missing.length === 0) return primary;\n    const resolvedFallbackCwd = path.resolve(fallbackCwd);\n    if (canonicalizeDiscoveryCwd(resolvedPrimaryCwd) === canonicalizeDiscoveryCwd(resolvedFallbackCwd)) return primary;\n\n    const fallback = this.resolveSkills(primary.missing, resolvedFallbackCwd);\n    return {\n      resolved: [...primary.resolved, ...fallback.resolved],\n      missing: fallback.missing,\n    };\n  }\n\n  discoverAvailableSkills(cwd: string): DiscoveredSkill[] {\n    return this.listSkills(cwd)\n      .filter((skill) => skill.name !== SUBAGENT_ORCHESTRATION_SKILL)\n      .map((skill) => ({\n        name: skill.name,\n        source: skill.source,\n        description: skill.description,\n      }))\n      .sort((a, b) => a.name.localeCompare(b.name));\n  }\n\n  invalidate(): void {\n    this.fileCache.clear();\n    this.listingCache.clear();\n  }\n\n  /** The catalogue visible from `cwd`, sweeping the roots only when stale. */\n  private listSkills(cwd: string): CachedSkillEntry[] {\n    const timestamp = this.now();\n    const resolvedCwd = path.resolve(cwd);\n    const resolvedAgentDir = path.resolve(getAgentDir());\n    const key = `${canonicalizeDiscoveryCwd(resolvedCwd)}${CACHE_KEY_SEPARATOR}${canonicalizeDiscoveryCwd(resolvedAgentDir)}`;\n\n    const cached = this.listingCache.get(key);\n    if (cached && cached.expiresAt > timestamp) return cached.skills;\n\n    const loaded = collectFilesystemSkills(\n      resolvedCwd,\n      resolvedAgentDir,\n      buildSkillPaths(resolvedCwd, resolvedAgentDir),\n    );\n    const dedupedByName = new Map<string, CachedSkillEntry>();\n    for (const entry of loaded) {\n      dedupedByName.set(entry.name, chooseHigherPrioritySkill(dedupedByName.get(entry.name), entry));\n    }\n\n    const skills = [...dedupedByName.values()].sort((a, b) => a.order - b.order);\n    this.listingCache.set(key, { skills, expiresAt: timestamp + this.listingTtlMs });\n    return skills;\n  }\n\n  /** Read one skill file, reusing the cached parse while its mtime holds. */\n  private readSkill(skillName: string, skillPath: string, source: SkillSource): ResolvedSkill | undefined {\n    try {\n      const stat = fs.statSync(skillPath);\n      const cached = this.fileCache.get(skillPath);\n      if (cached && cached.mtimeMs === stat.mtimeMs) return cached.skill;\n\n      const raw = fs.readFileSync(skillPath, 'utf-8');\n      const skill: ResolvedSkill = {\n        name: skillName,\n        path: skillPath,\n        content: stripSkillFrontmatter(raw),\n        description: parseSkillDescription(raw),\n        source,\n      };\n\n      this.fileCache.set(skillPath, { mtimeMs: stat.mtimeMs, skill });\n      return skill;\n    } catch {\n      // Treat an unreadable skill file as unresolved so the caller reports it\n      // missing rather than injecting a half-formed block into a child prompt.\n      return undefined;\n    }\n  }\n}\n\n/**\n * Index skill files supplied by an agent's own `skillPath`, keyed by name.\n *\n * Deliberately uncached: these paths are per-agent rather than per-directory, so\n * they would pollute a catalogue cache keyed on cwd.\n */\nfunction collectLocalSkills(\n  cwd: string,\n  localSkillPaths: string[],\n  localBaseDir?: string,\n): Map<string, CachedSkillEntry> {\n  const localByName = new Map<string, CachedSkillEntry>();\n  const localEntries = collectFilesystemSkills(\n    cwd,\n    getAgentDir(),\n    localSkillPaths.map((entry) => ({\n      path: path.resolve(localBaseDir ?? cwd, entry),\n      source: 'unknown' as const,\n    })),\n  );\n  for (const entry of localEntries) {\n    if (!localByName.has(entry.name)) localByName.set(entry.name, entry);\n  }\n  return localByName;\n}\n\nfunction escapeXmlText(value: string): string {\n  return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/**\n * Render the skill catalogue for a child system prompt.\n *\n * Only names, descriptions and locations are injected. The child reads a skill\n * when its description matches the task, which keeps the prompt small no matter\n * how large the configured skill bodies are.\n */\nexport function buildSkillInjection(skills: ResolvedSkill[]): string {\n  if (skills.length === 0) return '';\n\n  const lines = [\n    'The following configured skills are available to this subagent.',\n    \"Use the read tool to load a skill's file when the task matches its description.\",\n    'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',\n    '',\n    '<available_skills>',\n  ];\n  const stableSkills = [...skills].sort(\n    (left, right) => left.name.localeCompare(right.name) || left.path.localeCompare(right.path),\n  );\n  for (const skill of stableSkills) {\n    lines.push('  <skill>');\n    lines.push(`    <name>${escapeXmlText(skill.name)}</name>`);\n    lines.push(`    <description>${escapeXmlText(skill.description ?? '')}</description>`);\n    lines.push(`    <location>${escapeXmlText(skill.path)}</location>`);\n    lines.push('  </skill>');\n  }\n  lines.push('</available_skills>');\n  return lines.join('\\n');\n}\n\nfunction dedupeSkillNames(names: string[]): string[] {\n  return [...new Set(names.map((entry) => entry.trim()).filter((entry) => entry.length > 0))];\n}\n\n/**\n * Normalise the `skills` tool parameter into a name list.\n *\n * `false` means \"no skills at all\" and `undefined` means \"use the agent's own\n * configuration\", which is why they are distinct return values rather than both\n * collapsing to an empty array.\n */\nexport function normalizeSkillInput(input: string | string[] | boolean | undefined): string[] | false | undefined {\n  if (input === false) return false;\n  if (input === true || input === undefined) return undefined;\n  if (Array.isArray(input)) return dedupeSkillNames(input);\n\n  // Models sometimes serialise the parameter as a JSON string instead of a native\n  // array. Splitting '[\"a\",\"b\"]' on commas would embed brackets and quotes into\n  // the names, and resolution would then fail with no obvious cause.\n  const trimmed = input.trim();\n  if (trimmed.startsWith('[')) {\n    try {\n      const parsed: unknown = JSON.parse(trimmed);\n      if (Array.isArray(parsed)) {\n        return dedupeSkillNames(parsed.filter((entry): entry is string => typeof entry === 'string'));\n      }\n    } catch {\n      // Not valid JSON after all; fall through to the comma-separated reading.\n    }\n  }\n  return dedupeSkillNames(input.split(','));\n}\n","/**\n * Enforces `maxSubagentDepth`: how many spawn-levels deep a chain of\n * subagents may go before a further spawn is refused.\n *\n * WHY ABSENT MEANS DEPTH 0, NOT \"UNKNOWN, REFUSE\":\n * `SUBAGENT_PARENT_DEPTH_ENV` is only ever set by a parent that is itself a\n * spawned child (see `piArgs.ts`'s child env contract). A root session -\n * the common case, and every top-level spawn - never has it set. Treating\n * absence as \"unknown depth\" and failing closed would refuse every\n * top-level spawn, which is the opposite of the intended behavior. Absence\n * means this process IS the root, depth 0.\n *\n * WHY A PRESENT-BUT-UNPARSEABLE VALUE IS A HARD FAILURE, NOT A SILENT 0:\n * Falling back to 0 for a corrupted value would make a runaway or tampered\n * depth chain invisible - exactly the failure mode this guard exists to\n * catch. A value that is present but not a valid non-negative integer is\n * treated as more suspicious than merely absent, not less.\n *\n * TWO SEPARATE STEPS, MATCHING `spawn-budget.ts`'S RESOLVE/PREFLIGHT SPLIT:\n * `resolveCurrentSubagentDepth` only reads and validates this process's own\n * depth (throws on corruption); `preflightSubagentDepth` only compares an\n * already-resolved depth against the configured limit, returning a\n * describable `{error}` the same shape `spawn-budget.ts` already uses for\n * \"over the limit\" - a business-rule refusal, not an anomaly, so it does\n * not throw on its own. The caller (`spawnPlan.ts`'s preflight) decides\n * when to turn a returned `error` into an actual throw.\n */\n\nimport { SUBAGENT_PARENT_DEPTH_ENV } from '../../types/environment';\n\n/** The slice of extension configuration this module reads. */\nexport interface DepthGuardLimitConfig {\n  maxSubagentDepth?: number;\n}\n\nexport interface DepthPreflightResult {\n  depth: number;\n  limit: number | undefined;\n  error?: string;\n}\n\n/**\n * This process's own spawn depth: 0 for a root session, N for the Nth-level\n * child of a chain of spawns. Throws when `SUBAGENT_PARENT_DEPTH_ENV` is\n * present but not a valid non-negative integer - see the module header.\n */\nexport function resolveCurrentSubagentDepth(env: NodeJS.ProcessEnv = process.env): number {\n  const raw = env[SUBAGENT_PARENT_DEPTH_ENV];\n  if (raw === undefined) return 0;\n  // An empty string is \"present but says nothing\", not \"present and zero\" -\n  // `Number('')` is 0 by a JS quirk, which would otherwise let a blank env\n  // var silently pass as a valid depth.\n  const parsed = raw.trim() === '' ? Number.NaN : Number(raw);\n  if (!Number.isInteger(parsed) || parsed < 0) {\n    throw new Error(\n      `${SUBAGENT_PARENT_DEPTH_ENV} is set to an invalid value (${JSON.stringify(raw)}); expected a non-negative integer.`,\n    );\n  }\n  return parsed;\n}\n\n/**\n * Would a spawn from a process at `depth` exceed `config.maxSubagentDepth`?\n * A configured limit of 0 or `undefined` means no limit. At the limit is\n * allowed - the refusal is for a depth one PAST it, per the boundary team\n * lead specified: `depth === limit` passes, `depth === limit + 1` refuses.\n */\nexport function preflightSubagentDepth(depth: number, config: DepthGuardLimitConfig): DepthPreflightResult {\n  const limit =\n    typeof config.maxSubagentDepth === 'number' &&\n    Number.isInteger(config.maxSubagentDepth) &&\n    config.maxSubagentDepth > 0\n      ? config.maxSubagentDepth\n      : undefined;\n  if (limit === undefined || depth <= limit) return { depth, limit };\n  return {\n    depth,\n    limit,\n    error: `Subagent spawn refused: this process is already at depth ${depth}, past the configured maxSubagentDepth of ${limit}.`,\n  };\n}\n","export type DoomTeamErrorCode =\n  | 'invalid_request'\n  | 'unsupported_operation'\n  | 'unsupported_context'\n  | 'agent_not_found'\n  | 'runtime_unavailable'\n  | 'model_unavailable'\n  | 'run_not_found'\n  | 'ambiguous_run_id'\n  | 'run_terminal'\n  | 'not_resumable'\n  | 'communication_unavailable'\n  | 'recipient_not_found'\n  | 'recipient_ambiguous'\n  | 'delivery_unconfirmed'\n  | 'reply_timeout'\n  | 'status_corrupt'\n  | 'operation_conflict'\n  | 'tool_conflict';\n\nexport class DoomTeamExpectedError extends Error {\n  constructor(\n    readonly code: DoomTeamErrorCode,\n    message: string,\n    readonly retryable: boolean,\n    readonly recovery: string,\n  ) {\n    super(`[${code}] ${message}\\nRecovery: ${recovery}`);\n    this.name = 'DoomTeamExpectedError';\n  }\n}\n\nexport function invalidRequest(message: string, recovery: string): DoomTeamExpectedError {\n  return new DoomTeamExpectedError('invalid_request', message, false, recovery);\n}\n","/**\n * Model identity and thinking-level resolution.\n *\n * DESIGN PATTERNS:\n * - A model string may carry a thinking level as a `:level` suffix. Only suffixes\n *   in THINKING_LEVELS are recognised, so a model id that legitimately contains a\n *   colon (`openrouter/vendor:free`) is never mistaken for a thinking request\n * - `max` is excluded from the default supported set because a model only offers\n *   it when its thinkingLevelMap says so explicitly\n *\n * AVOID:\n * - Splitting a model string on the first colon; the suffix is at the end\n * - Assuming a missing thinkingLevelMap means \"no thinking\"; it means \"unknown\",\n *   which is treated as the standard set\n */\n\nexport const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;\nexport type ThinkingLevel = (typeof THINKING_LEVELS)[number];\nexport type ThinkingLevelMap = Partial<Record<ThinkingLevel, string | null>>;\n\nconst THINKING_SUFFIX_SEPARATOR = ':';\nconst PROVIDER_SEPARATOR = '/';\n\nexport interface ModelInfo {\n  provider: string;\n  id: string;\n  fullId: string;\n  api?: string;\n  reasoning?: boolean;\n  thinkingLevelMap?: ThinkingLevelMap;\n}\n\ninterface RegistryModelLike {\n  provider: string;\n  id: string;\n  api?: string;\n  reasoning?: boolean;\n  thinkingLevelMap?: ThinkingLevelMap;\n}\n\nexport function toModelInfo(model: RegistryModelLike): ModelInfo {\n  return {\n    provider: model.provider,\n    id: model.id,\n    fullId: `${model.provider}${PROVIDER_SEPARATOR}${model.id}`,\n    api: model.api,\n    reasoning: model.reasoning,\n    thinkingLevelMap: model.thinkingLevelMap,\n  };\n}\n\n/** Resolve the effective thinking level from a model string (which may contain a known suffix like `:high`)\n * and an explicit thinking config value. Returns `undefined` when no thinking is applicable\n * (e.g. no model was specified, or the model has no suffix and no config was provided). */\nexport function resolveEffectiveThinking(\n  model: string | undefined,\n  configThinking: string | false | undefined,\n): string | undefined {\n  if (!model) return undefined;\n  const { thinkingSuffix } = splitKnownThinkingSuffix(model);\n  if (thinkingSuffix) return thinkingSuffix.slice(1);\n  return THINKING_LEVELS.find((level) => level === configThinking);\n}\n\nexport function splitKnownThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {\n  const colonIdx = model.lastIndexOf(THINKING_SUFFIX_SEPARATOR);\n  if (colonIdx === -1) return { baseModel: model, thinkingSuffix: '' };\n  const suffix = THINKING_LEVELS.find((level) => level === model.substring(colonIdx + 1));\n  if (!suffix) return { baseModel: model, thinkingSuffix: '' };\n  return {\n    baseModel: model.substring(0, colonIdx),\n    thinkingSuffix: `${THINKING_SUFFIX_SEPARATOR}${suffix}`,\n  };\n}\n\nexport function findModelInfo(\n  model: string | undefined,\n  availableModels: ModelInfo[] | undefined,\n  preferredProvider?: string,\n): ModelInfo | undefined {\n  if (!model || !availableModels || availableModels.length === 0) return undefined;\n  const { baseModel } = splitKnownThinkingSuffix(model);\n  const exact = availableModels.find((entry) => entry.fullId === baseModel);\n  if (exact) return exact;\n\n  // A bare id can be ambiguous across providers. Prefer the caller's provider,\n  // and otherwise resolve only when exactly one provider offers the id.\n  const matches = availableModels.filter((entry) => entry.id === baseModel);\n  if (preferredProvider) {\n    const preferred = matches.find((entry) => entry.provider === preferredProvider);\n    if (preferred) return preferred;\n  }\n  return matches.length === 1 ? matches[0] : undefined;\n}\n\nexport function getSupportedThinkingLevels(model: ModelInfo | undefined): ThinkingLevel[] {\n  if (!model) return THINKING_LEVELS.filter((level) => level !== 'max');\n  if (model.reasoning === false) return ['off'];\n\n  if (!model.thinkingLevelMap) return THINKING_LEVELS.filter((level) => level !== 'max');\n\n  const levels = THINKING_LEVELS.filter((level) => {\n    const mapped = model.thinkingLevelMap?.[level];\n    if (mapped === null) return false;\n    // The extended levels are opt-in: they count as supported only when mapped.\n    if (level === 'xhigh' || level === 'max') return mapped !== undefined;\n    return true;\n  });\n  return levels;\n}\n","/**\n * Resolving a loosely-spelled model name to a canonical `provider/id`.\n *\n * Users and agent frontmatter name models by hand, so the same string has to\n * resolve the same way wherever it is written. This is a leaf so every domain\n * can share one answer.\n *\n * DESIGN PATTERNS:\n * - Pure functions over a registry passed in, so model policy is testable with\n *   no process, no config on disk and no network\n * - Exact matches win; fuzzy matching is only ever a fallback\n * - A qualified `provider/id` query never resolves across providers, and an\n *   ambiguous match resolves to nothing rather than guessing. Picking the wrong\n *   provider costs real money\n *\n * AVOID:\n * - Splitting a model string on the first colon to find a thinking suffix; ids\n *   legitimately contain colons, which is why `splitKnownThinkingSuffix` exists\n * - Adding a second, looser resolver anywhere. Two spellings of \"the same\n *   model\" that disagree are worse than one that is occasionally strict\n */\n\nimport { type ModelInfo as AvailableModelInfo, splitKnownThinkingSuffix } from '../modelInfo';\n\nexport type { AvailableModelInfo };\n\ninterface ModelRegistryLike<TModel extends { provider: string; id: string }> {\n  getAvailable(): TModel[];\n  hasConfiguredAuth(model: TModel): boolean;\n}\n\n/** Return only models the live host can authenticate, in registry order. */\nexport function authenticatedModelInfos<TModel extends { provider: string; id: string }>(\n  registry: ModelRegistryLike<TModel>,\n): AvailableModelInfo[] {\n  return registry\n    .getAvailable()\n    .filter((model) => registry.hasConfiguredAuth(model))\n    .map((model) => ({ provider: model.provider, id: model.id, fullId: `${model.provider}/${model.id}` }));\n}\n\n/** Separates provider from id in a canonical model reference. */\nexport const PROVIDER_SEPARATOR = '/';\n\n/**\n * Separators an unqualified query may use in place of `/`. Only accepted when\n * the leading segment names a provider that actually exists, so a model id\n * containing a dot is not mistaken for `provider.id`.\n */\nconst ALTERNATE_PROVIDER_SEPARATORS = [':', '.'];\n\n/** Bounds for a trailing date stamp, wide enough to be permissive and narrow enough to reject version numbers. */\nconst MIN_DATE_STAMP_YEAR = 1900;\nconst MAX_DATE_STAMP_YEAR = 2099;\nconst MONTHS_PER_YEAR = 12;\nconst MAX_DAYS_PER_MONTH = 31;\n\n/** `-2025-10-01` and `-20251001` respectively, anchored to the end of a segment. */\nconst DASHED_DATE_STAMP = /^(.*)-(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst COMPACT_DATE_STAMP = /^(.*)-(\\d{4})(\\d{2})(\\d{2})$/;\n\n/**\n * Normalize a model id or provider segment for fuzzy comparison: case-fold,\n * treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse\n * repeated separators. Pure.\n */\nexport function normalizeModelSegment(segment: string): string {\n  return segment.toLowerCase().replace(/[._]+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');\n}\n\nfunction isPlausibleDateStamp(year: string, month: string, day: string): boolean {\n  const yyyy = Number(year);\n  const mm = Number(month);\n  const dd = Number(day);\n  return (\n    yyyy >= MIN_DATE_STAMP_YEAR &&\n    yyyy <= MAX_DATE_STAMP_YEAR &&\n    mm >= 1 &&\n    mm <= MONTHS_PER_YEAR &&\n    dd >= 1 &&\n    dd <= MAX_DAYS_PER_MONTH\n  );\n}\n\n/** Drop a trailing date stamp (`-20251001` or `-2025-10-01`) so dated and undated ids match. Pure. */\nfunction stripTrailingDateStamp(segment: string): string {\n  const dashed = DASHED_DATE_STAMP.exec(segment);\n  if (dashed && isPlausibleDateStamp(dashed[2], dashed[3], dashed[4])) return dashed[1];\n  const compact = COMPACT_DATE_STAMP.exec(segment);\n  if (compact && isPlausibleDateStamp(compact[2], compact[3], compact[4])) return compact[1];\n  return segment;\n}\n\nfunction resolveBaseModelCandidate(\n  baseModel: string,\n  availableModels: AvailableModelInfo[],\n  preferredProvider?: string,\n): string | undefined {\n  if (baseModel.includes(PROVIDER_SEPARATOR)) {\n    const exact = availableModels.find((entry) => entry.fullId === baseModel);\n    if (exact) return exact.fullId;\n  } else {\n    const exactMatches = availableModels.filter((entry) => entry.id === baseModel);\n    if (preferredProvider) {\n      const preferredMatch = exactMatches.find((entry) => entry.provider === preferredProvider);\n      if (preferredMatch) return preferredMatch.fullId;\n    }\n    if (exactMatches.length === 1) return exactMatches[0].fullId;\n  }\n\n  return fuzzyResolveModel(baseModel, availableModels, preferredProvider);\n}\n\n/**\n * Fuzzy-resolve a base model id (thinking suffix already stripped) against the\n * registry, tolerating separator, case, and optional date-stamp differences so\n * users do not have to spell provider/model exactly. A qualified `provider/id`\n * query only matches within the named provider, so this never silently switches\n * providers for security/cost-sensitive configs. Returns the matched `fullId`,\n * or `undefined` when there is no match or the match is ambiguous across\n * providers (and no `preferredProvider` disambiguates). Pure.\n */\nexport function fuzzyResolveModel(\n  baseModel: string,\n  availableModels: AvailableModelInfo[],\n  preferredProvider?: string,\n): string | undefined {\n  let queryProvider: string | undefined;\n  let queryIdRaw = baseModel;\n  const slashIdx = baseModel.indexOf(PROVIDER_SEPARATOR);\n  if (slashIdx !== -1) {\n    queryProvider = normalizeModelSegment(baseModel.slice(0, slashIdx));\n    queryIdRaw = baseModel.slice(slashIdx + 1);\n  } else {\n    for (const separator of ALTERNATE_PROVIDER_SEPARATORS) {\n      const separatorIdx = baseModel.indexOf(separator);\n      if (separatorIdx <= 0) continue;\n      const providerPart = normalizeModelSegment(baseModel.slice(0, separatorIdx));\n      if (!availableModels.some((entry) => normalizeModelSegment(entry.provider) === providerPart)) continue;\n      queryProvider = providerPart;\n      queryIdRaw = baseModel.slice(separatorIdx + 1);\n      break;\n    }\n  }\n  const queryId = normalizeModelSegment(queryIdRaw);\n  const queryIdNoDate = stripTrailingDateStamp(queryId);\n\n  const candidates = availableModels.filter((entry) => {\n    const entryId = normalizeModelSegment(entry.id);\n    if (entryId !== queryId && stripTrailingDateStamp(entryId) !== queryIdNoDate) return false;\n    if (queryProvider !== undefined && normalizeModelSegment(entry.provider) !== queryProvider) return false;\n    return true;\n  });\n  if (candidates.length === 0) return undefined;\n  if (preferredProvider) {\n    const preferredProviderNorm = normalizeModelSegment(preferredProvider);\n    const preferred = candidates.find((entry) => normalizeModelSegment(entry.provider) === preferredProviderNorm);\n    if (preferred) return preferred.fullId;\n  }\n  if (candidates.length === 1) return candidates[0].fullId;\n  return undefined;\n}\n\n/**\n * Resolve a possibly-loose model id to a canonical `provider/id` (plus any\n * thinking suffix). Exact registry matches win; fuzzy normalization\n * (separator/case/date-stamp via {@link fuzzyResolveModel}) is a fallback so\n * spelling differences still resolve. Never switches providers for a qualified\n * query. Pure.\n */\nexport function resolveModelCandidate(\n  model: string | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  preferredProvider?: string,\n): string | undefined {\n  if (!model) return undefined;\n  // With no registry to match against, the caller's spelling is all there is.\n  if (!availableModels || availableModels.length === 0) return model;\n\n  const resolvedWhole = resolveBaseModelCandidate(model, availableModels, preferredProvider);\n  if (resolvedWhole) return resolvedWhole;\n\n  const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(model);\n  if (!thinkingSuffix) return model;\n  const resolvedBase = resolveBaseModelCandidate(baseModel, availableModels, preferredProvider);\n  if (resolvedBase) return `${resolvedBase}${thinkingSuffix}`;\n  return model;\n}\n","/**\n * Decides whether a resolved model is inside the configured subagent model scope.\n *\n * DESIGN PATTERNS:\n * - Pure decision function, so scope policy can be unit-tested without config or\n *   filesystem access\n * - Severity follows provenance rather than the model: a model the caller asked\n *   for by name is an error, a model inherited from frontmatter, the settings\n *   default, or the parent session is only a warning, so tightening scope never\n *   breaks a working configuration outright\n * - Patterns match the full `provider/id`, never a bare id, so `*` cannot let an\n *   unintended provider in through a same-named model\n *\n * AVOID:\n * - Treating an empty `allow` list as \"deny everything\"; enforcement without\n *   patterns is a no-op here and is rejected at settings-parse time instead\n * - Comparing the raw model string; the thinking suffix is not part of identity\n */\n\nimport type { ModelScopeConfig } from '../../types';\nimport { splitKnownThinkingSuffix } from '../modelInfo';\n\n/** Where a resolved model originated, deciding enforcement severity. */\nexport type ModelSource = 'explicit' | 'inherited';\n\nexport interface ModelScopeViolation {\n  /** Resolved model id (without thinking suffix) that fell outside the scope. */\n  model: string;\n  severity: 'warn' | 'error';\n  message: string;\n  allowedPatterns: string[];\n}\n\n/** RegExp metacharacters that must be escaped. `*` is excluded: it is the glob wildcard. */\nconst REGEXP_SPECIALS_EXCEPT_WILDCARD = /[.+^${}()|[\\]\\\\]/g;\nconst GLOB_WILDCARD = /\\*/g;\n/** What `*` expands to: any run of characters, including `/`, so `anthropic/*` covers every id. */\nconst WILDCARD_EXPANSION = '.*';\n\nfunction stripThinkingSuffix(model: string): string {\n  return splitKnownThinkingSuffix(model).baseModel;\n}\n\n/** Escape RegExp specials except `*`, then turn `*` into `.*`. */\nfunction globToRegExp(pattern: string): RegExp {\n  const escaped = pattern.replace(REGEXP_SPECIALS_EXCEPT_WILDCARD, '\\\\$&').replace(GLOB_WILDCARD, WILDCARD_EXPANSION);\n  return new RegExp(`^${escaped}$`, 'i');\n}\n\n/**\n * Test whether a resolved model matches a single allow pattern. Both sides are\n * compared case-insensitively against the full `provider/id` (thinking suffix\n * stripped from the model).\n */\nexport function matchesScopePattern(model: string, pattern: string): boolean {\n  return globToRegExp(pattern).test(stripThinkingSuffix(model));\n}\n\n/**\n * Pure scope decision. Returns a {@link ModelScopeViolation} when the model is\n * out of scope and enforcement is on, otherwise `undefined`. Enforcement with\n * no `allow` list is a no-op (the settings parser rejects that combination, but\n * this stays defensive for callers that build configs programmatically).\n */\nexport function checkModelScope(\n  model: string | undefined,\n  scope: ModelScopeConfig | undefined,\n  source: ModelSource,\n): ModelScopeViolation | undefined {\n  if (!model || !scope?.enforce) return undefined;\n  const allow = scope.allow;\n  if (!allow || allow.length === 0) return undefined;\n  if (allow.some((pattern) => matchesScopePattern(model, pattern))) return undefined;\n\n  const baseModel = stripThinkingSuffix(model);\n  const severity: ModelScopeViolation['severity'] = source === 'explicit' ? 'error' : 'warn';\n  return {\n    model: baseModel,\n    severity,\n    allowedPatterns: allow,\n    message:\n      `Model '${baseModel}' is outside the configured subagent model scope. ` +\n      `Allowed patterns: ${allow.join(', ')}.`,\n  };\n}\n","/**\n * Resolving which model a child run uses, and which models it may fall back to.\n *\n * WHY A CHILD IS ALWAYS GIVEN AN EXPLICIT MODEL:\n * Without a `provider/id` on the command line, a child resolves its own model\n * from the global agent settings file, which every open session shares. Another\n * session that changed its model in the TUI would then silently decide this\n * session's children. Passing the parent's in-memory model keeps each session's\n * children isolated to that session.\n *\n * DESIGN PATTERNS:\n * - Every resolver is pure, so model policy is testable without a registry, a\n *   process, or config on disk\n * - Enforcement severity follows provenance: a model the caller named explicitly\n *   throws when out of scope, an inherited one only warns, so tightening scope\n *   never breaks a working configuration outright\n * - Fuzzy matching tolerates separator, case, and date-stamp spelling but never\n *   crosses providers for a qualified query, and refuses ambiguous matches\n *   rather than guessing, because the wrong provider costs real money\n *\n * AVOID:\n * - Retrying a different model on a tool failure; the model was never the\n *   problem and the retry reruns the whole task\n * - Splitting a model string on the first colon to find the thinking suffix;\n *   ids legitimately contain colons\n */\n\nimport type { ModelScopeConfig, Usage } from '../../types';\nimport { type ModelInfo as AvailableModelInfo, splitKnownThinkingSuffix } from '../modelInfo';\nimport { PROVIDER_SEPARATOR, resolveModelCandidate } from '../modelResolution';\nimport { checkModelScope, type ModelScopeViolation, type ModelSource } from '../modelScope';\n\n// Re-exported so the runs domain still reads as the entry point for model\n// resolution, while the definitions stay in a leaf both domains can reach.\nexport { fuzzyResolveModel, normalizeModelSegment, resolveModelCandidate } from '../modelResolution';\nexport type { AvailableModelInfo };\n\n/** One finished attempt at running a child on a given model. */\nexport interface ModelAttemptSummary {\n  model: string;\n  success: boolean;\n  exitCode?: number | null;\n  error?: string;\n  usage?: Usage;\n}\n\n/** Sentinel model value requesting that a subagent inherit the parent session's model. */\nexport const INHERIT_MODEL = 'inherit';\n\nconst FALLBACK_NOTE_PREFIX = '[fallback]';\nconst EXPLICIT_MODEL_SOURCE: ModelSource = 'explicit';\nconst INHERITED_MODEL_SOURCE: ModelSource = 'inherited';\n\n/** Minimal shape of the parent session's in-memory model (`ctx.model`). */\nexport interface ParentModel {\n  provider: string;\n  id: string;\n}\n\nexport function normalizeParentModel(model: unknown): ParentModel | undefined {\n  if (!model || typeof model !== 'object') return undefined;\n  if (!('provider' in model) || !('id' in model)) return undefined;\n  const { provider, id } = model;\n  if (typeof provider !== 'string' || typeof id !== 'string') return undefined;\n  if (!provider || !id) return undefined;\n  return { provider, id };\n}\n\nexport interface ResolveSubagentModelOverrideOptions {\n  /** When set with `enforce: true`, out-of-scope models are rejected. */\n  scope?: ModelScopeConfig;\n  /** Origin of the requested model: explicit caller-supplied (hard error) vs inherited (warn). Defaults to `\"inherited\"`. */\n  source?: ModelSource;\n  /** Sink for warn-severity violations. Without it they are dropped; see `discardScopeViolation`. */\n  onWarn?: (violation: ModelScopeViolation) => void;\n}\n\n/**\n * Where a warn-severity scope violation goes when the caller supplies no sink.\n *\n * Deliberately silent rather than writing to stdio. This module runs inside both\n * the parent's TUI process and a detached runner whose stdout is the child's\n * captured transcript, so writing here would corrupt one and pollute the other.\n * The violation is advisory by definition: its error-severity sibling throws\n * instead. A composition root that wants these visible passes `onWarn` and\n * routes them into that process's own diagnostics.\n */\nfunction discardScopeViolation(_violation: ModelScopeViolation): void {}\n\n/**\n * Resolve the `--model` override passed to a spawned subagent.\n *\n * When no model is requested (`undefined`, `false`, empty, or the `\"inherit\"`\n * sentinel), the child inherits the parent session's in-memory `provider/id`\n * rather than being left to resolve its own; see the module header for why.\n *\n * An explicitly requested model string is resolved via {@link resolveModelCandidate}.\n * When `options.scope.enforce` is on, an out-of-scope resolved model throws for\n * an explicit (`source: \"explicit\"`) request and warns for an inherited one.\n */\nexport function resolveSubagentModelOverride(\n  requestedModel: string | boolean | undefined,\n  parentModel: ParentModel | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  preferredProvider?: string,\n  options?: ResolveSubagentModelOverrideOptions,\n): string | undefined {\n  const trimmed = typeof requestedModel === 'string' ? requestedModel.trim() : '';\n  const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;\n  let resolved: string | undefined;\n  if (explicit === undefined) {\n    resolved = parentModel ? `${parentModel.provider}${PROVIDER_SEPARATOR}${parentModel.id}` : undefined;\n  } else {\n    resolved = resolveModelCandidate(explicit, availableModels, preferredProvider);\n  }\n  if (resolved && options?.scope?.enforce) {\n    // A model that fell back to the parent's was never explicitly requested,\n    // whatever the caller declared, so it can only ever warn.\n    const source = explicit === undefined ? INHERITED_MODEL_SOURCE : (options.source ?? INHERITED_MODEL_SOURCE);\n    const violation = checkModelScope(resolved, options.scope, source);\n    if (violation) {\n      if (violation.severity === 'error') throw new Error(violation.message);\n      (options.onWarn ?? discardScopeViolation)(violation);\n    }\n  }\n  return resolved;\n}\n\n/**\n * Resolve the model for a run from the caller's request, falling back to the\n * agent's own declared model. A caller-supplied model that resolves to nothing\n * retries against the agent's, which is inherited and so only ever warns.\n */\nexport function resolveEffectiveSubagentModel(\n  explicitModel: string | boolean | undefined,\n  agentModel: string | boolean | undefined,\n  parentModel: ParentModel | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  preferredProvider?: string,\n  options?: Omit<ResolveSubagentModelOverrideOptions, 'source'>,\n): string | undefined {\n  const resolved = resolveSubagentModelOverride(\n    explicitModel ?? agentModel,\n    parentModel,\n    availableModels,\n    preferredProvider,\n    { ...options, source: explicitModel !== undefined ? EXPLICIT_MODEL_SOURCE : INHERITED_MODEL_SOURCE },\n  );\n  if (resolved || explicitModel === undefined) return resolved;\n  return resolveSubagentModelOverride(agentModel, parentModel, availableModels, preferredProvider, {\n    ...options,\n    source: INHERITED_MODEL_SOURCE,\n  });\n}\n\nexport interface BuildModelCandidatesOptions {\n  /** Fallback models are inherited agent config and warn, rather than error, when out of scope. */\n  scope?: ModelScopeConfig;\n  onWarn?: (violation: ModelScopeViolation) => void;\n}\n\n/**\n * Build the ordered, de-duplicated list of models to try: the primary first,\n * then each declared fallback. The primary is left to the caller to scope-check,\n * since only the caller knows whether it was explicitly requested.\n */\nexport function buildModelCandidates(\n  primaryModel: string | undefined,\n  fallbackModels: string[] | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  preferredProvider?: string,\n  options?: BuildModelCandidatesOptions,\n): string[] {\n  const seen = new Set<string>();\n  const candidates: string[] = [];\n  const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];\n  for (let index = 0; index < rawCandidates.length; index++) {\n    const raw = rawCandidates[index];\n    if (!raw) continue;\n    const normalized = resolveModelCandidate(raw.trim(), availableModels, preferredProvider);\n    if (!normalized || seen.has(normalized)) continue;\n    if (index > 0 && options?.scope?.enforce) {\n      const violation = checkModelScope(normalized, options.scope, INHERITED_MODEL_SOURCE);\n      if (violation) (options.onWarn ?? discardScopeViolation)(violation);\n    }\n    seen.add(normalized);\n    candidates.push(normalized);\n  }\n  return candidates;\n}\n\n/**\n * Pick the first configured primary/fallback model that the live parent can\n * authenticate. When no registry snapshot is supplied, preserve the primary\n * model for non-interactive callers and older persisted schedules.\n */\nexport function selectAvailableModel(\n  primaryModel: string | undefined,\n  fallbackModels: string[] | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  preferredProvider?: string,\n): string | undefined {\n  if (availableModels === undefined) return primaryModel;\n  const availableIds = new Set(availableModels.map((model) => model.fullId));\n  for (const candidate of buildModelCandidates(primaryModel, fallbackModels, availableModels, preferredProvider)) {\n    const { baseModel } = splitKnownThinkingSuffix(candidate);\n    if (availableIds.has(baseModel)) return candidate;\n  }\n  return undefined;\n}\n\nconst RETRYABLE_MODEL_FAILURE_PATTERNS = [\n  /rate\\s*limit/i,\n  /too many requests/i,\n  /\\b429\\b/,\n  /quota/i,\n  /billing/i,\n  /credit/i,\n  /auth(?:entication)?/i,\n  /unauthori[sz]ed/i,\n  /forbidden/i,\n  /api key/i,\n  /token expired/i,\n  /invalid key/i,\n  /provider.*unavailable/i,\n  /model.*unavailable/i,\n  /model.*disabled/i,\n  /model.*not found/i,\n  /unknown model/i,\n  /overloaded/i,\n  /service unavailable/i,\n  /temporar(?:ily)? unavailable/i,\n  /connection refused/i,\n  /fetch failed/i,\n  /network error/i,\n  /socket hang up/i,\n  /stream ended without finish_reason/i,\n  /upstream/i,\n  /timed? out/i,\n  /timeout/i,\n  /\\b502\\b/,\n  /\\b503\\b/,\n  /\\b504\\b/,\n  /cold.?start/i,\n  /empty response/i,\n  /no output/i,\n  /model.*(?:load|fail|error)/i,\n];\n\n/**\n * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with\n * exit code N` come from a tool call inside the child's task, not from the\n * provider/model, however network-flavored their details read. Retrying a\n * different model cannot fix them and would rerun the whole task. Tool names\n * include namespaced forms like `mcp.server/write`.\n */\nconst TOOL_FAILURE_PREFIX = /^[\\w.:@/-]+ failed (?:(?:\\(exit \\d+\\):)|(?:with exit code \\d+))(?:\\s|$)/i;\n\nexport function isRetryableModelFailure(error: string | undefined): boolean {\n  if (!error) return false;\n  if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;\n  return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));\n}\n\n/** Default exit code reported when an attempt failed without one, so the note never reads `exit undefined`. */\nconst UNKNOWN_EXIT_CODE = 1;\n\nexport function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {\n  const failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? UNKNOWN_EXIT_CODE}`;\n  return nextModel\n    ? `${FALLBACK_NOTE_PREFIX} ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`\n    : `${FALLBACK_NOTE_PREFIX} ${attempt.model} failed: ${failure}.`;\n}\n","/**\n * Which agent runtime executes a run, and how to invoke it.\n *\n * WHY THIS IS CONFIG AND NOT A CLASS PER VENDOR:\n * Every external agent CLI is the same shape from here: a binary, an argv with\n * the prompt substituted in, a working directory, and whatever it prints. There\n * is no per-vendor behaviour worth a per-vendor module, and inventing an\n * adapter interface would mean a new file, a new registration and a new test\n * suite every time someone wants to point a run at a different command. Adding\n * or retargeting a CLI is a config edit.\n *\n * WHAT THIS DELIBERATELY DOES NOT DO:\n * It does not parse vendor output. A generic runner cannot know what a given\n * CLI's JSON stream means, and pretending to would either lock the config down\n * to the two CLIs someone happened to test, or silently mis-report a third. The\n * run's final output is its output; status comes from the run lifecycle, which\n * already knows queued/running/terminal without reading a word of it.\n *\n * `pi` IS NOT IN THIS TABLE:\n * It is not an external command - it runs in-process through the SDK\n * (`runs/sdkRunnerEntry.ts`) and gets the team channel, steering and\n * structured output that an external one-shot cannot. Treating it as one more\n * row here would advertise capabilities the external path does not have.\n *\n * AVOID:\n * - Putting a secret in an argv template; argv is visible in the process table\n * - Adding a placeholder without substituting it. An unsubstituted `{prompt}`\n *   reaches the CLI literally\n */\n\nimport { PI_RUNTIME_NAME, runtimeBinaryEnvVar } from '../../types/environment';\n\n/** One external CLI, as configured. */\nexport interface RuntimeDefinition {\n  /** Binary to execute. Resolved against PATH unless overridden by env. */\n  command: string;\n  /** Argv template. `{prompt}`, `{model}` and `{cwd}` are substituted per run. */\n  args: string[];\n}\n\nexport type RuntimeTable = Record<string, RuntimeDefinition>;\n\n/**\n * Shipped defaults, overridable per entry by config.\n *\n * Both are headless one-shot invocations: the prompt goes in, the final answer\n * comes out on stdout, and the process exits. Neither is asked for a structured\n * stream, because nothing here would read it.\n */\nexport const DEFAULT_RUNTIMES: RuntimeTable = {\n  claude: { command: 'claude', args: ['-p', '{prompt}'] },\n  antigravity: { command: 'antigravity', args: ['{prompt}'] },\n};\n\nexport interface ResolvedRuntimeLaunch {\n  runtime: string;\n  command: string;\n  args: string[];\n}\n\nexport interface RuntimeSubstitutions {\n  prompt: string;\n  model?: string;\n  cwd: string;\n}\n\n/** True for the in-process SDK path, which this module does not describe. */\nexport function isPiRuntime(runtime: string | undefined): boolean {\n  return (runtime ?? PI_RUNTIME_NAME).trim() === PI_RUNTIME_NAME;\n}\n\nexport function resolveRuntimeTable(configured: RuntimeTable | undefined): RuntimeTable {\n  if (!configured) return { ...DEFAULT_RUNTIMES };\n  return { ...DEFAULT_RUNTIMES, ...configured };\n}\n\n/** Resolve the bounded external runtime binary, with an explicit test/development override. */\nfunction resolveCommand(runtime: string, definition: RuntimeDefinition, env: NodeJS.ProcessEnv): string {\n  const override = env[runtimeBinaryEnvVar(runtime)]?.trim();\n  return override || definition.command;\n}\n\nfunction substitute(template: string, values: RuntimeSubstitutions): string {\n  return template\n    .replaceAll('{prompt}', values.prompt)\n    .replaceAll('{model}', values.model ?? '')\n    .replaceAll('{cwd}', values.cwd);\n}\n\n/**\n * Resolve one run's command line.\n *\n * An argument that reduces to the empty string is dropped rather than passed:\n * a template carrying `--model {model}` for a run with no model override would\n * otherwise hand the CLI a bare `--model` with nothing after it.\n */\nexport function resolveRuntimeLaunch(\n  runtime: string,\n  table: RuntimeTable,\n  values: RuntimeSubstitutions,\n  env: NodeJS.ProcessEnv = process.env,\n): ResolvedRuntimeLaunch {\n  const definition = table[runtime];\n  if (!definition) {\n    const known = Object.keys(table).sort().join(', ') || '(none configured)';\n    throw new Error(`Unknown subagent runtime '${runtime}'. Configured runtimes: ${known}.`);\n  }\n  return {\n    runtime,\n    command: resolveCommand(runtime, definition, env),\n    args: definition.args.map((arg) => substitute(arg, values)).filter((arg) => arg.length > 0),\n  };\n}\n","/**\n * Runs a batch of async operations with at most N in flight at once, and\n * always settles all of them - one rejection never aborts its peers.\n *\n * WHY THIS EXISTS, RATHER THAN BEING INLINED INTO ITS ONE CALLER:\n * `spawnPlan.ts`'s PARALLEL mode needs exactly this shape (fire up to\n * `concurrency` tasks at once, wait for a slot to free before starting the\n * next, return every outcome regardless of individual failure), and it is a\n * property worth testing directly rather than only through spawn-plan's own\n * fixtures: \"at most N in flight at any moment\" and \"one rejection does not\n * abort its peers\" are each independently verifiable here, which is more\n * precise than inferring them from a higher-level test that also exercises\n * agent resolution, depth checks, and status writes.\n *\n * DELIBERATELY MINIMAL:\n * Bounded concurrency and settle-all, nothing else - no priority ordering\n * beyond FIFO start order, no cancellation, no `AbortSignal`. Reporting is\n * injected by the caller so this host-neutral helper never creates a telemetry\n * resource that it cannot shut down.\n */\n\nexport type ConcurrencyEventReporter = (event: string, attributes: Record<string, unknown>) => void;\n\nexport type ConcurrencyOutcome<T> = { status: 'fulfilled'; value: T } | { status: 'rejected'; reason: unknown };\n\n/**\n * Runs `factories` (each called at most once, lazily, only once a slot is\n * free) with at most `concurrency` in flight at a time. Resolves once every\n * factory has settled, in the SAME ORDER as `factories` regardless of which\n * one finished first - a caller zipping results back against its own input\n * list does not need to track indices itself.\n */\nexport async function runWithConcurrency<T>(\n  factories: ReadonlyArray<() => Promise<T>>,\n  concurrency: number,\n  report?: ConcurrencyEventReporter,\n): Promise<ConcurrencyOutcome<T>[]> {\n  const startedAt = Date.now();\n  const results: ConcurrencyOutcome<T>[] = Array.from({ length: factories.length });\n  const effectiveConcurrency = Math.max(1, Math.min(concurrency, factories.length || 1));\n  let nextIndex = 0;\n\n  async function worker(): Promise<void> {\n    for (;;) {\n      const index = nextIndex;\n      nextIndex += 1;\n      if (index >= factories.length) return;\n      try {\n        results[index] = { status: 'fulfilled', value: await factories[index]!() };\n      } catch (reason) {\n        results[index] = { status: 'rejected', reason };\n      }\n    }\n  }\n\n  report?.('doom_team.concurrency_started', {\n    'team.task_count': factories.length,\n    'team.concurrency': effectiveConcurrency,\n  });\n  await Promise.all(Array.from({ length: effectiveConcurrency }, () => worker()));\n  report?.('doom_team.concurrency_finished', {\n    'team.task_count': factories.length,\n    'team.concurrency': effectiveConcurrency,\n    'team.failure_count': results.filter((result) => result?.status === 'rejected').length,\n    duration_ms: Date.now() - startedAt,\n    outcome: 'completed',\n  });\n  return results;\n}\n","/**\n * Turns `subagent` tool params into a resolved sequence of\n * `AsyncSubagentSpawner.spawn()` calls: SINGLE (one child), PARALLEL (N\n * children, bounded by `concurrency`).\n *\n * WHY THIS IS NEW LOGIC, NOT COMPOSITION:\n * `AsyncSubagentSpawner` is deliberately a per-child primitive -\n * `childIndex`/`fanout` arrive as inputs it does not derive (see that\n * module's header). Nothing else in this package decides \"how many\n * children, in what order, at what `childIndex`\" from a `subagent` tool\n * call. That decision is this file's job.\n *\n * PREFLIGHT, ALL-OR-NOTHING:\n * `resolveCurrentSubagentDepth`/`preflightSubagentDepth` run once, before\n * anything spawns. A depth refusal throws - a declared plan that cannot run\n * at all should produce one clear refusal, not a partial fan-out.\n * `AgentDiscoveryService.find` resolves and validates every child's agent\n * name up front too, for the same reason: a typo'd agent name is a\n * preflight failure named at the tool boundary, not a spawn error surfacing\n * deep inside one child while its siblings are already running.\n *\n * ONCE THE BATCH HAS STARTED, PER-CHILD FAILURE IS A RESULT, NOT AN\n * EXCEPTION:\n * `runWithConcurrency` never lets one child's rejection abort its siblings,\n * matching `failFast` being opt-in in the schema, not the default. Every\n * child gets an outcome - `{runId, pid}` on success, `{error}` on failure -\n * and the caller (`subagentTool.ts`) decides how to report a mixed batch.\n *\n * WHAT THIS DOES NOT WIRE YET, AND WHY - FLAGGED, NOT SILENTLY GUESSED:\n * - `maxSubagentSpawnsPerSession` (`spawn-budget.ts`) is NOT enforced here.\n *   `preflightSpawnBudget` needs a durable, session-scoped `SpawnBudgetStore`\n *   that accumulates spend ACROSS separate tool calls in the same session;\n *   inventing a fresh store per call would never track real spend and would\n *   be worse than not checking at all (false confidence). Wiring this needs\n *   a real session-scoped store owned by a lifecycle-bound service - a\n *   follow-up, not guessed here.\n * - Fork context is resolved here and requires a captured persisted Pi source;\n *   unavailable or non-Pi fork requests fail closed rather than becoming fresh\n *   launches.\n * - Per-task overrides with no direct `BuildPiArgsInput` field confirmed yet\n *   (`skill`, `toolBudget`, `turnBudget`, `outputSchema`/structured output,\n *   `acceptance`, `output`/`outputMode`) are not mapped into `piArgs` for\n *   v1. Each child still gets its resolved `AgentConfig`'s own defaults\n *   (`systemPromptMode`, `inheritProjectContext`, `inheritSkills`,\n *   `systemPrompt`) - not nothing, just not every param override yet.\n *\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type {\n  DoomChildSessionScope,\n  DoomChildSessionSource,\n  DoomChildSessionServiceProvider,\n  DoomChildSessionTerminalPiForkSource,\n  DoomChildSessionV4ForkSource,\n} from '@agimon-ai/doompi-core/childSession';\nimport type { SessionManager } from '@earendil-works/pi-coding-agent';\n\nimport type { InlineAgent } from '../../schemas/subagentTool';\nimport {\n  type ResolvedSubagentCapabilityCeiling,\n  SubagentCapabilityPolicyStore,\n} from '../../schemas/team/capabilityCeiling';\nimport type { AgentConfig, AgentScope, AgentDiscoveryContract } from '../../types/agent';\nimport { PI_RUNTIME_NAME } from '../../types/environment';\nimport { type AdmissionGateContract, type AdmissionTicket, DEFAULT_ADMISSION_TIMEOUT_MS } from '../admissionGate';\nimport { resolveActiveTeamModelSpecs, resolveActiveTeamPackageConfig } from '../agentDiscovery';\nimport { adoptAgentIdentity, type AgentIdentity, claimAgentIdentity, roleFromAgent } from '../agentIdentity';\nimport { canonicalizeDiscoveryCwd } from '../agentProjectRoot';\nimport { buildSkillInjection, type SkillDiscoveryContract } from '../agentSkills';\nimport type {\n  AsyncSubagentSpawnInput,\n  AsyncSubagentSpawnResult,\n  AsyncSubagentSpawnerContract,\n} from '../asyncExecution';\nimport type { ExtensionConfig } from '../config';\nimport { preflightSubagentDepth, resolveCurrentSubagentDepth } from '../depthGuard';\nimport { DoomTeamExpectedError } from '../errors';\nimport type { McpDirectToolResolver } from '../mcpDirectToolAllowlist';\nimport { type AvailableModelInfo, type ParentModel, selectAvailableModel } from '../modelFallback';\nimport type { NativeRunCoordinatorContract } from '../nativeRunCoordinator';\nimport type { NativeTeamChannelContract } from '../nativeTeamChannel';\nimport { isPiRuntime, type RuntimeTable, resolveRuntimeLaunch, resolveRuntimeTable } from '../runtimeRegistry';\nimport { type ConcurrencyEventReporter, runWithConcurrency } from '../runWithConcurrency';\n\nconst CONTEXT_FRESH = 'fresh' as const;\nconst CONTEXT_FORK = 'fork' as const;\nconst PI_RUNTIME_REQUIREMENT = `runtime \"${PI_RUNTIME_NAME}\"`;\n\ntype SessionForkCaptureMode = 'tool' | 'settled';\n\nexport interface SessionForkSource {\n  readonly sessionFile?: string;\n  readonly leafId: string;\n  readonly terminalSource: DoomChildSessionTerminalPiForkSource;\n}\n\nexport type SessionForkSourceManager = Pick<\n  SessionManager,\n  'getSessionFile' | 'getSessionId' | 'getLeafId' | 'getLeafEntry' | 'getHeader' | 'getBranch'\n>;\n\nfunction readableSessionFile(sessionFile: string | undefined): sessionFile is string {\n  if (!sessionFile?.trim()) return false;\n  try {\n    fs.accessSync(sessionFile, fs.constants.R_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Why a capture reports a reason instead of a bare `undefined`.\n *\n * Five distinct conditions used to collapse into one `undefined`, and the\n * caller then asserted a cause it had never tested. That is how a missing\n * `captureForkSource` on the headless facet spent a long time looking like a\n * session-format problem. The reason is carried to the throw site so the error\n * names the condition that actually fired.\n */\nexport type ForkCaptureFailure = 'no-leaf' | 'no-header' | 'unsupported-version' | 'branch-mismatch' | 'no-session-id';\n\nexport type ForkCaptureResult =\n  | { readonly ok: true; readonly source: SessionForkSource }\n  | { readonly ok: false; readonly reason: ForkCaptureFailure };\n\n/** Either host's capture output, plus the absent case when no capture is installed. */\nexport type ParentForkCapture = ForkCaptureResult | DoomChildSessionV4ForkSource | undefined;\n\nconst FORK_FAILURE_TEXT: Record<ForkCaptureFailure | 'no-capture-installed', string> = {\n  'no-capture-installed': 'this host installed no fork-source capture',\n  'no-leaf': 'the parent session has no entry to branch from',\n  'no-header': 'the parent session has no readable header',\n  'unsupported-version': 'the parent session format cannot be forked',\n  'branch-mismatch': 'the parent branch did not resolve to its own leaf',\n  'no-session-id': 'the parent session has no identity',\n};\n\nexport function describeForkFailure(reason: ForkCaptureFailure | 'no-capture-installed' | undefined): string {\n  return reason ? FORK_FAILURE_TEXT[reason] : 'the parent session has no capturable branch';\n}\n\n/**\n * Map a captured parent branch onto the spawn request's fork fields.\n *\n * `parentSessionFile` and `parentLeafId` describe a terminal Pi capture only. A\n * v4 source already carries its own file and branch, so flattening it into\n * those fields would describe it in the wrong vocabulary and lose the branch.\n */\nexport function forkRequestFields(\n  captured: ParentForkCapture,\n): Pick<SpawnPlanRequest, 'parentForkSource' | 'parentSessionFile' | 'parentLeafId' | 'parentForkFailure'> {\n  if (!captured) return { parentForkFailure: 'no-capture-installed' };\n  if ('kind' in captured) return { parentForkSource: captured };\n  if (!captured.ok) return { parentForkFailure: captured.reason };\n  const { source } = captured;\n  return {\n    parentForkSource: source.terminalSource,\n    ...(source.sessionFile ? { parentSessionFile: source.sessionFile } : {}),\n    parentLeafId: source.leafId,\n  };\n}\n\n/** Capture an immutable parent branch while excluding an assistant turn whose tool is still executing. */\nexport function captureSessionForkSource(\n  manager: SessionForkSourceManager,\n  mode: SessionForkCaptureMode,\n): ForkCaptureResult {\n  const leaf = manager.getLeafEntry();\n  const leafId =\n    mode === 'tool' && leaf?.type === 'message' && leaf.message.role === 'assistant'\n      ? leaf.parentId\n      : (leaf?.id ?? manager.getLeafId());\n  const header = manager.getHeader();\n  if (!leafId) return { ok: false, reason: 'no-leaf' };\n  if (header?.type !== 'session') return { ok: false, reason: 'no-header' };\n  if (header.version !== 3) return { ok: false, reason: 'unsupported-version' };\n\n  const branch = manager.getBranch(leafId);\n  if (branch.at(-1)?.id !== leafId) return { ok: false, reason: 'branch-mismatch' };\n  const sourceSessionId = manager.getSessionId();\n  if (!sourceSessionId.trim()) return { ok: false, reason: 'no-session-id' };\n  const terminalSource: DoomChildSessionTerminalPiForkSource = Object.freeze({\n    kind: 'terminal-pi-fork',\n    sourceSessionId,\n    sourceLeafId: leafId,\n    snapshotJsonl: `${[header, ...branch].map((record) => JSON.stringify(record)).join('\\n')}\\n`,\n  });\n  const sessionFile = manager.getSessionFile();\n  return {\n    ok: true,\n    source: {\n      leafId,\n      terminalSource,\n      ...(readableSessionFile(sessionFile) ? { sessionFile } : {}),\n    },\n  };\n}\n\nexport interface SpawnPlanTaskInput {\n  agent: string;\n  inlineAgent?: InlineAgent;\n  task?: string;\n  cwd?: string;\n  model?: string;\n  runtime?: string;\n  context?: typeof CONTEXT_FRESH | typeof CONTEXT_FORK;\n  /** An existing child transcript to continue instead of starting fresh. */\n  sessionFile?: string;\n  /** An identity inherited by a restore. Absent for a fresh run, which mints one. */\n  identity?: string;\n}\n\ntype ExecutableAgentConfig = Pick<\n  AgentConfig,\n  | 'name'\n  | 'defaultContext'\n  | 'defaultReads'\n  | 'extensions'\n  | 'fallbackModels'\n  | 'inheritProjectContext'\n  | 'inheritSkills'\n  | 'mcpDirectTools'\n  | 'model'\n  | 'modelSource'\n  | 'runtime'\n  | 'skills'\n  | 'skillPath'\n  | 'subagentOnlyExtensions'\n  | 'systemPrompt'\n  | 'systemPromptMode'\n  | 'thinking'\n  | 'tools'\n>;\n\nfunction resolveEffectiveContext(\n  taskInput: SpawnPlanTaskInput,\n  agent: Pick<ExecutableAgentConfig, 'defaultContext'>,\n): typeof CONTEXT_FRESH | typeof CONTEXT_FORK {\n  return taskInput.sessionFile ? CONTEXT_FRESH : (taskInput.context ?? agent.defaultContext ?? CONTEXT_FRESH);\n}\n\nexport interface SpawnPlanRequest {\n  /** SINGLE mode: exactly one child. Mutually exclusive with `tasks`. */\n  single?: SpawnPlanTaskInput;\n  /** PARALLEL mode: N children, fanned out. Mutually exclusive with `single`. */\n  tasks?: SpawnPlanTaskInput[];\n  /** Max children in flight at once for PARALLEL mode. Ignored for SINGLE. Defaults to `config.parallel.concurrency` or 4. */\n  concurrency?: number;\n  /** Fallback cwd for any task that omits its own. */\n  cwd: string;\n  agentScope: AgentScope;\n  /** Explicit owner scope forwarded to every child runtime. */\n  sessionScope: DoomChildSessionScope;\n  /** Environment admitted to this parent session, forwarded only to native children. */\n  environment?: Readonly<Record<string, string | undefined>>;\n  /** Parent identity retained for delegation correlation. */\n  parentSessionId?: string;\n  /** Immutable parent branch used by native fork children. */\n  parentForkSource?: DoomChildSessionTerminalPiForkSource | DoomChildSessionV4ForkSource;\n  /** Why no parent branch was captured, so a refused fork can name its cause. */\n  parentForkFailure?: ForkCaptureFailure | 'no-capture-installed';\n  /** External-runtime parent source fields. */\n  parentSessionFile?: string;\n  parentLeafId?: string;\n  artifacts?: boolean;\n  /** Authenticated models reported by the live parent host. Undefined for callers without a host context. */\n  availableModels?: AvailableModelInfo[];\n  /** The live parent model, forwarded only for Pi child selection. */\n  parentModel?: ParentModel;\n  /** Overrides `resolveCurrentSubagentDepth()`'s own env read - a test seam, not a runtime path. */\n  currentDepth?: number;\n  /** Which runtime executes every child of this request. Defaults per agent, then to `pi`. */\n  runtime?: string;\n  /** Stable Pi tool-call identity used to correlate this batch. */\n  operationId?: string;\n  /** Run ids persisted by the operation journal before any process starts. */\n  preallocatedRunIds?: string[];\n}\n\n/** Everything one child spawn needs. An object because this reached ten positional parameters. */\ninterface SpawnOneChildInput {\n  runId: string;\n  operationId?: string;\n  agentConfig: ExecutableAgentConfig;\n  identity: AgentIdentity;\n  excludeTools?: string[];\n  teamPackageModels?: string[];\n  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;\n  taskInput: SpawnPlanTaskInput;\n  childIndex: number;\n  fanout: boolean;\n  fallbackCwd: string;\n  parentSessionId: string | undefined;\n  parentForkSource: DoomChildSessionTerminalPiForkSource | DoomChildSessionV4ForkSource | undefined;\n  sessionScope: DoomChildSessionScope;\n  environment: Readonly<Record<string, string | undefined>>;\n  parentSessionFile: string | undefined;\n  maxLiveRuns: number;\n  admissionTimeoutMs: number;\n  handshakeTimeoutMs: number | undefined;\n  artifacts: boolean | undefined;\n  artifactDir: ExtensionConfig['artifactDir'];\n  availableModels: AvailableModelInfo[] | undefined;\n  parentModel: ParentModel | undefined;\n  runtime: string | undefined;\n  runtimes: RuntimeTable;\n  skillProjectionCache: Map<string, ChildSkillProjection>;\n}\n\nexport interface SpawnPlanChildOutcome {\n  agent: string;\n  task: string;\n  /** This spawn's position among its siblings. Always 0 for SINGLE mode. */\n  childIndex: number;\n  runId?: string;\n  /** The generated addressable identity, for example `alan-reviewer-3`. */\n  identity?: string;\n  /** True when this run came from a one-shot inline agent definition. */\n  inline?: boolean;\n  pid?: number;\n  error?: string;\n  warning?: string;\n}\n\nexport interface SpawnPlanResult {\n  outcomes: SpawnPlanChildOutcome[];\n}\n\nconst DEFAULT_PARALLEL_CONCURRENCY = 4;\n/**\n * Hard ceiling on how many children one PARALLEL call may DECLARE.\n *\n * `concurrency` does NOT bound this, and cannot: `spawnOneChild` resolves as\n * soon as its child confirms it started, and the child then runs detached. So\n * `runWithConcurrency` throttles how fast children are STARTED, not how many\n * are running - `{tasks: [8], concurrency: 4}` ends up with eight live model\n * processes, not four. 8 matches the sibling implementation's\n * `PI_TEAM_MATE_MAX_PARALLEL`.\n *\n * This is a per-call declaration limit and nothing more. What actually bounds\n * live children across concurrent calls is `AdmissionGate`\n * (`runs/shared/admissionGate.ts`), which every spawn passes through.\n */\nconst DEFAULT_PARALLEL_MAX_TASKS = 8;\n/**\n * Process-wide ceiling on children ALIVE at once.\n *\n * Defaulted to `DEFAULT_PARALLEL_MAX_TASKS` so a single call's width is\n * exactly what it was before the gate existed; the only behaviour that\n * changes is that a second overlapping call now queues instead of stacking\n * another full batch on the machine. Raise or lower it with\n * `parallel.maxLiveRuns` in the subagent config, and bound the queue wait with\n * `parallel.admissionTimeoutMs`. It is deliberately NOT derived from the host's\n * cores or memory: a number measured on one machine is not a default.\n */\nconst DEFAULT_MAX_LIVE_RUNS = DEFAULT_PARALLEL_MAX_TASKS;\nconst INLINE_AGENT_TOOLS = ['read', 'grep', 'find', 'ls'] as const;\n\nfunction appendPromptSection(prompt: string, section: string): string {\n  if (!section) return prompt;\n  return prompt ? `${prompt}\\n\\n${section}` : section;\n}\n\nfunction bestEffortRuntimeWarnings(\n  runtime: string,\n  agentConfig: ExecutableAgentConfig,\n  excludeTools: string[] | undefined,\n): string[] {\n  if (isPiRuntime(runtime)) return [];\n\n  const warnings = [`Runtime '${runtime}' does not load Pi child extensions or hooks; launched best effort.`];\n  const unsupportedResources = [\n    ...(agentConfig.tools !== undefined || agentConfig.mcpDirectTools?.length ? ['tools'] : []),\n    ...(agentConfig.skills?.length || agentConfig.skillPath?.length ? ['skills'] : []),\n    ...(agentConfig.extensions !== undefined || agentConfig.subagentOnlyExtensions?.length ? ['extensions'] : []),\n  ];\n  if (unsupportedResources.length > 0) {\n    warnings.push(\n      `Doom Team cannot project or enforce configured Pi ${unsupportedResources.join(', ')} on runtime '${runtime}'.`,\n    );\n  }\n  if (agentConfig.skills?.length) {\n    warnings.push(`Configured skills were not injected: ${agentConfig.skills.join(', ')}.`);\n  }\n  if (excludeTools?.length) {\n    warnings.push(\n      `Runtime '${runtime}' cannot enforce Team package tool exclusions; launched best effort for: ${excludeTools.join(', ')}.`,\n    );\n  }\n  return warnings;\n}\n\ninterface ChildSkillProjection {\n  systemPrompt: string;\n  requireReadTool: boolean;\n  warnings: string[];\n}\n\ninterface ResolvedModelSelection {\n  primaryModel: string | undefined;\n  fallbackModels: string[];\n  model: string | undefined;\n}\n\nfunction resolvedModelSelection(\n  taskInput: SpawnPlanTaskInput,\n  agentConfig: Pick<ExecutableAgentConfig, 'model' | 'modelSource' | 'fallbackModels'>,\n  runtime: string,\n  parentModel: ParentModel | undefined,\n  availableModels: AvailableModelInfo[] | undefined,\n  teamPackageModels: string[] | undefined,\n): ResolvedModelSelection {\n  const parentModelId =\n    isPiRuntime(runtime) && parentModel && availableModels !== undefined\n      ? `${parentModel.provider}/${parentModel.id}`\n      : undefined;\n  const agentModels = [\n    ...(agentConfig.modelSource?.scope === 'package' ? [] : [agentConfig.model]),\n    ...(agentConfig.fallbackModels ?? []),\n  ];\n  const ordered = isPiRuntime(runtime)\n    ? [taskInput.model, ...agentModels, ...(teamPackageModels ?? []), parentModelId]\n    : [taskInput.model, ...agentModels, ...(teamPackageModels ?? [])];\n  const candidates = ordered.filter((candidate): candidate is string => Boolean(candidate?.trim()));\n  const [primaryModel, ...fallbackModels] = candidates;\n  return {\n    primaryModel,\n    fallbackModels,\n    model: selectAvailableModel(primaryModel, fallbackModels, availableModels),\n  };\n}\n\nexport interface SpawnPlannerContract {\n  /**\n   * Resolves the plan and spawns every child. Throws on any PREFLIGHT\n   * failure (bad request shape, depth exceeded, unknown agent) before\n   * anything spawns. Never throws for an individual child's spawn failure\n   * once the batch has started - that is a `{error}` outcome instead.\n   */\n  spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult>;\n}\n\nconst ERROR_CODE_AGENT_NOT_FOUND = 'agent_not_found' as const;\nconst ERROR_CODE_INVALID_REQUEST = 'invalid_request' as const;\nconst ERROR_CODE_MODEL_UNAVAILABLE = 'model_unavailable' as const;\nconst ERROR_CODE_OPERATION_CONFLICT = 'operation_conflict' as const;\nconst ERROR_CODE_RUNTIME_UNAVAILABLE = 'runtime_unavailable' as const;\nconst ERROR_CODE_UNSUPPORTED_CONTEXT = 'unsupported_context' as const;\nconst ERROR_CODE_UNSUPPORTED_OPERATION = 'unsupported_operation' as const;\n\nexport class SpawnPlanner implements SpawnPlannerContract {\n  constructor(\n    private readonly agents: AgentDiscoveryContract,\n    private readonly spawner: AsyncSubagentSpawnerContract,\n    private readonly policies: SubagentCapabilityPolicyStore = new SubagentCapabilityPolicyStore(),\n    private readonly skills?: SkillDiscoveryContract,\n    private readonly reportConcurrencyEvent?: ConcurrencyEventReporter,\n    _mcpToolResolver?: McpDirectToolResolver,\n    private readonly admission?: AdmissionGateContract,\n    private readonly childSessions?: DoomChildSessionServiceProvider,\n    private readonly nativeRuns?: NativeRunCoordinatorContract,\n    private readonly teamChannel?: Pick<NativeTeamChannelContract, 'createNativeChildIntercom'>,\n  ) {}\n\n  protected generateRunId(): string {\n    return crypto.randomUUID();\n  }\n\n  protected validateCwd(cwd: string): void {\n    let stat: fs.Stats;\n    try {\n      stat = fs.statSync(cwd);\n    } catch {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_INVALID_REQUEST,\n        `Working directory '${cwd}' does not exist.`,\n        false,\n        'Retry with an existing directory.',\n      );\n    }\n    if (!stat.isDirectory()) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_INVALID_REQUEST,\n        `Working directory '${cwd}' is not a directory.`,\n        false,\n        'Retry with an existing directory.',\n      );\n    }\n  }\n\n  protected resolveTeamPackageExcludeTools(): string[] | undefined {\n    return resolveActiveTeamPackageConfig()?.config.excludeTools;\n  }\n\n  protected resolveTeamPackageModels(): string[] | undefined {\n    return resolveActiveTeamModelSpecs();\n  }\n\n  protected executableAvailable(command: string): boolean {\n    if (path.isAbsolute(command) || command.includes(path.sep)) {\n      try {\n        fs.accessSync(command, fs.constants.X_OK);\n        return true;\n      } catch {\n        return false;\n      }\n    }\n    return (process.env.PATH ?? '')\n      .split(path.delimiter)\n      .filter(Boolean)\n      .some((directory) => {\n        try {\n          fs.accessSync(path.join(directory, command), fs.constants.X_OK);\n          return true;\n        } catch {\n          return false;\n        }\n      });\n  }\n\n  private resolveTaskList(request: SpawnPlanRequest): SpawnPlanTaskInput[] {\n    const hasSingle = request.single !== undefined;\n    const hasTasks = request.tasks !== undefined;\n    if (hasSingle === hasTasks) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_INVALID_REQUEST,\n        'A run requires exactly one of internal single or tasks representations.',\n        false,\n        'Submit a non-empty requests array.',\n      );\n    }\n    if (hasSingle) return [request.single!];\n    if (!request.tasks || request.tasks.length === 0) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_INVALID_REQUEST,\n        'A run requires at least one entry in its requests collection.',\n        false,\n        'Submit a non-empty requests array.',\n      );\n    }\n    return request.tasks;\n  }\n\n  private resolveAgentOrThrow(name: string, cwd: string, scope: AgentScope) {\n    const resolved = this.agents.find(cwd, scope, name);\n    if (!resolved) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_AGENT_NOT_FOUND,\n        `Unknown agent '${name}'.`,\n        false,\n        'Call subagent({\"action\":\"agents\"}) and retry with an exact name.',\n      );\n    }\n    return resolved;\n  }\n\n  private resolveExecutableAgent(taskInput: SpawnPlanTaskInput, cwd: string, scope: AgentScope): ExecutableAgentConfig {\n    if (!taskInput.inlineAgent) return this.resolveAgentOrThrow(taskInput.agent, cwd, scope);\n    return {\n      name: taskInput.agent.trim(),\n      systemPromptMode: 'append',\n      inheritProjectContext: true,\n      inheritSkills: false,\n      systemPrompt: taskInput.inlineAgent.systemPrompt.trim(),\n      tools: [...INLINE_AGENT_TOOLS],\n      defaultContext: CONTEXT_FRESH,\n      runtime: PI_RUNTIME_NAME,\n    };\n  }\n\n  private projectDefaultReads(\n    defaultReads: string[] | undefined,\n    childCwd: string,\n    agentName: string,\n  ): ChildSkillProjection {\n    if (!defaultReads?.length) return { systemPrompt: '', requireReadTool: false, warnings: [] };\n\n    const seen = new Set<string>();\n    const readablePaths: string[] = [];\n    const missingPaths: string[] = [];\n    for (const configuredPath of defaultReads) {\n      const trimmed = configuredPath.trim();\n      if (!trimmed) continue;\n      const resolvedPath = path.isAbsolute(trimmed) ? path.normalize(trimmed) : path.resolve(childCwd, trimmed);\n      const identity = canonicalizeDiscoveryCwd(resolvedPath);\n      if (seen.has(identity)) continue;\n      seen.add(identity);\n      try {\n        if (fs.statSync(resolvedPath).isFile()) readablePaths.push(resolvedPath);\n        else missingPaths.push(resolvedPath);\n      } catch {\n        missingPaths.push(resolvedPath);\n      }\n    }\n\n    const systemPrompt =\n      readablePaths.length > 0\n        ? [\n            'Read these configured paths before broad repository discovery:',\n            ...readablePaths.map((readPath) => `- ${readPath}`),\n            'If a listed path does not provide enough context, name the concrete missing dependency before searching narrowly for it.',\n          ].join('\\n')\n        : '';\n    return {\n      systemPrompt,\n      requireReadTool: readablePaths.length > 0,\n      warnings:\n        missingPaths.length > 0\n          ? [`Agent '${agentName}' could not read optional default paths: ${missingPaths.join(', ')}.`]\n          : [],\n    };\n  }\n\n  private projectConfiguredSkills(\n    agentConfig: ExecutableAgentConfig,\n    childCwd: string,\n    requestCwd: string,\n    runtime: string,\n    cache: Map<string, ChildSkillProjection>,\n  ): ChildSkillProjection {\n    const cacheKey = JSON.stringify([\n      canonicalizeDiscoveryCwd(childCwd),\n      canonicalizeDiscoveryCwd(requestCwd),\n      runtime,\n      agentConfig.name,\n      agentConfig.systemPrompt,\n      agentConfig.skills ?? [],\n      agentConfig.skillPath ?? [],\n      agentConfig.defaultReads ?? [],\n    ]);\n    const cached = cache.get(cacheKey);\n    if (cached) return cached;\n\n    if (!isPiRuntime(runtime)) {\n      const projection = { systemPrompt: agentConfig.systemPrompt, requireReadTool: false, warnings: [] };\n      cache.set(cacheKey, projection);\n      return projection;\n    }\n\n    const defaultReads = this.projectDefaultReads(agentConfig.defaultReads, childCwd, agentConfig.name);\n    let skillInjection = '';\n    let skillWarnings: string[] = [];\n    if (agentConfig.skills?.length) {\n      if (!this.skills) throw new Error('Skill discovery is unavailable for configured child skills.');\n      const resolution = this.skills.resolveSkillsWithFallback(\n        agentConfig.skills,\n        childCwd,\n        requestCwd,\n        agentConfig.skillPath,\n        requestCwd,\n      );\n      skillInjection = buildSkillInjection(resolution.resolved);\n      skillWarnings =\n        resolution.missing.length > 0\n          ? [\n              `Agent '${agentConfig.name}' could not resolve configured skills: ${resolution.missing.join(', ')}; launched with resolved skills only.`,\n            ]\n          : [];\n    }\n\n    const projection = {\n      systemPrompt: appendPromptSection(\n        appendPromptSection(agentConfig.systemPrompt, skillInjection),\n        defaultReads.systemPrompt,\n      ),\n      requireReadTool: skillInjection.length > 0 || defaultReads.requireReadTool,\n      warnings: [...skillWarnings, ...defaultReads.warnings],\n    };\n    cache.set(cacheKey, projection);\n    return projection;\n  }\n\n  /**\n   * Spawns exactly one child and returns its outcome. Shared by `spawn()`\n   * (SINGLE/PARALLEL) and `spawnChain()`'s per-step/per-parallel-group-child\n   * calls, so the `AsyncSubagentSpawnInput` mapping exists in exactly one\n   * place. Never throws - a spawn failure becomes an `{error}` outcome, per\n   * the \"preflight throws, per-child failure does not\" split documented in\n   * the module header.\n   */\n  private async spawnOneChild(input: SpawnOneChildInput): Promise<SpawnPlanChildOutcome> {\n    const {\n      runId,\n      operationId,\n      agentConfig,\n      identity,\n      capabilityCeiling,\n      excludeTools,\n      teamPackageModels,\n      taskInput,\n      childIndex,\n      fanout,\n      fallbackCwd,\n      parentSessionId,\n      parentForkSource,\n      sessionScope,\n      environment,\n      parentSessionFile,\n      maxLiveRuns,\n      admissionTimeoutMs,\n      handshakeTimeoutMs,\n      artifacts,\n      artifactDir,\n      availableModels,\n      parentModel,\n      runtime,\n      runtimes,\n      skillProjectionCache,\n    } = input;\n    const cwd = taskInput.cwd ?? fallbackCwd;\n    const task = taskInput.task ?? '';\n    const effectiveContext = resolveEffectiveContext(taskInput, agentConfig);\n    const effectiveRuntime = taskInput.runtime ?? runtime ?? agentConfig.runtime ?? PI_RUNTIME_NAME;\n    const modelSelection = resolvedModelSelection(\n      taskInput,\n      agentConfig,\n      effectiveRuntime,\n      parentModel,\n      availableModels,\n      teamPackageModels,\n    );\n    if (modelSelection.primaryModel && availableModels !== undefined && !modelSelection.model) {\n      return {\n        agent: agentConfig.name,\n        identity: identity.identity,\n        inline: identity.inline,\n        task,\n        childIndex,\n        error: `No authenticated model is available for '${agentConfig.name}'. Checked: ${[\n          modelSelection.primaryModel,\n          ...modelSelection.fallbackModels,\n        ].join(', ')}.`,\n      };\n    }\n\n    let skillProjection: ChildSkillProjection;\n    try {\n      skillProjection = this.projectConfiguredSkills(\n        agentConfig,\n        cwd,\n        fallbackCwd,\n        effectiveRuntime,\n        skillProjectionCache,\n      );\n    } catch (error) {\n      return {\n        agent: agentConfig.name,\n        identity: identity.identity,\n        inline: identity.inline,\n        task,\n        childIndex,\n        error: error instanceof Error ? error.message : String(error),\n      };\n    }\n    const warnings = [\n      ...skillProjection.warnings,\n      ...bestEffortRuntimeWarnings(effectiveRuntime, agentConfig, excludeTools),\n    ];\n    const warning = warnings.length > 0 ? warnings.join(' ') : undefined;\n\n    // Persist every Pi child's own transcript so a later explicit restore can\n    // continue it. External runtimes retain their existing session behavior.\n    const spawnInput: AsyncSubagentSpawnInput = {\n      runId,\n      ...(operationId ? { operationId } : {}),\n      agent: agentConfig.name,\n      ...(taskInput.inlineAgent ? { inlineAgent: taskInput.inlineAgent } : {}),\n      task,\n      cwd,\n      environment,\n      childIndex,\n      fanout,\n      sessionScope,\n      ...(parentSessionFile ? { parentSessionFile } : {}),\n      piArgs: {\n        ...(taskInput.sessionFile ? { sessionFile: taskInput.sessionFile } : {}),\n        ...(modelSelection.model ? { model: modelSelection.model } : {}),\n        ...(capabilityCeiling ? { capabilityCeiling } : {}),\n        ...(effectiveContext === CONTEXT_FORK && parentSessionId ? { parentSessionId } : {}),\n      },\n      ...(handshakeTimeoutMs !== undefined ? { handshakeTimeoutMs } : {}),\n      ...(artifacts !== undefined ? { artifacts } : {}),\n      ...(artifactDir !== undefined ? { artifactDir } : {}),\n      // Per-call `runtime` wins over the agent's own default, matching how\n      // `model` and `context` already resolve.\n      runtime: effectiveRuntime,\n      runtimes,\n    };\n\n    const admission = this.admission;\n    if (!admission) throw new Error('Doom Team spawn admission is not configured.');\n    let ticket: AdmissionTicket;\n    try {\n      ticket = await admission.admit({\n        sessionScope,\n        maxLiveRuns,\n        timeoutMs: admissionTimeoutMs,\n        ...(this.reportConcurrencyEvent ? { report: this.reportConcurrencyEvent } : {}),\n      });\n    } catch (error) {\n      return {\n        agent: agentConfig.name,\n        task,\n        childIndex,\n        error: error instanceof Error ? error.message : String(error),\n        ...(warning ? { warning } : {}),\n      };\n    }\n\n    try {\n      if (isPiRuntime(effectiveRuntime)) {\n        if (!this.nativeRuns || !this.childSessions?.get())\n          throw new Error('The native Team run coordinator is unavailable.');\n        const scope = sessionScope;\n        const source: DoomChildSessionSource = taskInput.sessionFile\n          ? { kind: 'v4-restore', sessionFile: taskInput.sessionFile }\n          : effectiveContext === CONTEXT_FORK\n            ? (parentForkSource ??\n              (() => {\n                throw new Error('Native fork input requires an immutable terminal Pi snapshot.');\n              })())\n            : { kind: 'fresh' };\n        const intercom = this.teamChannel?.createNativeChildIntercom({\n          rootSessionId: scope.rootSessionId,\n          agent: agentConfig.name,\n          identity: identity.identity,\n          inline: identity.inline,\n          runId,\n          childIndex,\n          task: { id: runId, subject: task },\n        });\n        let child: Awaited<ReturnType<NativeRunCoordinatorContract['start']>>;\n        try {\n          child = await this.nativeRuns.start(\n            parentSessionId ?? scope.rootSessionId,\n            {\n              runId,\n              parentSessionId: parentSessionId ?? scope.rootSessionId,\n              scope,\n              source,\n              agent: agentConfig.name,\n              task,\n              cwd,\n              ...(modelSelection.model ? { model: modelSelection.model } : {}),\n              ...(typeof agentConfig.thinking === 'string' ? { thinking: agentConfig.thinking } : {}),\n              ...(skillProjection.systemPrompt ? { systemPrompt: skillProjection.systemPrompt } : {}),\n              systemPromptMode: agentConfig.systemPromptMode,\n              ...(agentConfig.extensions ? { extensions: agentConfig.extensions } : {}),\n              ...(agentConfig.subagentOnlyExtensions\n                ? { subagentOnlyExtensions: agentConfig.subagentOnlyExtensions }\n                : {}),\n              ...(agentConfig.tools\n                ? { tools: [...new Set([...agentConfig.tools, ...(capabilityCeiling?.requiredTools ?? [])])] }\n                : {}),\n              ...(excludeTools ? { excludeTools } : {}),\n              ...(agentConfig.skills ? { skills: agentConfig.skills } : {}),\n              ...(agentConfig.mcpDirectTools ? { mcpDirectTools: agentConfig.mcpDirectTools } : {}),\n              ...(capabilityCeiling ? { capabilityCeiling } : {}),\n              ...(intercom ? { intercom } : {}),\n              environment,\n            },\n            // Carried beside the core child request rather than inside it, so a\n            // Team-only concept does not widen the shared child contract.\n            { identity: identity.identity, inline: identity.inline },\n          );\n        } catch (error) {\n          intercom?.dispose?.();\n          throw error;\n        }\n        return {\n          agent: agentConfig.name,\n          identity: identity.identity,\n          inline: identity.inline,\n          task,\n          childIndex,\n          runId: child.runId,\n          ...(warning ? { warning } : {}),\n        };\n      }\n      const result: AsyncSubagentSpawnResult = await this.spawner.spawn(spawnInput);\n      return {\n        agent: agentConfig.name,\n        identity: identity.identity,\n        inline: identity.inline,\n        task,\n        childIndex,\n        runId: result.runId,\n        pid: result.pid,\n        ...(warning ? { warning } : {}),\n      };\n    } catch (error) {\n      return {\n        agent: agentConfig.name,\n        identity: identity.identity,\n        inline: identity.inline,\n        task,\n        childIndex,\n        error: error instanceof Error ? error.message : String(error),\n        ...(warning ? { warning } : {}),\n      };\n    } finally {\n      // Once spawn resolves, direct child events make the run visible to the\n      // injected live counter, so only the reservation is released here.\n      ticket.release();\n    }\n  }\n\n  async spawn(request: SpawnPlanRequest, config: ExtensionConfig): Promise<SpawnPlanResult> {\n    const tasks = this.resolveTaskList(request);\n    const fanout = tasks.length > 1;\n    const teamPackageExcludeTools = this.resolveTeamPackageExcludeTools();\n    const teamPackageModels = this.resolveTeamPackageModels();\n    const capabilityCeiling = this.policies.resolve();\n\n    // PREFLIGHT - all before any spawn call, so a declared plan that cannot\n    // run at all produces one refusal, not a partial fan-out.\n    const currentDepth = request.currentDepth ?? resolveCurrentSubagentDepth();\n    const depthCheck = preflightSubagentDepth(currentDepth, config);\n    if (depthCheck.error) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_UNSUPPORTED_OPERATION,\n        depthCheck.error,\n        false,\n        'Give each child a self-contained task within the Team package policy.',\n      );\n    }\n\n    const maxTasks = config.parallel?.maxTasks ?? DEFAULT_PARALLEL_MAX_TASKS;\n    if (tasks.length > maxTasks) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_INVALID_REQUEST,\n        `Run requested ${tasks.length} tasks, but at most ${maxTasks} may be declared in one call. Concurrency throttles how fast they start, not how many run.`,\n        false,\n        'Send at most that many requests in this call and wait for them, or raise parallel.maxTasks in the subagent config. Splitting the same width across extra calls does not raise the live-child ceiling.',\n      );\n    }\n\n    for (const taskInput of tasks) {\n      if (!taskInput.task?.trim()) {\n        throw new DoomTeamExpectedError(\n          ERROR_CODE_INVALID_REQUEST,\n          `Run request for '${taskInput.agent}' requires a nonblank task.`,\n          false,\n          'Provide a self-contained nonblank task.',\n        );\n      }\n      if (taskInput.inlineAgent && !taskInput.inlineAgent.systemPrompt.trim()) {\n        throw new DoomTeamExpectedError(\n          ERROR_CODE_INVALID_REQUEST,\n          `Inline agent '${taskInput.agent}' requires a nonblank system prompt.`,\n          false,\n          'Provide a focused read-only exploration role.',\n        );\n      }\n    }\n\n    const resolvedAgentCache = new Map<string, ExecutableAgentConfig>();\n    const resolvedAgents = tasks.map((taskInput) => {\n      if (taskInput.inlineAgent) {\n        return this.resolveExecutableAgent(taskInput, taskInput.cwd ?? request.cwd, request.agentScope);\n      }\n      const cacheKey = [\n        request.agentScope,\n        canonicalizeDiscoveryCwd(taskInput.cwd ?? request.cwd),\n        taskInput.agent,\n      ].join('\\0');\n      const cached = resolvedAgentCache.get(cacheKey);\n      if (cached) return cached;\n      const resolved = this.resolveExecutableAgent(taskInput, taskInput.cwd ?? request.cwd, request.agentScope);\n      resolvedAgentCache.set(cacheKey, resolved);\n      return resolved;\n    });\n    for (const [index, taskInput] of tasks.entries()) {\n      const effectiveContext = resolveEffectiveContext(taskInput, resolvedAgents[index]!);\n      const runtime = taskInput.runtime ?? request.runtime ?? resolvedAgents[index]!.runtime ?? PI_RUNTIME_NAME;\n      if (effectiveContext === CONTEXT_FORK) {\n        if (!isPiRuntime(runtime)) {\n          throw new DoomTeamExpectedError(\n            ERROR_CODE_UNSUPPORTED_CONTEXT,\n            `Fork context requires ${PI_RUNTIME_REQUIREMENT} for '${taskInput.agent}'.`,\n            false,\n            'Use a Pi agent for fork context or explicitly request a fresh run.',\n          );\n        }\n        if (!request.parentForkSource) {\n          throw new DoomTeamExpectedError(\n            ERROR_CODE_UNSUPPORTED_CONTEXT,\n            `Fork context is unavailable for '${taskInput.agent}': ${describeForkFailure(request.parentForkFailure)}.`,\n            false,\n            'Use an active Pi session with a completed parent turn or explicitly request a fresh run.',\n          );\n        }\n      }\n    }\n\n    if (request.preallocatedRunIds && request.preallocatedRunIds.length !== tasks.length) {\n      throw new DoomTeamExpectedError(\n        ERROR_CODE_OPERATION_CONFLICT,\n        'The operation journal run-id count does not match the request count.',\n        false,\n        'Submit the run as a new tool call.',\n      );\n    }\n    const runIds = request.preallocatedRunIds ?? tasks.map(() => this.generateRunId());\n    // Minted here because this is the one funnel every spawn path reaches, and\n    // because the inline flag and the resolved agent name are both in hand. A\n    // restore carries its identity in, and repoints the existing claim rather\n    // than burning a second number on the same logical agent.\n    const identities = tasks.map((taskInput, index) => {\n      const inline = taskInput.inlineAgent !== undefined;\n      if (!taskInput.identity) {\n        return claimAgentIdentity(request.sessionScope, {\n          agent: resolvedAgents[index]!.name,\n          inline,\n          runId: runIds[index]!,\n        });\n      }\n      adoptAgentIdentity(request.sessionScope, taskInput.identity, runIds[index]!);\n      return {\n        identity: taskInput.identity,\n        name: '',\n        role: roleFromAgent(resolvedAgents[index]!.name),\n        number: 0,\n        inline,\n        persisted: true,\n      };\n    });\n    const runtimes = resolveRuntimeTable(config.runtimes);\n    for (const [index, taskInput] of tasks.entries()) {\n      const agent = resolvedAgents[index]!;\n      const cwd = taskInput.cwd ?? request.cwd;\n      this.validateCwd(cwd);\n      const runtime = taskInput.runtime ?? request.runtime ?? agent.runtime ?? PI_RUNTIME_NAME;\n      const modelSelection = resolvedModelSelection(\n        taskInput,\n        agent,\n        runtime,\n        request.parentModel,\n        request.availableModels,\n        teamPackageModels,\n      );\n      if (modelSelection.primaryModel && request.availableModels !== undefined && !modelSelection.model) {\n        throw new DoomTeamExpectedError(\n          ERROR_CODE_MODEL_UNAVAILABLE,\n          `No authenticated model is available for '${agent.name}'.`,\n          false,\n          'Authenticate the requested model or choose an available model.',\n        );\n      }\n      if (taskInput.inlineAgent && !isPiRuntime(runtime)) {\n        throw new DoomTeamExpectedError(\n          ERROR_CODE_UNSUPPORTED_OPERATION,\n          `Inline agent '${taskInput.agent}' requires ${PI_RUNTIME_REQUIREMENT} to enforce its read-only tools.`,\n          false,\n          'Remove the runtime override or use a discovered external-runtime agent without inlineAgent.',\n        );\n      }\n      if (capabilityCeiling && !isPiRuntime(runtime)) {\n        throw new DoomTeamExpectedError(\n          ERROR_CODE_UNSUPPORTED_OPERATION,\n          `Runtime '${runtime}' cannot enforce the active capability ceiling.`,\n          false,\n          `Use ${PI_RUNTIME_REQUIREMENT} while plan mode or another capability ceiling is active.`,\n        );\n      }\n      if (!isPiRuntime(runtime)) {\n        let command: string;\n        try {\n          command = resolveRuntimeLaunch(runtime, runtimes, { prompt: taskInput.task ?? '', cwd }).command;\n        } catch (error) {\n          throw new DoomTeamExpectedError(\n            ERROR_CODE_RUNTIME_UNAVAILABLE,\n            error instanceof Error ? error.message : String(error),\n            false,\n            `Configure a valid external runtime or use ${PI_RUNTIME_REQUIREMENT}.`,\n          );\n        }\n        if (!this.executableAvailable(command)) {\n          throw new DoomTeamExpectedError(\n            ERROR_CODE_RUNTIME_UNAVAILABLE,\n            `Executable '${command}' for runtime '${runtime}' is unavailable.`,\n            false,\n            `Install the executable, configure its absolute path, or use ${PI_RUNTIME_REQUIREMENT}.`,\n          );\n        }\n      }\n    }\n    const concurrency = fanout\n      ? (request.concurrency ?? config.parallel?.concurrency ?? DEFAULT_PARALLEL_CONCURRENCY)\n      : 1;\n    const maxLiveRuns = Math.max(1, config.parallel?.maxLiveRuns ?? DEFAULT_MAX_LIVE_RUNS);\n    const admissionTimeoutMs = config.parallel?.admissionTimeoutMs ?? DEFAULT_ADMISSION_TIMEOUT_MS;\n\n    const skillProjectionCache = new Map<string, ChildSkillProjection>();\n    const factories = tasks.map(\n      (taskInput, childIndex) => () =>\n        this.spawnOneChild({\n          runId: runIds[childIndex]!,\n          operationId: request.operationId,\n          agentConfig: resolvedAgents[childIndex]!,\n          identity: identities[childIndex]!,\n          excludeTools: teamPackageExcludeTools,\n          teamPackageModels,\n          capabilityCeiling,\n          taskInput,\n          childIndex,\n          fanout,\n          fallbackCwd: request.cwd,\n          parentSessionId: request.parentSessionId,\n          parentForkSource: request.parentForkSource,\n          sessionScope: request.sessionScope,\n          environment: request.environment ?? {},\n          parentSessionFile: request.parentSessionFile,\n          maxLiveRuns,\n          admissionTimeoutMs,\n          handshakeTimeoutMs: config.handshakeTimeoutMs,\n          artifacts: request.artifacts,\n          artifactDir: config.artifactDir,\n          availableModels: request.availableModels,\n          parentModel: request.parentModel,\n          runtime: request.runtime,\n          runtimes,\n          skillProjectionCache,\n        }),\n    );\n\n    const settled = await runWithConcurrency(factories, concurrency, this.reportConcurrencyEvent);\n    // `spawnOneChild` never rejects (it catches its own spawn failure into\n    // an `{error}` outcome), so `runWithConcurrency` never sees a rejection\n    // here - this unwrap is defensive, not a real branch.\n    const outcomes = settled.map((outcome, index) =>\n      outcome.status === 'fulfilled'\n        ? outcome.value\n        : {\n            agent: resolvedAgents[index]!.name,\n            identity: identities[index]!.identity,\n            inline: identities[index]!.inline,\n            task: tasks[index]!.task ?? '',\n            childIndex: index,\n            error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason),\n          },\n    );\n\n    return { outcomes };\n  }\n}\n","/**\n * Serves `doom-task` through Team's session-bound delegation service: turn a\n * request into a spawned run, report its progress, and settle it exactly once.\n *\n * WHY THIS IS NOT IN `pi.ts`:\n * It used to be, inline, and it was the single largest reason that file failed\n * `thin-pi-adapter`: roughly 250 lines of orchestration, state and protocol\n * handling sitting in what should be a lifecycle shim. None of it is Pi\n * lifecycle - it is a request/response state machine that happens to be started\n * from one. Here it is testable without activating an extension.\n *\n * SETTLING EXACTLY ONCE IS THE WHOLE CONTRACT:\n * A delegation can be finished by four racing paths - the run completing, the\n * wait timing out, an explicit cancel, and a session teardown. `finish()` is\n * the only writer, guarded by the request's own `settled` flag, so whichever\n * arrives first wins and the rest are no-ops. `settledRequestIds` then keeps a\n * bounded memory of what already finished, because a late duplicate request\n * for an id that has already settled must not start a second run.\n *\n * AVOID:\n * - Publishing a terminal event from anywhere but `finish()`\n * - Letting the settled set grow without bound; it is a dedupe window, not a\n *   ledger\n */\n\nimport {\n  DelegationCancelSchema,\n  DOOM_DELEGATION_ACCEPTED_EVENT,\n  DOOM_DELEGATION_CANCELLED_EVENT,\n  DOOM_DELEGATION_FINISHED_EVENT,\n  DOOM_DELEGATION_STARTED_EVENT,\n  DOOM_DELEGATION_UPDATED_EVENT,\n  DOOM_DELEGATION_REQUESTED_EVENT,\n  type DoomDelegationService,\n  type DelegationRequest,\n  DelegationRequestSchema,\n  type DelegationResult,\n} from '@agimon-ai/doompi-core/delegation';\nimport type { Context } from '@deepseek-ai/cordis';\nimport { Check } from 'typebox/value';\n\nimport type { AsyncJobTrackerContract, TrackedAsyncJobsContract } from '../asyncJobTracker';\nimport type { ExtensionConfig } from '../config';\nimport type { ManagementActionsContract } from '../managementActions';\nimport type { AvailableModelInfo, ParentModel } from '../modelFallback';\nimport type { PollSchedulerContract } from '../pollScheduler';\nimport type { SessionScope } from '../sessionPaths';\nimport { forkRequestFields, type ParentForkCapture, type SpawnPlannerContract } from '../spawnPlan';\nimport type { SubagentWaiterContract } from '../subagentWait';\n\nconst DEFAULT_DELEGATION_TIMEOUT_MS = 20 * 60 * 1000;\nconst DELEGATION_TIMEOUT_WARNING_MAX_LEAD_MS = 2 * 60 * 1000;\nconst DELEGATION_TIMEOUT_WARNING_FRACTION = 0.1;\nconst DELEGATION_PROGRESS_INTERVAL_MS = 250;\nconst SETTLED_DELEGATION_WINDOW = 256;\n\n/**\n * Terminal states, named because they are an external contract with\n * `doom-task`'s `DelegationManager`, which branches on the exact strings.\n */\nconst STATUS_COMPLETED = 'completed';\nconst STATUS_CANCELLED = 'cancelled';\nconst STATUS_FAILED = 'failed';\nconst STATUS_TIMED_OUT = 'timed_out';\nconst FAILED_RUN_ID_PREFIX = 'failed:';\nconst CANCELLED_RUN_ID_PREFIX = 'cancelled:';\n\ninterface ActiveDelegation {\n  requestId: string;\n  taskId: string | number;\n  controller: AbortController;\n  runId?: string;\n  /** Wall-clock start captured after the child has been acknowledged. */\n  runtimeStartedAt?: number;\n  cancelRequested: boolean;\n  settled: boolean;\n  disposeProgress?: () => void;\n}\n\n/** What the bridge needs from the session it is bound to, read fresh per call. */\nexport interface DelegationSessionContext {\n  sessionId: string;\n  sessionScope: SessionScope;\n  availableModels: AvailableModelInfo[];\n  parentModel?: ParentModel;\n  /**\n   * Read fresh per delegation request. Never cached: Pi does not persist a\n   * transcript until the session's first assistant message, so a value captured\n   * when the session binds is empty for a new session and stale after a resume.\n   */\n  captureForkSource?: () => Promise<ParentForkCapture> | ParentForkCapture;\n}\n\nexport interface DelegationBridgeDeps {\n  planner: SpawnPlannerContract;\n  management: ManagementActionsContract;\n  waiter: SubagentWaiterContract;\n  scheduler: PollSchedulerContract;\n  tracker: AsyncJobTrackerContract;\n  loadConfig: () => ExtensionConfig;\n}\n\nexport interface DelegationBridge {\n  /** Create the generation-bound service published for one Team session. */\n  createService(ctx: Context, session: DelegationSessionContext): DoomDelegationService;\n  /** Abandon every in-flight delegation without notifying, for a session teardown. */\n  abandonAll(): void;\n}\n\nexport function createDelegationBridge(deps: DelegationBridgeDeps): DelegationBridge {\n  const active = new Map<string, ActiveDelegation>();\n  const settledRequestIds = new Set<string>();\n\n  const rememberSettled = (requestId: string): void => {\n    settledRequestIds.add(requestId);\n    if (settledRequestIds.size > SETTLED_DELEGATION_WINDOW) {\n      settledRequestIds.delete(settledRequestIds.values().next().value as string);\n    }\n  };\n\n  /** The one writer of a terminal outcome. See the module header. */\n  const finish = (entry: ActiveDelegation, result: DelegationResult, ctx: Context): void => {\n    if (entry.settled) return;\n    entry.settled = true;\n    entry.disposeProgress?.();\n    active.delete(entry.requestId);\n    rememberSettled(entry.requestId);\n    ctx.emit(DOOM_DELEGATION_FINISHED_EVENT, result);\n  };\n\n  /** Ask the run to stop. Returns the failure message when the request itself failed. */\n  const stop = (entry: ActiveDelegation, reason: string): string | undefined => {\n    if (!entry.runId) return undefined;\n    try {\n      void deps.management.stop(entry.runId, reason);\n      return undefined;\n    } catch (error) {\n      return error instanceof Error ? error.message : String(error);\n    }\n  };\n\n  const monitor = async (\n    entry: ActiveDelegation,\n    request: DelegationRequest,\n    ctx: Context,\n    jobs: TrackedAsyncJobsContract,\n    sessionId: string,\n    sessionScope: SessionScope,\n  ): Promise<void> => {\n    const runId = entry.runId;\n    if (!runId) return;\n\n    const timeoutMs = request.timeoutMs ?? DEFAULT_DELEGATION_TIMEOUT_MS;\n    const warningLeadMs = Math.min(\n      DELEGATION_TIMEOUT_WARNING_MAX_LEAD_MS,\n      Math.max(1, Math.floor(timeoutMs * DELEGATION_TIMEOUT_WARNING_FRACTION)),\n    );\n    const warningAt = (entry.runtimeStartedAt ?? Date.now()) + timeoutMs - warningLeadMs;\n    let timeoutWarningSent = false;\n    let lastProgress = '';\n    entry.disposeProgress = deps.scheduler.register({\n      id: `delegation:${entry.requestId}`,\n      intervalMs: DELEGATION_PROGRESS_INTERVAL_MS,\n      run: () => {\n        const job = jobs.get(runId);\n        if (!job) return false;\n        let worked = false;\n        if (!timeoutWarningSent && Date.now() >= warningAt) {\n          timeoutWarningSent = true;\n          const secondsRemaining = Math.max(1, Math.ceil(warningLeadMs / 1000));\n          const secondsLabel = `${secondsRemaining} second${secondsRemaining === 1 ? '' : 's'}`;\n          void deps.management\n            .steer(\n              runId,\n              `This delegation will time out in about ${secondsLabel}. Stop exploring now, complete the highest-value remaining work, and return a concise result before the deadline. If you cannot finish, return verified findings and blockers immediately.`,\n            )\n            .catch(() => undefined);\n          worked = true;\n        }\n        const progressKey = [job.status, job.updatedAt, job.error, job.tokens, job.currentTool, job.toolCount]\n          .map((value) => String(value))\n          .join(':');\n        if (progressKey === lastProgress) return worked;\n        lastProgress = progressKey;\n        ctx.emit(DOOM_DELEGATION_UPDATED_EVENT, {\n          requestId: entry.requestId,\n          runId,\n          ...(job.status !== undefined ? { status: job.status } : {}),\n          ...(entry.runtimeStartedAt !== undefined\n            ? { durationMs: Math.max(0, Date.now() - entry.runtimeStartedAt) }\n            : {}),\n          ...(job.tokens !== undefined ? { tokens: job.tokens } : {}),\n          ...(job.currentTool !== undefined ? { currentTool: job.currentTool } : {}),\n          ...(job.toolCount !== undefined ? { toolCount: job.toolCount } : {}),\n        });\n        return true;\n      },\n    });\n    deps.scheduler.wake();\n\n    const wait = await deps.waiter.wait({\n      target: { id: runId },\n      sessionId,\n      sessionScope,\n      waitFor: 'completion',\n      timeoutMs,\n      signal: entry.controller.signal,\n    });\n    if (entry.settled) return;\n\n    if (wait.reason === 'timeout') {\n      const stopError = stop(entry, 'Delegation timed out.');\n      finish(\n        entry,\n        {\n          requestId: entry.requestId,\n          runId,\n          status: STATUS_TIMED_OUT,\n          error: stopError ?? `Delegation produced no result within ${timeoutMs}ms`,\n          durationMs: wait.elapsedMs,\n        },\n        ctx,\n      );\n      return;\n    }\n    if (wait.reason === 'aborted' || entry.cancelRequested) {\n      finish(entry, { requestId: entry.requestId, runId, status: STATUS_CANCELLED, durationMs: wait.elapsedMs }, ctx);\n      return;\n    }\n    if (wait.reason !== 'completed') {\n      finish(\n        entry,\n        {\n          requestId: entry.requestId,\n          runId,\n          status: STATUS_FAILED,\n          error: `Delegation wait ended with ${wait.reason}.`,\n          durationMs: wait.elapsedMs,\n        },\n        ctx,\n      );\n      return;\n    }\n\n    const status = deps.management.status(runId).status;\n    const completed = status?.state === 'complete' || status?.state === STATUS_COMPLETED;\n    const cancelled = status?.state === 'stopped' && entry.cancelRequested;\n    finish(\n      entry,\n      {\n        requestId: entry.requestId,\n        runId,\n        status: completed ? STATUS_COMPLETED : cancelled ? STATUS_CANCELLED : STATUS_FAILED,\n        ...(status?.summary ? { output: status.summary } : {}),\n        ...(status?.error ? { error: status.error } : {}),\n        ...(status?.sessionFile ? { sessionFile: status.sessionFile } : {}),\n        durationMs:\n          status?.endedAt && status.startedAt ? Math.max(0, status.endedAt - status.startedAt) : wait.elapsedMs,\n      },\n      ctx,\n    );\n  };\n\n  const onRequested = async (\n    request: DelegationRequest,\n    ctx: Context,\n    session: DelegationSessionContext,\n  ): Promise<void> => {\n    if (active.has(request.requestId) || settledRequestIds.has(request.requestId)) return;\n    const entry: ActiveDelegation = {\n      requestId: request.requestId,\n      taskId: request.taskId,\n      controller: new AbortController(),\n      cancelRequested: false,\n      settled: false,\n    };\n    active.set(request.requestId, entry);\n    ctx.emit(DOOM_DELEGATION_ACCEPTED_EVENT, { requestId: request.requestId });\n\n    try {\n      const forkSource = await session.captureForkSource?.();\n      const result = await deps.planner.spawn(\n        {\n          single: {\n            agent: request.agent,\n            ...(request.inlineAgent ? { inlineAgent: request.inlineAgent } : {}),\n            task: request.prompt,\n            model: request.model,\n            ...(request.context ? { context: request.context } : {}),\n          },\n          cwd: request.cwd,\n          agentScope: 'both',\n          sessionScope: session.sessionScope,\n          parentSessionId: session.sessionId,\n          ...forkRequestFields(forkSource),\n          availableModels: session.availableModels,\n          ...(session.parentModel ? { parentModel: session.parentModel } : {}),\n        },\n        deps.loadConfig(),\n      );\n      const outcome = result.outcomes[0];\n      if (!outcome?.runId) {\n        finish(\n          entry,\n          {\n            requestId: request.requestId,\n            runId: `${FAILED_RUN_ID_PREFIX}${String(request.taskId)}`,\n            status: STATUS_FAILED,\n            error: outcome?.error ?? 'Delegation did not start.',\n          },\n          ctx,\n        );\n        return;\n      }\n\n      entry.runId = outcome.runId;\n      const jobs = deps.tracker.forSession(session.sessionId, session.sessionScope);\n      jobs.track(\n        outcome.runId,\n        outcome.identity ? { identity: outcome.identity, inline: outcome.inline ?? false } : undefined,\n      );\n      // A cancel that landed while the spawn was in flight already settled this\n      // entry; the run exists now, so it has to be stopped rather than tracked.\n      if (entry.settled) {\n        void stop(entry, 'Delegation was cancelled before launch completed.');\n        return;\n      }\n      entry.runtimeStartedAt = Date.now();\n      ctx.emit(DOOM_DELEGATION_STARTED_EVENT, { requestId: request.requestId, runId: outcome.runId });\n      await monitor(entry, request, ctx, jobs, session.sessionId, session.sessionScope);\n    } catch (error) {\n      finish(\n        entry,\n        {\n          requestId: request.requestId,\n          runId: entry.runId ?? `${FAILED_RUN_ID_PREFIX}${String(request.taskId)}`,\n          status: STATUS_FAILED,\n          error: error instanceof Error ? error.message : String(error),\n        },\n        ctx,\n      );\n    }\n  };\n\n  const onCancelled = (requestId: string, reason: string | undefined, ctx: Context): void => {\n    const entry = active.get(requestId);\n    if (!entry || entry.settled) return;\n    entry.cancelRequested = true;\n    const stopError = stop(entry, reason ?? 'Delegation cancelled by requester.');\n    entry.controller.abort();\n    finish(\n      entry,\n      {\n        requestId,\n        runId: entry.runId ?? `${CANCELLED_RUN_ID_PREFIX}${String(entry.taskId)}`,\n        status: STATUS_CANCELLED,\n        ...(stopError ? { error: stopError } : {}),\n      },\n      ctx,\n    );\n  };\n\n  return {\n    createService(ctx, session) {\n      const service: DoomDelegationService = {\n        sessionId: session.sessionId,\n        generation: `doom-delegation:${crypto.randomUUID()}`,\n        async request(request) {\n          if (!Check(DelegationRequestSchema, request)) throw new TypeError('Invalid delegation request.');\n          ctx.emit(DOOM_DELEGATION_REQUESTED_EVENT, request);\n          await onRequested(request, ctx, session);\n        },\n        cancel(request) {\n          if (!Check(DelegationCancelSchema, request)) throw new TypeError('Invalid delegation cancel request.');\n          ctx.emit(DOOM_DELEGATION_CANCELLED_EVENT, request);\n          onCancelled(request.requestId, request.reason, ctx);\n        },\n      };\n      return Object.freeze(service);\n    },\n\n    /**\n     * Teardown, not cancellation: the requester is going away with us, so there\n     * is nobody left to notify. Marked settled first so an in-flight `monitor`\n     * that wakes during shutdown finds the entry closed and stays quiet.\n     */\n    abandonAll() {\n      for (const entry of active.values()) {\n        entry.settled = true;\n        entry.controller.abort();\n        entry.disposeProgress?.();\n      }\n      active.clear();\n      settledRequestIds.clear();\n    },\n  };\n}\n","import type { ExternalProcessEndpoint, ExternalRunnerMessage } from '../externalProcessIpc';\nimport { parseExternalRunnerMessage } from '../externalProcessIpc';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport interface SpawnHandshakeOptions {\n  /** Bounded parent-child process IPC endpoint for this runner. */\n  child: ExternalProcessEndpoint;\n  /** Exact run identity accepted from the child. */\n  runId: string;\n  /** Exact session scope accepted from the child. */\n  scopeKey: string;\n  timeoutMs?: number;\n}\n\nexport type SpawnHandshakeOutcome =\n  | { status: 'signalled' }\n  | { status: 'failed'; error: string }\n  | { status: 'timed-out' };\n\nexport interface SpawnHandshakeWait {\n  promise: Promise<SpawnHandshakeOutcome>;\n  /** Reject early and tear down. */\n  cancel: (reason: string) => void;\n}\n\nexport type SpawnHandshakeContract = {\n  waitForHandshake(options: SpawnHandshakeOptions): SpawnHandshakeWait;\n};\n\nexport class SpawnHandshake implements SpawnHandshakeContract {\n  protected readonly defaultTimeoutMs: number = DEFAULT_TIMEOUT_MS;\n\n  waitForHandshake(options: SpawnHandshakeOptions): SpawnHandshakeWait {\n    const timeoutMs = options.timeoutMs ?? this.defaultTimeoutMs;\n    let settled = false;\n    let removeMessage: (() => void) | undefined;\n    let timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n    let rejectWait: ((reason: unknown) => void) | undefined;\n\n    const cleanup = (): void => {\n      if (timeoutTimer) clearTimeout(timeoutTimer);\n      timeoutTimer = undefined;\n      removeMessage?.();\n      removeMessage = undefined;\n    };\n\n    const promise = new Promise<SpawnHandshakeOutcome>((resolve, reject) => {\n      rejectWait = reject;\n      const settle = (outcome: SpawnHandshakeOutcome): void => {\n        if (settled) return;\n        settled = true;\n        cleanup();\n        resolve(outcome);\n      };\n      removeMessage = options.child.onMessage((raw) => {\n        const message: ExternalRunnerMessage | undefined = parseExternalRunnerMessage(raw, {\n          runId: options.runId,\n          scopeKey: options.scopeKey,\n        });\n        if (!message) return;\n        if (message.kind === 'ready') settle({ status: 'signalled' });\n        else if (message.kind === 'error') settle({ status: 'failed', error: message.error });\n      });\n      timeoutTimer = setTimeout(() => settle({ status: 'timed-out' }), timeoutMs);\n      timeoutTimer.unref?.();\n    });\n\n    return {\n      promise,\n      cancel: (reason: string) => {\n        if (settled) return;\n        settled = true;\n        cleanup();\n        rejectWait?.(new Error(reason));\n      },\n    };\n  }\n}\n","/**\n * Parent-side launcher for bounded external Claude and Codex subprocesses.\n *\n * Native Pi runs never enter this adapter. They are started in-process through\n * the typed child-session service. External launch, readiness, control, status,\n * result, errors, and exit all use the child process IPC channel. Files written\n * by this path are durable logs and result artifacts only.\n */\n\nimport { spawn } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { InlineAgent } from '../../schemas/subagentTool';\nimport type { SubagentCapabilityCeiling } from '../../schemas/team/capabilityCeiling';\nimport type { ActivityState, ArtifactDirPreference } from '../../types';\nimport { SUBAGENT_RUN_ID_ENV } from '../../types/environment';\nimport {\n  CLAUDE_FABLE_PROFILE,\n  type ClaudeFableLaunch,\n  cleanupClaudeFableLaunch,\n  prepareClaudeFableLaunch,\n} from '../claudeFableProfile';\nimport { childProcessEndpoint, ExternalProcessIpc, type ExternalProcessEndpoint } from '../externalProcessIpc';\nimport { isPiRuntime, type RuntimeTable, resolveRuntimeLaunch } from '../runtimeRegistry';\nimport { scopeResultsDir, sessionScopeEnvironment, scopeRunsDir, type SessionScope } from '../sessionPaths';\nimport { type SpawnHandshakeContract, SpawnHandshake } from '../spawnHandshake';\nimport type { StatusWithRecentEntries } from '../statusWriter';\n\nexport const RUNNER_STDOUT_FILE_NAME = 'runner.stdout.log';\nexport const RUNNER_STDERR_FILE_NAME = 'runner.stderr.log';\nexport const FABLE_PROFILE_RESULT_FILE_NAME = 'fable-profile-result.json';\n/**\n * The effective system prompt this run launched with, kept for the fleet\n * inspector's agent view.\n *\n * A SIDECAR RATHER THAN A FIELD ON status.json: `CoalescedStatusWriter`\n * rewrites the whole status file on every coalesced flush, and a system prompt\n * is kilobytes of text that never changes after spawn. Inlining it would put\n * that payload through every status write for the life of the run. This file\n * is written once, next to the status it belongs to.\n *\n * Written 0600 for the same reason `piArgs.ts` writes its prompt file that\n * way: a resolved prompt can carry inherited project context.\n */\nexport const SYSTEM_PROMPT_FILE_NAME = 'system-prompt.md';\nconst DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;\n\n/**\n * `state`/`steps`/`parallelGroups`/`chainStepCount`/`workflowGraph`/\n * `pendingAppends` are declared as optional-and-widened, rather than a\n * runner-owned status type, so this SAME status shape is what\n * `chain-append.ts`'s `applyChainAppendRequest` (which expects\n * `AppendableChainStatus`, an object with exactly these optional fields) can\n * mutate directly - one status type for the whole spawn-through-finalize\n * lifecycle, not a parent-side one and a child-side one that have to be kept\n * in sync by hand.\n */\nexport interface AsyncRunStatus extends StatusWithRecentEntries {\n  /** Version 1 is emitted by current writers; absent is accepted only by the compatibility reader. */\n  version?: 1;\n  runId: string;\n  operationId?: string;\n  agent: string;\n  /** Original task text required to restore a suspended run. */\n  task?: string;\n  cwd?: string;\n  /** Resolved model selected for this run, when one was requested. */\n  model?: string;\n  /** One-shot agent definition required to restore an inline agent. */\n  inlineAgent?: InlineAgent;\n  state: 'queued' | 'running' | 'complete' | 'completed' | 'failed' | 'paused' | 'stopped';\n  startedAt: number;\n  lastUpdate: number;\n  endedAt?: number;\n  /** This run's position among its fan-out siblings, when it has any. Absent for a standalone run. */\n  fanoutIndex?: number;\n  /** Bridge-owned runs are consumed internally and never rendered as generic completion chat. */\n  internal?: boolean;\n  /** Which runtime executes this run. Absent means the default in-process `pi` path. */\n  runtime?: string;\n  activityState?: ActivityState;\n  attentionReason?: string;\n  error?: string;\n  /**\n   * Set once, at finalize, by `RunnerReporting.mutateTerminalStatus` - the\n   * SAME value it puts in the terminal result file, truncated to a bounded\n   * length (see that module's header for why). Lets a caller (chain mode,\n   * in particular) learn a completed run's own summary through the status\n   * file it already reads to learn the run finished, rather than needing a\n   * second read of a claimed, single-consumer result file.\n   */\n  summary?: string;\n  /**\n   * This run's own Pi session transcript path, written during child bootstrap\n   * and retained by `RunnerReporting.mutateTerminalStatus` at finalize. See\n   * that module's header for where the value comes from and why it is bounded\n   * by omission, not truncation. Absent for a run that either never reported\n   * a session file (headless, no persisted transcript) or reported one too\n   * long to trust. This is what `action='resume'` reads to know which\n   * transcript a later revival should reopen.\n   */\n  sessionFile?: string;\n  /** Child-owned Pi SDK event transcript consumed by the fleet detail pane. */\n  transcriptPath?: string;\n  /**\n   * Sidecar holding this run's effective system prompt, and the resolved tool\n   * plan it launched with. Recorded at spawn purely so the fleet inspector can\n   * show what an agent was actually told: the launch config that carried them\n   * is deleted as soon as the child handshakes, and the agent definition on\n   * disk can change while a run is still going.\n   *\n   * All absent for a non-`pi` runtime, which has no SDK launch settings, and\n   * for any run started before this was recorded.\n   */\n  systemPromptPath?: string;\n  systemPromptMode?: 'append' | 'replace';\n  /** Effective tool allowlist. Absent means \"whatever the child defaults to\". */\n  tools?: string[];\n  excludeTools?: string[];\n  noTools?: boolean;\n  /** Cumulative tokens observed from finalized child messages. */\n  tokens?: number;\n  /** Cumulative cost observed from finalized child messages. */\n  cost?: number;\n  /** Most recently started child tool. */\n  currentTool?: string;\n  /** Number of child tool executions observed so far. */\n  toolCount?: number;\n}\n\nexport interface ExternalLaunchSettings {\n  model?: string;\n  capabilityCeiling?: SubagentCapabilityCeiling;\n  sessionFile?: string;\n  parentSessionId?: string;\n}\n\nexport interface AsyncSubagentSpawnInput {\n  runId: string;\n  operationId?: string;\n  agent: string;\n  /** One-shot agent definition retained only for explicit suspension restore. */\n  inlineAgent?: InlineAgent;\n  task: string;\n  cwd: string;\n  /** Immutable environment admitted to the owning session. */\n  environment: Readonly<Record<string, string | undefined>>;\n  /** Persisted parent transcript used to place child artifacts beside the parent session. */\n  parentSessionFile?: string;\n  /** This spawn's position among its siblings. 0 for a standalone (non-fan-out) run. */\n  childIndex: number;\n  /** Whether this spawn is one of several children under a fan-out parent. */\n  fanout: boolean;\n  /** External CLI model and capability constraints. */\n  piArgs: ExternalLaunchSettings;\n  /** False disables the child event transcript. Defaults to enabled. */\n  artifacts?: boolean;\n  /** Suppress persistence of sensitive task text in status.json. */\n  sensitiveTask?: boolean;\n  /** Bridge-owned runs are consumed internally rather than rendered as generic chat. */\n  internal?: boolean;\n  /** Artifact root policy inherited from the parent Doom Team config. */\n  artifactDir?: ArtifactDirPreference;\n  handshakeTimeoutMs?: number;\n  /**\n   * Which runtime executes this run. Defaults to the in-process Pi SDK path.\n   * Anything else is an external CLI resolved through `runtimeRegistry.ts`.\n   */\n  runtime?: string;\n  /** Fixed trusted external profile. Only Doom Team internal bridges may set this. */\n  externalProfile?: string;\n  /** Session-owned filesystem root for this child run. */\n  sessionScope: SessionScope;\n  /** Runtimes available to this spawn, already merged with the shipped defaults. */\n  runtimes?: RuntimeTable;\n}\n\nexport interface AsyncSubagentSpawnResult {\n  runId: string;\n  pid: number;\n}\n\nexport type AsyncSubagentSpawnerContract = {\n  /** Spawn one child and return once it has confirmed it started. Throws on any failure to reach that point. */\n  spawn(input: AsyncSubagentSpawnInput): Promise<AsyncSubagentSpawnResult>;\n};\n\n/** `runs/<runId>` under the explicit session scope. */\nexport function runDirFor(scope: SessionScope, runId: string): string {\n  return path.join(scopeRunsDir(scope), runId);\n}\n\nexport function fableProfileResultPathFor(scope: SessionScope, runId: string): string {\n  return path.join(runDirFor(scope, runId), FABLE_PROFILE_RESULT_FILE_NAME);\n}\n\n/** Where `spawn()` records this run's effective system prompt. See `SYSTEM_PROMPT_FILE_NAME`. */\nexport function systemPromptPathFor(scope: SessionScope, runId: string): string {\n  return path.join(runDirFor(scope, runId), SYSTEM_PROMPT_FILE_NAME);\n}\n\n/** Locate a child entry point on disk, built or source. */\nfunction resolveRunnerEntry(builtRelativePath: string, sourceRelativePath: string, stem: string): string {\n  let directory = path.dirname(fileURLToPath(import.meta.url));\n  while (true) {\n    const packageManifest = path.join(directory, 'package.json');\n    if (fs.existsSync(packageManifest)) {\n      const builtCandidate = path.join(directory, 'dist', `${builtRelativePath}.mjs`);\n      if (fs.existsSync(builtCandidate)) return builtCandidate;\n      const sourceCandidate = path.join(directory, 'src', `${sourceRelativePath}.ts`);\n      if (fs.existsSync(sourceCandidate)) return sourceCandidate;\n      throw new Error(`Doom Team runner '${stem}' is unavailable at '${builtCandidate}' or '${sourceCandidate}'.`);\n    }\n    const parent = path.dirname(directory);\n    if (parent === directory) throw new Error(`Could not locate the Doom Team package root for runner '${stem}'.`);\n    directory = parent;\n  }\n}\n\nfunction resolveCliRunnerEntry(): string {\n  return resolveRunnerEntry('runs/background/cliRunnerEntry', 'bin/cliRunner', 'cliRunnerEntry');\n}\n\nexport class AsyncSubagentSpawner implements AsyncSubagentSpawnerContract {\n  constructor(private readonly externalProcesses?: ExternalProcessIpc) {}\n\n  /**\n   * Runtime tuning seam for tests, kept out of the dependency constructor.\n   */\n  protected readonly defaultHandshakeTimeoutMs: number = DEFAULT_HANDSHAKE_TIMEOUT_MS;\n\n  protected now(): number {\n    return Date.now();\n  }\n\n  /** Spawn a detached external runner with a live IPC channel and durable output logs. */\n  protected spawnChild(\n    scope: SessionScope,\n    command: string,\n    args: string[],\n    options: { cwd: string; env: NodeJS.ProcessEnv },\n  ): {\n    pid: number | undefined;\n    onError: (handler: (error: Error) => void) => void;\n    onExit: (handler: (code: number | null, signal: NodeJS.Signals | null) => void) => void;\n    onMessage?: (handler: (message: unknown) => void) => () => void;\n    send?: (message: object) => Promise<void>;\n    disconnect?: () => void;\n  } {\n    const runId = options.env[SUBAGENT_RUN_ID_ENV];\n    let stdoutFd: number | undefined;\n    let stderrFd: number | undefined;\n    if (runId) {\n      const runDir = runDirFor(scope, runId);\n      fs.mkdirSync(runDir, { recursive: true });\n      stdoutFd = fs.openSync(path.join(runDir, RUNNER_STDOUT_FILE_NAME), 'a', 0o600);\n      try {\n        stderrFd = fs.openSync(path.join(runDir, RUNNER_STDERR_FILE_NAME), 'a', 0o600);\n      } catch (error) {\n        fs.closeSync(stdoutFd);\n        throw new Error(`Could not open runner stderr for '${runId}'.`, { cause: error });\n      }\n    }\n    let child: ReturnType<typeof spawn>;\n    try {\n      child = spawn(command, args, {\n        cwd: options.cwd,\n        detached: true,\n        // The fourth descriptor is the sole live control/status transport.\n        stdio: ['ignore', stdoutFd ?? 'ignore', stderrFd ?? 'ignore', 'ipc'],\n        windowsHide: true,\n        env: options.env,\n      });\n    } finally {\n      if (stdoutFd !== undefined) fs.closeSync(stdoutFd);\n      if (stderrFd !== undefined) fs.closeSync(stderrFd);\n    }\n    child.unref();\n    child.channel?.unref();\n    const endpoint = childProcessEndpoint(child as unknown as Parameters<typeof childProcessEndpoint>[0]);\n    return {\n      pid: child.pid,\n      onError: (handler) => child.on('error', handler),\n      onExit: (handler) => child.on('exit', handler),\n      onMessage: (handler) => endpoint.onMessage(handler),\n      send: (message) => endpoint.send(message),\n      disconnect: () => endpoint.disconnect?.(),\n    };\n  }\n\n  /** Construct a fresh process handshake for one bounded external spawn. */\n  protected createSpawnHandshake(): SpawnHandshakeContract {\n    return new SpawnHandshake();\n  }\n\n  async spawn(input: AsyncSubagentSpawnInput): Promise<AsyncSubagentSpawnResult> {\n    const { runId, agent, task, cwd, sessionScope: scope } = input;\n    const runtime = input.runtime;\n    if (isPiRuntime(runtime) || runtime === undefined) {\n      throw new Error('Native Pi runs must be launched through the in-process child-session service.');\n    }\n\n    const externalProcesses = this.externalProcesses;\n    if (!externalProcesses) throw new Error('External process IPC is not configured.');\n\n    const runDir = runDirFor(scope, runId);\n    const env: NodeJS.ProcessEnv = {\n      ...input.environment,\n      ...sessionScopeEnvironment(scope),\n      [SUBAGENT_RUN_ID_ENV]: runId,\n    };\n    let fableLaunch: ClaudeFableLaunch | undefined;\n    let launchConfig: Record<string, unknown>;\n    const fail = (message: string): never => {\n      if (fableLaunch) cleanupClaudeFableLaunch(fableLaunch);\n      fs.rmSync(fableProfileResultPathFor(scope, runId), { force: true });\n      throw new Error(message);\n    };\n\n    const ceiling = input.piArgs.capabilityCeiling;\n    if (\n      ceiling &&\n      (!input.externalProfile || !(ceiling.allowedExternalProfiles ?? []).includes(input.externalProfile))\n    ) {\n      return fail(`External profile '${input.externalProfile ?? 'none'}' is denied by the active capability ceiling.`);\n    }\n    if (input.externalProfile !== undefined && input.externalProfile !== CLAUDE_FABLE_PROFILE) {\n      return fail(`External profile '${input.externalProfile}' is not trusted.`);\n    }\n    if (input.externalProfile === CLAUDE_FABLE_PROFILE) {\n      if (runtime !== 'claude' || input.piArgs.model !== 'fable') {\n        return fail('The Fable profile requires runtime claude and model fable.');\n      }\n      if (input.inlineAgent || input.piArgs.sessionFile || input.piArgs.parentSessionId) {\n        return fail('The Fable profile requires a fresh isolated context.');\n      }\n      fableLaunch = prepareClaudeFableLaunch({\n        runId,\n        prompt: task,\n        repositoryCwd: cwd,\n        privateRoot: runDir,\n      });\n      launchConfig = {\n        runId,\n        ...(input.operationId ? { operationId: input.operationId } : {}),\n        agent,\n        task,\n        sensitiveTask: input.sensitiveTask === true,\n        runtime: 'claude',\n        command: fableLaunch.command,\n        args: fableLaunch.args,\n        cwd: fableLaunch.cwd,\n        env: fableLaunch.env,\n        profile: fableLaunch.profile,\n        stdinPath: fableLaunch.stdinPath,\n        cleanupPaths: fableLaunch.cleanupPaths,\n        profileResultPath: fableProfileResultPathFor(scope, runId),\n        resultPath: path.join(scopeResultsDir(scope), `${runId}.json`),\n        internal: input.internal === true,\n      };\n    } else {\n      launchConfig = {\n        runId,\n        ...(input.operationId ? { operationId: input.operationId } : {}),\n        agent,\n        task,\n        sensitiveTask: input.sensitiveTask === true,\n        ...resolveRuntimeLaunch(runtime, input.runtimes ?? {}, {\n          prompt: task,\n          model: input.piArgs.model,\n          cwd,\n        }),\n        cwd,\n        env: Object.fromEntries(\n          Object.entries(env).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),\n        ),\n        resultPath: path.join(scopeResultsDir(scope), `${runId}.json`),\n        internal: input.internal === true,\n      };\n    }\n\n    const child = this.spawnChild(scope, process.execPath, [resolveCliRunnerEntry()], {\n      cwd,\n      env,\n    });\n    if (child.pid === undefined) return fail(`Async spawn for '${agent}' (run '${runId}') did not produce a pid.`);\n    if (!child.onMessage || !child.send) {\n      return fail(`Async spawn for '${agent}' (run '${runId}') did not produce an IPC endpoint.`);\n    }\n\n    let spawnError: Error | undefined;\n    child.onError((error) => {\n      spawnError = error;\n    });\n    const endpoint: ExternalProcessEndpoint = {\n      onMessage: child.onMessage,\n      onExit: (handler) => {\n        child.onExit(handler);\n        return () => undefined;\n      },\n      send: child.send,\n      ...(child.disconnect ? { disconnect: child.disconnect } : {}),\n    };\n    const unregister = externalProcesses.register(scope, runId, endpoint);\n    const wait = this.createSpawnHandshake().waitForHandshake({\n      child: endpoint,\n      runId,\n      scopeKey: scope.scopeKey,\n      timeoutMs: input.handshakeTimeoutMs ?? this.defaultHandshakeTimeoutMs,\n    });\n    try {\n      await externalProcesses.launch(scope, runId, launchConfig);\n    } catch (error) {\n      wait.cancel(error instanceof Error ? error.message : String(error));\n      unregister();\n      return fail(error instanceof Error ? error.message : String(error));\n    }\n    const outcome = await wait.promise;\n    if (outcome.status !== 'signalled') {\n      unregister();\n      const message =\n        outcome.status === 'failed'\n          ? outcome.error\n          : (spawnError?.message ?? `Timed out waiting for '${agent}' (run '${runId}') to start.`);\n      return fail(message);\n    }\n    return { runId, pid: child.pid };\n  }\n}\n","/**\n * Runs stopped by a session shutdown, and enough about each to start it again.\n *\n * WHY EVERY SHUTDOWN SUSPENDS, WITH NO SPECIAL CASE FOR `reload`:\n * Pi emits `session_shutdown` for `quit`, `reload`, `new`, `resume` and `fork`.\n * An earlier design kept children alive across `reload` alone, on the grounds\n * that `/domains`, `/major-mode` and `/profile` reload the extension rather than\n * change the session. That is true, and it still makes `reload` the one case\n * behaving differently from the other four - which is a rule someone has to\n * remember, and a branch that silently does the wrong thing if Pi ever adds a\n * sixth reason. Suspending uniformly costs a respawn on reload and removes the\n * special case; restore is cheap because the child continues its own transcript\n * rather than starting over.\n *\n * WHY RESTORE IS OFFERED AND NEVER AUTOMATIC:\n * Reopening a session would otherwise spawn N processes and start spending\n * tokens on tasks that may be days stale. `session_start` reports what is\n * suspended; something explicit has to ask for it back.\n *\n * AVOID:\n * - Auto-restoring from any lifecycle event\n * - Recording a suspended run without its `sessionFile`; without it a restore\n *   restarts the work instead of continuing it\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport type { InlineAgent } from '../../schemas/subagentTool';\nimport { formatAgentIdentity } from '../agentIdentity';\nimport { writeAtomicJson, writeAtomicJsonAsync } from '../atomicJson';\nimport { type SessionScope, scopeSuspendedDir } from '../sessionPaths';\nimport { parseVersioned } from '../versioned';\n\nconst SUSPENDED_RUN_VERSION = 1;\nconst JSON_SUFFIX = '.json';\n\nexport interface SuspendedRun {\n  version: typeof SUSPENDED_RUN_VERSION;\n  runId: string;\n  agent: string;\n  /** Generated addressable identity, reclaimed by a restore instead of re-minted. */\n  identity?: string;\n  /** True when this run came from a one-shot inline agent definition. */\n  inline?: boolean;\n  runtime: string;\n  task: string;\n  cwd: string;\n  model?: string;\n  /** One-shot agent definition required to reconstruct an inline agent. */\n  inlineAgent?: InlineAgent;\n  context?: 'fresh' | 'fork';\n  /** Last state the run reported before it was stopped. */\n  lastStatus?: string;\n  /**\n   * The child's own transcript.\n   *\n   * This is what makes a restore a continuation: `sdkRunnerEntry.ts` opens it\n   * through `SessionManager.open` when `sdk.sessionFile` is set. Absent for a\n   * run that never persisted one (an external CLI, or a headless child), in\n   * which case the record remains visible but cannot be restored.\n   */\n  sessionFile?: string;\n  suspendedAt: number;\n  /** Why the session went away, for the report a later `session_start` shows. */\n  reason: string;\n}\n\nfunction suspendedPath(scope: SessionScope, runId: string): string {\n  return path.join(scopeSuspendedDir(scope), `${runId}${JSON_SUFFIX}`);\n}\n\nexport function suspendRun(scope: SessionScope, record: Omit<SuspendedRun, 'version'>): void {\n  writeAtomicJson(suspendedPath(scope, record.runId), { version: SUSPENDED_RUN_VERSION, ...record });\n}\n\nexport async function suspendRunAsync(scope: SessionScope, record: Omit<SuspendedRun, 'version'>): Promise<void> {\n  await writeAtomicJsonAsync(suspendedPath(scope, record.runId), { version: SUSPENDED_RUN_VERSION, ...record });\n}\n\nfunction parseSuspendedRun(raw: string): SuspendedRun | undefined {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(raw);\n  } catch {\n    return undefined;\n  }\n  const result = parseVersioned<SuspendedRun>(parsed, [SUSPENDED_RUN_VERSION]);\n  return result.ok && typeof result.value.runId === 'string' ? result.value : undefined;\n}\n\nexport function listSuspendedRuns(scope: SessionScope): SuspendedRun[] {\n  let entries: string[];\n  try {\n    entries = fs.readdirSync(scopeSuspendedDir(scope));\n  } catch {\n    return [];\n  }\n\n  const runs: SuspendedRun[] = [];\n  for (const entry of entries) {\n    if (!entry.endsWith(JSON_SUFFIX)) continue;\n    let run: SuspendedRun | undefined;\n    try {\n      run = parseSuspendedRun(fs.readFileSync(path.join(scopeSuspendedDir(scope), entry), 'utf-8'));\n    } catch {\n      // A record this build cannot read is skipped, not deleted: it may belong\n      // to a newer build that will read it back correctly.\n      continue;\n    }\n    if (run) runs.push(run);\n  }\n  return runs.sort((left, right) => left.suspendedAt - right.suspendedAt);\n}\n\nexport async function listSuspendedRunsAsync(scope: SessionScope): Promise<SuspendedRun[]> {\n  let entries: string[];\n  try {\n    entries = await fs.promises.readdir(scopeSuspendedDir(scope));\n  } catch {\n    return [];\n  }\n\n  const runs: SuspendedRun[] = [];\n  for (const entry of entries) {\n    if (!entry.endsWith(JSON_SUFFIX)) continue;\n    try {\n      const run = parseSuspendedRun(await fs.promises.readFile(path.join(scopeSuspendedDir(scope), entry), 'utf-8'));\n      if (run) runs.push(run);\n    } catch {\n      // A record this build cannot read is skipped, not deleted.\n    }\n  }\n  return runs.sort((left, right) => left.suspendedAt - right.suspendedAt);\n}\n\n/** Drop a record once its run has been restored, or explicitly discarded. */\nexport function clearSuspendedRun(scope: SessionScope, runId: string): void {\n  try {\n    fs.rmSync(suspendedPath(scope, runId), { force: true });\n  } catch {\n    // Best effort: a leftover record shows up again in the next report, which\n    // is a visible annoyance rather than a lost run.\n  }\n}\n\n/** Whether an explicit restore can safely continue this exact run. */\nexport function isSuspendedRunResumable(run: SuspendedRun): boolean {\n  if (run.runtime !== 'pi' || !run.agent.trim() || !run.task.trim() || !run.cwd.trim() || !run.sessionFile) {\n    return false;\n  }\n  try {\n    fs.accessSync(run.sessionFile, fs.constants.R_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function isSuspendedRunResumableAsync(run: SuspendedRun): Promise<boolean> {\n  if (run.runtime !== 'pi' || !run.agent.trim() || !run.task.trim() || !run.cwd.trim() || !run.sessionFile) {\n    return false;\n  }\n  try {\n    await fs.promises.access(run.sessionFile, fs.constants.R_OK);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/** The identity prefix for a suspended line, empty for a record written before identities existed. */\nfunction suspendedLabel(run: SuspendedRun): string {\n  const label = formatAgentIdentity(run.identity, run.inline);\n  return label ? `${label}, ` : '';\n}\n\n/** One line per suspended run, for the report `session_start` prints. */\nexport function formatSuspendedRuns(runs: SuspendedRun[]): string {\n  if (runs.length === 0) return '';\n  const lines = runs.map((run) => {\n    const continues = isSuspendedRunResumable(run) ? 'resumable' : 'not resumable';\n    return `- ${run.runId} (${suspendedLabel(run)}${run.agent}, ${run.runtime}, ${continues}): ${run.task.split('\\n')[0]}`;\n  });\n  const noun = runs.length === 1 ? 'subagent' : 'subagents';\n  return [\n    `${runs.length} suspended ${noun} from this session:`,\n    ...lines,\n    '',\n    'They are stopped. Restore one with subagent {\"action\":\"restore\",\"id\":\"<run-id>\"}, or leave them.',\n  ].join('\\n');\n}\n\nexport async function formatSuspendedRunsAsync(runs: SuspendedRun[]): Promise<string> {\n  if (runs.length === 0) return '';\n  const resumable = await Promise.all(runs.map((run) => isSuspendedRunResumableAsync(run)));\n  const lines = runs.map((run, index) => {\n    const continues = resumable[index] ? 'resumable' : 'not resumable';\n    return `- ${run.runId} (${suspendedLabel(run)}${run.agent}, ${run.runtime}, ${continues}): ${run.task.split('\\n')[0]}`;\n  });\n  const noun = runs.length === 1 ? 'subagent' : 'subagents';\n  return [\n    `${runs.length} suspended ${noun} from this session:`,\n    ...lines,\n    '',\n    'They are stopped. Restore one with subagent {\"action\":\"restore\",\"id\":\"<run-id>\"}, or leave them.',\n  ].join('\\n');\n}\n","import type { TrackedAsyncJob } from '../asyncJobTracker';\nimport type { SessionScope } from '../sessionPaths';\nimport { listSuspendedRuns, listSuspendedRunsAsync, type SuspendedRun, suspendRun } from '../suspendedRuns';\n\nexport interface SuspendScopeOptions {\n  scope: SessionScope;\n  reason: string;\n  jobs: readonly TrackedAsyncJob[];\n  stop: (runId: string, reason: string) => Promise<unknown>;\n  now?: () => number;\n}\n\nexport interface SuspendScopeResult {\n  suspended: string[];\n  unstoppable: string[];\n}\n\nfunction active(job: TrackedAsyncJob): boolean {\n  return job.status === undefined || !new Set(['complete', 'completed', 'failed', 'paused', 'stopped']).has(job.status);\n}\n\nfunction suspendedRecord(job: TrackedAsyncJob, reason: string, suspendedAt: number): Omit<SuspendedRun, 'version'> {\n  return {\n    runId: job.runId,\n    agent: job.agent ?? 'unknown',\n    // Copied explicitly. This function is the only producer of a suspended\n    // record, so a field declared on SuspendedRun but not restated here is\n    // dead on arrival, which is what already happened to inlineAgent and model.\n    ...(job.identity === undefined ? {} : { identity: job.identity }),\n    ...(job.inline === undefined ? {} : { inline: job.inline }),\n    runtime: job.runtime ?? (job.native ? 'pi' : 'external'),\n    task: job.task ?? '',\n    cwd: job.cwd ?? '',\n    ...(job.status === undefined ? {} : { lastStatus: job.status }),\n    ...(job.sessionFile === undefined ? {} : { sessionFile: job.sessionFile }),\n    suspendedAt,\n    reason,\n  };\n}\n\n/** Persist resumable metadata, then stop every live run through its typed owner. */\nexport async function suspendScopeRuns(options: SuspendScopeOptions): Promise<SuspendScopeResult> {\n  const jobs = options.jobs.filter(active);\n  const suspendedAt = options.now?.() ?? Date.now();\n  for (const job of jobs) suspendRun(options.scope, suspendedRecord(job, options.reason, suspendedAt));\n  const outcomes = await Promise.allSettled(jobs.map((job) => options.stop(job.runId, options.reason)));\n  return {\n    suspended: jobs.map((job) => job.runId),\n    unstoppable: jobs.filter((_, index) => outcomes[index]?.status === 'rejected').map((job) => job.runId),\n  };\n}\n\nexport interface OpenScopeResult {\n  pruned: string[];\n  reaped: number;\n  suspended: SuspendedRun[];\n}\n\n/** Durable suspended records are history only. They never seed current live state. */\nexport function openScope(scope: SessionScope): OpenScopeResult {\n  return { pruned: [], reaped: 0, suspended: listSuspendedRuns(scope) };\n}\n\n/** Async form used by session startup. */\nexport async function openScopeAsync(scope: SessionScope): Promise<OpenScopeResult> {\n  return { pruned: [], reaped: 0, suspended: await listSuspendedRunsAsync(scope) };\n}\n","import type { BackgroundProviderWorkItem, DoomBackgroundWorkService } from '@agimon-ai/doompi-core/backgroundWork';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport type { AsyncJobTracker } from '../asyncJobTracker';\n\nconst PROVIDER_NAME = 'team-direct-runs';\n\n/** Publish direct Team runs owned by exactly one Pi session. */\nexport function registerDirectRunBackgroundWork(\n  ctx: Context,\n  service: DoomBackgroundWorkService,\n  sessionId: string,\n  tracker: Pick<AsyncJobTracker, 'listBackgroundWork' | 'subscribe'>,\n): void {\n  const registration = service.register({\n    provider: PROVIDER_NAME,\n    listActiveWork: (): BackgroundProviderWorkItem[] =>\n      tracker.listBackgroundWork(sessionId).map((job) => ({\n        id: job.runId,\n        sessionId,\n        ...(job.agent ? { label: job.agent } : {}),\n        ...(job.status ? { status: job.status } : {}),\n      })),\n  });\n  const unsubscribe = tracker.subscribe(sessionId, () => registration.update());\n  ctx.effect(\n    () => () => {\n      unsubscribe();\n      registration.dispose();\n    },\n    '@agimon-ai/doompi-team/direct-run-background-work',\n  );\n}\n","import { Check } from 'typebox/value';\n\nimport {\n  type DoomSubagentPolicyService,\n  type SubagentPolicy,\n  type SubagentPolicyHandle,\n  SubagentPolicySchema,\n} from '../../schemas/subagentPolicy';\nimport type { SubagentCapabilityPolicyStore } from '../../schemas/team/capabilityCeiling';\n\nfunction assertPolicy(policy: SubagentPolicy): void {\n  if (!Check(SubagentPolicySchema, policy)) throw new TypeError('Invalid subagent policy contribution.');\n}\n\n/** Publishes Team's capability intersection store through a Cordis service. */\nexport function createSubagentPolicyService(store: SubagentCapabilityPolicyStore): DoomSubagentPolicyService {\n  const generation = `doom-subagent-policy:${crypto.randomUUID()}`;\n  const service: DoomSubagentPolicyService = {\n    generation,\n    register(initialPolicy: SubagentPolicy): SubagentPolicyHandle {\n      assertPolicy(initialPolicy);\n      const owner = initialPolicy.owner;\n      const contributionGeneration = `${owner}:${crypto.randomUUID()}`;\n      let policy = initialPolicy;\n      let disposed = false;\n      store.register(policy, contributionGeneration);\n      return Object.freeze({\n        owner,\n        generation: contributionGeneration,\n        update(nextPolicy: SubagentPolicy): void {\n          if (disposed) throw new Error('Cannot update a disposed subagent policy.');\n          assertPolicy(nextPolicy);\n          if (nextPolicy.owner !== owner) throw new Error('Cannot change a subagent policy owner.');\n          policy = nextPolicy;\n          store.update(policy, contributionGeneration);\n        },\n        dispose(): void {\n          if (disposed) return;\n          disposed = true;\n          store.remove(owner, contributionGeneration);\n        },\n      });\n    },\n  };\n  return Object.freeze(service);\n}\n","/**\n * Session-scoped management over in-memory run projections and typed controls.\n * Live status and control never read or write filesystem mailboxes.\n */\n\nimport { randomUUID } from 'node:crypto';\n\nimport type { AsyncRunStatus } from '../asyncExecution';\nimport type { AsyncJobTrackerContract, TrackedAsyncJob, TrackedAsyncJobsContract } from '../asyncJobTracker';\nimport { DoomTeamExpectedError } from '../errors';\nimport type { ExternalProcessIpc } from '../externalProcessIpc';\nimport type { NativeRunCoordinatorContract } from '../nativeRunCoordinator';\nimport type { SessionScope } from '../sessionPaths';\n\nexport interface StatusActionResult {\n  runId: string;\n  runDir: string | undefined;\n  resultPath?: string;\n  claimed: boolean;\n  status: AsyncRunStatus | undefined;\n}\n\nexport interface ListActionResult {\n  runs: TrackedAsyncJob[];\n}\n\nexport interface ControlActionResult {\n  requestId: string;\n}\n\nexport interface SteerActionResult {\n  requestId: string;\n  index: number;\n  state: 'delivered' | 'failed' | 'pending';\n  message: string;\n}\n\nexport interface ManagementActionsContract {\n  bindSessionScope(scope: SessionScope): void;\n  releaseSessionScope?(scope: SessionScope): void;\n  status(id: string): StatusActionResult;\n  statusAsync?(id: string): Promise<StatusActionResult>;\n  list(): ListActionResult;\n  interrupt(id: string, reason?: string): Promise<ControlActionResult>;\n  stop(id: string, reason?: string): Promise<ControlActionResult>;\n  steer(id: string, message: string, targetIndex?: number, signal?: AbortSignal): Promise<SteerActionResult>;\n}\n\nfunction statusProjection(job: TrackedAsyncJob): AsyncRunStatus {\n  const now = job.updatedAt ?? job.startedAt ?? Date.now();\n  return {\n    version: 1,\n    runId: job.runId,\n    agent: job.agent ?? 'unknown',\n    ...(job.task === undefined ? {} : { task: job.task }),\n    cwd: job.cwd ?? '',\n    ...(job.runtime === undefined ? {} : { runtime: job.runtime }),\n    state: job.status as AsyncRunStatus['state'],\n    startedAt: job.startedAt ?? now,\n    lastUpdate: now,\n    ...(job.error === undefined ? {} : { error: job.error }),\n    ...(job.activityState === undefined ? {} : { activityState: job.activityState }),\n    ...(job.attentionReason === undefined ? {} : { attentionReason: job.attentionReason }),\n    ...(job.sessionFile === undefined ? {} : { sessionFile: job.sessionFile }),\n    ...(job.summary === undefined ? {} : { summary: job.summary }),\n    ...(job.tokens === undefined ? {} : { tokens: job.tokens }),\n    ...(job.cost === undefined ? {} : { cost: job.cost }),\n    ...(job.currentTool === undefined ? {} : { currentTool: job.currentTool }),\n    ...(job.toolCount === undefined ? {} : { toolCount: job.toolCount }),\n  };\n}\n\nexport class ManagementActions implements ManagementActionsContract {\n  private scope: SessionScope | undefined;\n\n  constructor(\n    private readonly jobs: AsyncJobTrackerContract,\n    private readonly nativeRuns?: NativeRunCoordinatorContract,\n    private readonly externalProcesses?: ExternalProcessIpc,\n  ) {}\n\n  bindSessionScope(scope: SessionScope): void {\n    if (this.scope && this.scope.scopeKey !== scope.scopeKey) {\n      throw new Error('Team management scope is immutable for the active session runtime.');\n    }\n    this.scope = scope;\n  }\n\n  releaseSessionScope(scope: SessionScope): void {\n    if (this.scope?.scopeKey === scope.scopeKey) this.scope = undefined;\n  }\n\n  private requireScope(): SessionScope {\n    if (!this.scope) throw new Error('Team management requires an admitted session scope.');\n    return this.scope;\n  }\n\n  private sessionJobs(): TrackedAsyncJobsContract {\n    const scope = this.requireScope();\n    return this.jobs.forSession(scope.rootSessionId, scope);\n  }\n\n  private resolveJob(id: string): TrackedAsyncJob | undefined {\n    const runs = this.sessionJobs().list();\n    const exact = runs.find((run) => run.runId === id);\n    if (exact) return exact;\n    const matches = runs.filter((run) => run.runId.startsWith(id));\n    if (matches.length === 1) return matches[0];\n    if (matches.length > 1) {\n      throw new DoomTeamExpectedError(\n        'run_not_found',\n        `Multiple current-session runs match '${id}'.`,\n        false,\n        'Retry with a longer run id.',\n      );\n    }\n    return undefined;\n  }\n\n  private requireActiveJob(id: string): TrackedAsyncJob {\n    const job = this.resolveJob(id);\n    if (!job) {\n      throw new DoomTeamExpectedError(\n        'run_not_found',\n        `No active run matches '${id}'.`,\n        false,\n        'Call subagent({\"action\":\"status\"}) and retry with an exact run id.',\n      );\n    }\n    return job;\n  }\n\n  status(id: string): StatusActionResult {\n    const job = this.resolveJob(id);\n    return {\n      runId: job?.runId ?? id,\n      runDir: undefined,\n      resultPath: undefined,\n      claimed: false,\n      status: job ? statusProjection(job) : undefined,\n    };\n  }\n\n  async statusAsync(id: string): Promise<StatusActionResult> {\n    return this.status(id);\n  }\n\n  list(): ListActionResult {\n    return { runs: this.sessionJobs().list() };\n  }\n\n  async interrupt(id: string, reason?: string): Promise<ControlActionResult> {\n    return this.stopWithCommand(id, 'interrupt', reason);\n  }\n\n  async stop(id: string, reason?: string): Promise<ControlActionResult> {\n    return this.stopWithCommand(id, 'stop', reason);\n  }\n\n  private async stopWithCommand(\n    id: string,\n    command: 'interrupt' | 'stop',\n    reason?: string,\n  ): Promise<ControlActionResult> {\n    const scope = this.requireScope();\n    const job = this.requireActiveJob(id);\n    const requestId = randomUUID();\n    if (job.native) {\n      if (!this.nativeRuns?.get(scope.rootSessionId, job.runId)) {\n        throw new DoomTeamExpectedError(\n          'run_not_found',\n          `Native run '${job.runId}' is no longer active.`,\n          false,\n          'List active runs and retry with a current run id.',\n        );\n      }\n      await this.nativeRuns.stop(scope.rootSessionId, job.runId, reason);\n      return { requestId };\n    }\n    if (!this.externalProcesses?.has(scope, job.runId)) {\n      throw new DoomTeamExpectedError(\n        'run_not_found',\n        `External run '${job.runId}' is no longer active.`,\n        false,\n        'List active runs and retry with a current run id.',\n      );\n    }\n    await this.externalProcesses.control(scope, job.runId, { command, requestId, ...(reason ? { reason } : {}) });\n    return { requestId };\n  }\n\n  async steer(id: string, message: string, targetIndex?: number, signal?: AbortSignal): Promise<SteerActionResult> {\n    const scope = this.requireScope();\n    const job = this.requireActiveJob(id);\n    const requestId = randomUUID();\n    const index = targetIndex ?? 0;\n    if (job.native) {\n      if (!this.nativeRuns?.get(scope.rootSessionId, job.runId)) {\n        throw new DoomTeamExpectedError(\n          'run_not_found',\n          `Native run '${job.runId}' is no longer active.`,\n          false,\n          'List active runs and retry with a current run id.',\n        );\n      }\n      await this.nativeRuns.steer(scope.rootSessionId, job.runId, message, signal);\n      return { requestId, index, state: 'delivered', message: 'Native child accepted the steer request.' };\n    }\n    if (!this.externalProcesses?.has(scope, job.runId)) {\n      throw new DoomTeamExpectedError(\n        'run_not_found',\n        `External run '${job.runId}' is no longer active.`,\n        false,\n        'List active runs and retry with a current run id.',\n      );\n    }\n    const acknowledgement = await this.externalProcesses.control(scope, job.runId, {\n      command: 'steer',\n      requestId,\n      message,\n      targetIndex: index,\n    });\n    if (!acknowledgement) {\n      return { requestId, index, state: 'pending', message: 'No child acknowledgment arrived within 3 seconds.' };\n    }\n    return {\n      requestId,\n      index,\n      state: acknowledgement.state,\n      message: acknowledgement.message,\n    };\n  }\n}\n","import type { DoomMcpResolvedToolSelection, DoomMcpToolResolverService } from '@agimon-ai/doompi-core/mcpToolResolver';\n\nexport type ResolvedMcpDirectToolSelection = DoomMcpResolvedToolSelection;\nexport type McpDirectToolResolver = Pick<DoomMcpToolResolverService, 'resolve'>;\n\n/**\n * Session-owned bridge between Team's launch planner and an optional MCP provider.\n *\n * The stable bridge can be threaded through Team's ordinary object graph while\n * Cordis replaces the live provider binding. Provider removal always narrows to\n * no direct MCP tools, and a stale provider disposer cannot clear its replacement.\n */\nexport class McpDirectToolResolverBinding implements McpDirectToolResolver {\n  private active: DoomMcpToolResolverService | undefined;\n\n  bind(service: DoomMcpToolResolverService): () => void {\n    this.active = service;\n    let bound = true;\n    return () => {\n      if (!bound) return;\n      bound = false;\n      if (this.active === service) this.active = undefined;\n    };\n  }\n\n  resolve(selectors: readonly string[]): readonly DoomMcpResolvedToolSelection[] {\n    if (selectors.length === 0) return [];\n    try {\n      return this.active?.resolve(selectors) ?? [];\n    } catch {\n      // A provider failure cannot widen a child's tool grant. Resolving nothing\n      // is the narrow result and is surfaced later by the child tool diagnostic.\n      return [];\n    }\n  }\n}\n\nexport function resolveMcpDirectToolSelections(\n  mcpDirectTools: readonly string[] | undefined,\n  resolver?: McpDirectToolResolver,\n): ResolvedMcpDirectToolSelection[] {\n  if (!mcpDirectTools?.length || !resolver) return [];\n  try {\n    return [...resolver.resolve(mcpDirectTools)];\n  } catch {\n    return [];\n  }\n}\n\nexport function resolveMcpDirectToolNames(\n  mcpDirectTools: readonly string[] | undefined,\n  resolver?: McpDirectToolResolver,\n): string[] {\n  return resolveMcpDirectToolSelections(mcpDirectTools, resolver).map((selection) => selection.name);\n}\n","import type {\n  DoomChildSessionEvent,\n  DoomChildSessionHandle,\n  DoomChildSessionRequest,\n  DoomChildSessionServiceProvider,\n} from '@agimon-ai/doompi-core/childSession';\n\nimport type { AsyncJobTracker, NativeAsyncJobProjection } from '../asyncJobTracker';\nimport type { NativeRunProjectionSink } from '../nativeRunProjection';\nimport type { CompletionNotifierContract } from '../notify';\nimport type { SessionScope } from '../sessionPaths';\n\n/** Team-owned run identity, carried beside the shared child request rather than inside it. */\nexport interface NativeRunIdentity {\n  readonly identity: string;\n  readonly inline: boolean;\n}\n\nexport interface NativeRunCoordinatorContract {\n  start(\n    sessionId: string,\n    request: DoomChildSessionRequest,\n    identity?: NativeRunIdentity,\n  ): Promise<DoomChildSessionHandle>;\n  get(sessionId: string, runId: string): DoomChildSessionHandle | undefined;\n  status(sessionId: string, runId: string): NativeAsyncJobProjection | undefined;\n  steer(sessionId: string, runId: string, message: string, signal?: AbortSignal): Promise<void>;\n  stop(sessionId: string, runId: string, reason?: string): Promise<void>;\n  close(): Promise<void>;\n}\n\ninterface NativeRunEntry {\n  readonly sessionId: string;\n  readonly scope: SessionScope;\n  readonly request: DoomChildSessionRequest;\n  readonly identity?: NativeRunIdentity;\n  readonly handle: DoomChildSessionHandle;\n  unsubscribe?: () => void;\n  startedAt?: number;\n  terminal: boolean;\n}\n\nfunction terminalState(event: DoomChildSessionEvent): 'completed' | 'failed' | 'stopped' | undefined {\n  return event.state === 'completed' || event.state === 'failed' || event.state === 'stopped' ? event.state : undefined;\n}\n\nfunction entryKey(sessionId: string, runId: string): string {\n  return JSON.stringify([sessionId, runId]);\n}\n\nexport class NativeRunCoordinator implements NativeRunCoordinatorContract {\n  private readonly entries = new Map<string, NativeRunEntry>();\n  private closed = false;\n  private closing: Promise<void> | undefined;\n\n  constructor(\n    private readonly childSessions: DoomChildSessionServiceProvider | undefined,\n    private readonly tracker: AsyncJobTracker,\n    private readonly notifier?: CompletionNotifierContract,\n    private readonly projection?: NativeRunProjectionSink,\n  ) {}\n\n  async start(\n    sessionId: string,\n    request: DoomChildSessionRequest,\n    identity?: NativeRunIdentity,\n  ): Promise<DoomChildSessionHandle> {\n    if (this.closed) throw new Error('The native Team run coordinator is closed.');\n    if (!sessionId.trim()) throw new Error('Native child runs require a session identity.');\n    const service = this.childSessions?.get();\n    if (!service) throw new Error('The in-process Pi child-session service is unavailable.');\n    const handle = await service.start(request);\n    if (this.closed) {\n      await handle.dispose();\n      throw new Error('The native Team run coordinator closed during child startup.');\n    }\n    const entry: NativeRunEntry = {\n      sessionId,\n      scope: request.scope,\n      request,\n      ...(identity ? { identity } : {}),\n      handle,\n      terminal: false,\n    };\n    const key = entryKey(sessionId, request.runId);\n    this.entries.set(key, entry);\n    try {\n      const unsubscribe = handle.subscribe((event) => this.onEvent(entry, event));\n      if (entry.terminal) unsubscribe();\n      else entry.unsubscribe = unsubscribe;\n      return handle;\n    } catch (error) {\n      this.entries.delete(key);\n      await handle.dispose().catch(() => undefined);\n      throw error;\n    }\n  }\n\n  get(sessionId: string, runId: string): DoomChildSessionHandle | undefined {\n    return this.entries.get(entryKey(sessionId, runId))?.handle;\n  }\n\n  status(sessionId: string, runId: string): NativeAsyncJobProjection | undefined {\n    return this.tracker.getNative(sessionId, runId);\n  }\n\n  async steer(sessionId: string, runId: string, message: string, signal?: AbortSignal): Promise<void> {\n    const handle = this.get(sessionId, runId);\n    if (!handle) throw new Error(`No active native run matches '${runId}'.`);\n    await handle.steer(message, signal);\n  }\n\n  async stop(sessionId: string, runId: string, reason?: string): Promise<void> {\n    const handle = this.get(sessionId, runId);\n    if (!handle) throw new Error(`No active native run matches '${runId}'.`);\n    await handle.stop(reason);\n  }\n\n  async close(): Promise<void> {\n    this.closed = true;\n    this.closing ??= (async () => {\n      const active = [...this.entries.values()];\n      const outcomes = await Promise.allSettled(active.map((entry) => entry.handle.dispose()));\n      for (const entry of active) {\n        entry.unsubscribe?.();\n        this.entries.delete(entryKey(entry.sessionId, entry.request.runId));\n      }\n      const failures = outcomes\n        .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n        .map((outcome) => outcome.reason);\n      if (failures.length) throw new AggregateError(failures, 'Native Team run shutdown failed.');\n    })();\n    return this.closing;\n  }\n\n  private onEvent(entry: NativeRunEntry, event: DoomChildSessionEvent): void {\n    entry.startedAt ??= event.timestamp;\n    const status = terminalState(event);\n    const projection: NativeAsyncJobProjection = {\n      runId: event.runId,\n      agent: entry.request.agent,\n      // Carried on the projection, not merged in by the tracker, because\n      // `upsertNative` replaces the record wholesale on every event.\n      ...(entry.identity ? { identity: entry.identity.identity, inline: entry.identity.inline } : {}),\n      task: entry.request.task,\n      cwd: entry.request.cwd,\n      runtime: 'pi',\n      status: event.state === 'starting' ? 'queued' : event.state === 'running' ? 'running' : event.state,\n      startedAt: entry.startedAt,\n      updatedAt: event.timestamp,\n      ...(event.cost === undefined ? {} : { cost: event.cost }),\n      ...(event.sessionFile ? { sessionFile: event.sessionFile } : {}),\n      ...(event.message\n        ? { error: status === 'failed' || status === 'stopped' ? event.message : undefined, summary: event.message }\n        : {}),\n    };\n    this.tracker.upsertNative(entry.sessionId, entry.scope, projection);\n    this.projection?.publish(entry.sessionId, projection);\n    if (!status || entry.terminal) return;\n    entry.terminal = true;\n    entry.unsubscribe?.();\n    this.entries.delete(entryKey(entry.sessionId, entry.request.runId));\n    const result = {\n      runId: entry.request.runId,\n      agent: entry.request.agent,\n      // The completion message is the only thing the model sees when a run\n      // ends, so it names the agent the same way every other surface does.\n      ...(entry.identity ? { identity: entry.identity.identity, inline: entry.identity.inline } : {}),\n      task: entry.request.task,\n      cwd: entry.request.cwd,\n      runtime: 'pi',\n      state: status,\n      success: status === 'completed',\n      summary:\n        event.message ?? (status === 'completed' ? 'Native child run completed.' : `Native child run ${status}.`),\n      durationMs: Math.max(\n        0,\n        event.timestamp - (this.tracker.getNative(entry.sessionId, entry.request.runId)?.startedAt ?? event.timestamp),\n      ),\n      sessionId: entry.sessionId,\n      ...(event.sessionFile ? { sessionFile: event.sessionFile } : {}),\n    };\n    if (this.notifier) {\n      void this.notifier\n        .deliver(result)\n        .then((delivered) => {\n          if (delivered) this.tracker.acknowledgeHandoff(entry.sessionId, entry.request.runId);\n        })\n        .catch(() => undefined);\n    }\n  }\n}\n","/**\n * BoundedKeySet - a \"have I already seen this?\" set that cannot grow forever.\n *\n * DESIGN PATTERNS:\n * - Insertion-ordered eviction: the oldest key goes when the cap is reached\n *\n * WHY THIS EXISTS:\n * The predecessor package tracked delivered messages, emitted control events and\n * seen request files in plain Sets that were never pruned, so a long session\n * accumulated one entry per event for its whole lifetime. Dedupe only needs a\n * recent window: once an event is old enough to be evicted, the file or record\n * that would have re-triggered it is long gone.\n *\n * AVOID:\n * - Sizing the cap below the number of events that can be in flight at once,\n *   which would let a duplicate slip through\n */\n\nconst MINIMUM_CAPACITY = 1;\n\nexport class BoundedKeySet<K> {\n  private readonly keys = new Set<K>();\n  private readonly capacity: number;\n\n  constructor(capacity: number) {\n    if (!Number.isInteger(capacity) || capacity < MINIMUM_CAPACITY) {\n      throw new Error(`BoundedKeySet capacity must be an integer of at least ${MINIMUM_CAPACITY}.`);\n    }\n    this.capacity = capacity;\n  }\n\n  get size(): number {\n    return this.keys.size;\n  }\n\n  has(key: K): boolean {\n    return this.keys.has(key);\n  }\n\n  /** Record a key. Returns true when it was newly added. */\n  add(key: K): boolean {\n    if (this.keys.has(key)) return false;\n    this.keys.add(key);\n    while (this.keys.size > this.capacity) {\n      const oldest = this.keys.values().next();\n      if (oldest.done === true) break;\n      this.keys.delete(oldest.value);\n    }\n    return true;\n  }\n\n  delete(key: K): boolean {\n    return this.keys.delete(key);\n  }\n\n  clear(): void {\n    this.keys.clear();\n  }\n}\n","/**\n * In-process peer messaging for one root session's native Team children.\n *\n * Native Pi children share the host's child-session service, so intercom state\n * lives here, in the owning Team channel. External runtimes do not join this\n * channel: they are explicit one-shot subprocesses with no filesystem fallback.\n */\n\nimport { createHash, randomBytes } from 'node:crypto';\n\nimport type {\n  DoomChildSessionIntercom,\n  DoomChildSessionRuntime,\n  DoomChildSessionTool,\n  DoomChildSessionToolResult,\n} from '@agimon-ai/doompi-core/childSession';\nimport type { AgentToolResult } from '@earendil-works/pi-agent-core';\nimport type { ExtensionAPI } from '@earendil-works/pi-coding-agent';\nimport type { TSchema } from 'typebox';\n\nimport { BoundedKeySet } from '../boundedKeySet';\nimport { DoomTeamExpectedError, invalidRequest } from '../errors';\n\n/** Wire literal. The model calls the tool by this name, so it is not renamed. */\nexport const NATIVE_TEAM_TOOL_NAME = 'intercom';\n\nexport const TEAM_MESSAGE_CUSTOM_TYPE = 'intercom_message';\nconst MAIN_MEMBER_ID = 'main';\nconst RESERVED_NAME_FALLBACK = 'main-agent';\nconst FALLBACK_MEMBER_NAME = 'agent';\nconst MAX_MEMBER_NAME_LENGTH = 48;\nconst FANOUT_SUFFIX_SEPARATOR = '-';\nconst MAX_MESSAGE_BYTES = 64 * 1024;\nconst DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;\nconst MAX_IDEMPOTENCY_KEYS = 1024;\nconst HASH_ALGORITHM = 'sha256';\nconst TOKEN_BYTES = 32;\nconst TEAM_ID_PREFIX = 'session-';\nconst TEAM_ROOT_VERSION = 1;\n\nconst TEAM_ACTIONS = ['members', 'send', 'ask', 'reply', 'pending'] as const;\nconst UNSAFE_NAME_CHARS = /[^a-z0-9._-]+/g;\nconst SURROUNDING_SEPARATORS = /^[-.]+|[-.]+$/g;\n\nexport type TeamMemberRole = 'main' | 'subagent';\n\nexport interface TeamRootContext {\n  version: typeof TEAM_ROOT_VERSION;\n  teamId: string;\n  rootSessionId: string;\n  mainMemberId: string;\n}\n\nexport interface TeamTaskMetadata {\n  id: string;\n  subject: string;\n}\n\nexport interface TeamMemberContext extends TeamRootContext {\n  memberId: string;\n  /** Kept in the direct context for capability identity, never forwarded through env or files. */\n  token: string;\n  role: TeamMemberRole;\n  agent?: string;\n  inline?: boolean;\n  runId?: string;\n  childIndex?: number;\n  parentMemberId?: string;\n  task?: TeamTaskMetadata;\n}\n\nexport interface NativeTeamMemberSnapshot {\n  name: string;\n  role: TeamMemberRole;\n  agent?: string;\n  /** True when this run came from a one-shot inline agent definition. */\n  inline?: boolean;\n  runId?: string;\n  task?: TeamTaskMetadata;\n}\n\nexport interface NativeTeamSnapshot {\n  members: NativeTeamMemberSnapshot[];\n}\n\ninterface TeamToolParams {\n  action: (typeof TEAM_ACTIONS)[number];\n  to?: string;\n  message?: string;\n  requestId?: string;\n  timeoutMs?: number;\n}\n\nexport const TeamToolParamsSchema = {\n  oneOf: [\n    ...(['members', 'pending'] as const).map((action) => ({\n      type: 'object',\n      properties: { action: { const: action } },\n      required: ['action'],\n      additionalProperties: false,\n    })),\n    {\n      type: 'object',\n      properties: { action: { const: 'send' }, to: { type: 'string' }, message: { type: 'string' } },\n      required: ['action', 'to', 'message'],\n      additionalProperties: false,\n    },\n    {\n      type: 'object',\n      properties: {\n        action: { const: 'ask' },\n        to: { type: 'string' },\n        message: { type: 'string' },\n        timeoutMs: { type: 'integer', minimum: 1 },\n      },\n      required: ['action', 'to', 'message'],\n      additionalProperties: false,\n    },\n    {\n      type: 'object',\n      properties: { action: { const: 'reply' }, requestId: { type: 'string' }, message: { type: 'string' } },\n      required: ['action', 'requestId', 'message'],\n      additionalProperties: false,\n    },\n  ],\n} as unknown as TSchema;\n\nfunction isInteger(value: unknown): value is number {\n  return typeof value === 'number' && Number.isInteger(value);\n}\n\nfunction isOptionalString(value: unknown): value is string | undefined {\n  return value === undefined || typeof value === 'string';\n}\n\nfunction withinBytes(value: string, limit: number): boolean {\n  return Buffer.byteLength(value, 'utf8') <= limit;\n}\n\nfunction hash(value: string): string {\n  return createHash(HASH_ALGORITHM).update(value).digest('hex');\n}\n\nfunction newToken(): string {\n  return randomBytes(TOKEN_BYTES).toString('base64url');\n}\n\nfunction teamIdForSession(rootSessionId: string): string {\n  return `${TEAM_ID_PREFIX}${hash(rootSessionId).slice(0, 32)}`;\n}\n\nfunction operationMessageId(memberId: string, operationId: string): string {\n  return hash(`${memberId}:${operationId}`);\n}\n\nfunction guardReservedName(name: string, explicit: boolean): string {\n  if (name !== MAIN_MEMBER_ID) return name;\n  if (explicit) throw new Error(`Native team member name '${MAIN_MEMBER_ID}' is reserved for the root session.`);\n  return RESERVED_NAME_FALLBACK;\n}\n\nexport function normalizeTeamMemberName(raw: string): string {\n  const normalized = raw\n    .trim()\n    .toLowerCase()\n    .replace(UNSAFE_NAME_CHARS, FANOUT_SUFFIX_SEPARATOR)\n    .replace(SURROUNDING_SEPARATORS, '')\n    .slice(0, MAX_MEMBER_NAME_LENGTH)\n    .replace(SURROUNDING_SEPARATORS, '');\n  return normalized || FALLBACK_MEMBER_NAME;\n}\n\n/**\n * The member id, which is also the address a peer sends to.\n *\n * A generated identity (`alan-reviewer-3`) already survives\n * `normalizeTeamMemberName` unchanged and is unique per session, so it is used\n * verbatim. The older `<agent>-<runId prefix>` shape remains the fallback for a\n * run whose identity could not be claimed, so a spawn never fails for want of\n * a name.\n */\nfunction directMemberName(input: NativeTeamChildIntercomInput): string {\n  if (input.identity?.trim()) return guardReservedName(normalizeTeamMemberName(input.identity), false);\n  const base = guardReservedName(normalizeTeamMemberName(input.agent), false);\n  const suffix = normalizeTeamMemberName(input.runId).slice(0, 8);\n  const room = MAX_MEMBER_NAME_LENGTH - suffix.length - FANOUT_SUFFIX_SEPARATOR.length;\n  return `${base.slice(0, room).replace(SURROUNDING_SEPARATORS, '') || FALLBACK_MEMBER_NAME}-${suffix}`;\n}\n\nfunction validateTask(task: TeamTaskMetadata | undefined): TeamTaskMetadata | undefined {\n  if (!task) return undefined;\n  const id = task.id.trim();\n  const subject = task.subject.trim();\n  if (!id || !subject) throw new Error('Native team task metadata requires an id and subject.');\n  return { id, subject };\n}\n\nfunction parseTeamToolParams(raw: unknown): TeamToolParams {\n  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n    throw invalidRequest('Intercom params must be an object.', 'Use one documented intercom action shape.');\n  }\n  const params = raw as Record<string, unknown>;\n  const action = TEAM_ACTIONS.find((candidate) => candidate === params.action);\n  if (!action) {\n    throw new DoomTeamExpectedError(\n      'unsupported_operation',\n      `Unsupported intercom action: ${String(params.action)}.`,\n      false,\n      'Use members, send, ask, pending, or reply.',\n    );\n  }\n  if (!isOptionalString(params.to) || !isOptionalString(params.message) || !isOptionalString(params.requestId)) {\n    throw invalidRequest(\n      'Intercom to, message and requestId values must be strings.',\n      'Correct the action fields and retry.',\n    );\n  }\n  if (params.timeoutMs !== undefined && (!isInteger(params.timeoutMs) || params.timeoutMs < 1)) {\n    throw invalidRequest('Intercom timeoutMs must be a positive integer.', 'Correct timeoutMs and retry.');\n  }\n  const allowed = new Set(\n    action === 'members' || action === 'pending'\n      ? ['action']\n      : action === 'reply'\n        ? ['action', 'requestId', 'message']\n        : action === 'ask'\n          ? ['action', 'to', 'message', 'timeoutMs']\n          : ['action', 'to', 'message'],\n  );\n  const unknown = Object.keys(params).filter((field) => !allowed.has(field));\n  if (unknown.length) {\n    throw invalidRequest(\n      `Intercom action '${action}' does not accept: ${unknown.join(', ')}.`,\n      'Remove unknown fields and retry.',\n    );\n  }\n  return {\n    action,\n    ...(params.to !== undefined ? { to: params.to } : {}),\n    ...(params.message !== undefined ? { message: params.message } : {}),\n    ...(params.requestId !== undefined ? { requestId: params.requestId } : {}),\n    ...(params.timeoutMs !== undefined ? { timeoutMs: params.timeoutMs } : {}),\n  };\n}\n\nfunction validateMessage(message: string | undefined): string {\n  const normalized = message?.trim();\n  if (!normalized) {\n    throw invalidRequest('message is required for intercom communication.', 'Provide a nonblank message.');\n  }\n  if (!withinBytes(normalized, MAX_MESSAGE_BYTES)) {\n    throw invalidRequest('Intercom message exceeds 64 KiB.', 'Shorten the message and retry.');\n  }\n  return normalized;\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal?.aborted) {\n      reject(new Error('Native team request cancelled.'));\n      return;\n    }\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const cleanup = (): void => {\n      if (timer) clearTimeout(timer);\n      signal?.removeEventListener('abort', onAbort);\n    };\n    const onAbort = (): void => {\n      cleanup();\n      reject(new Error('Native team request cancelled.'));\n    };\n    timer = setTimeout(() => {\n      cleanup();\n      resolve();\n    }, ms);\n    signal?.addEventListener('abort', onAbort, { once: true });\n  });\n}\n\nfunction toChildSessionToolResult(result: AgentToolResult<Record<string, unknown>>): DoomChildSessionToolResult {\n  return {\n    content: result.content.filter((item): item is { type: 'text'; text: string } => item.type === 'text'),\n    details: result.details,\n  };\n}\n\nfunction publicMember(context: TeamMemberContext): NativeTeamMemberSnapshot {\n  return {\n    name: context.memberId,\n    role: context.role,\n    ...(context.agent ? { agent: context.agent } : {}),\n    ...(context.inline ? { inline: true } : {}),\n    ...(context.runId ? { runId: context.runId } : {}),\n    ...(context.task ? { task: context.task } : {}),\n  };\n}\n\nexport interface IntercomMessageDetails {\n  readonly kind: 'send' | 'ask';\n  readonly from: NativeTeamMemberSnapshot;\n  readonly message: string;\n  readonly requestId: string;\n}\n\ninterface DirectMessage {\n  readonly content: string;\n  readonly details: IntercomMessageDetails;\n}\n\nfunction formatDirectMessage(\n  from: TeamMemberContext,\n  kind: IntercomMessageDetails['kind'],\n  requestId: string,\n  message: string,\n): DirectMessage {\n  return {\n    content: `${kind === 'ask' ? 'Question' : 'Message'} from ${from.memberId}${from.inline ? ' (inline)' : ''}${from.agent ? ` [${from.agent}]` : ''}.\\n\\n${message}${kind === 'ask' ? `\\n\\nReply with ${NATIVE_TEAM_TOOL_NAME}({ action: \"reply\", requestId: \"${requestId}\", message: \"...\" }).` : ''}`,\n    details: { kind, from: publicMember(from), message, requestId },\n  };\n}\n\ninterface DirectMember {\n  readonly context: TeamMemberContext;\n  deliver?: (message: DirectMessage) => Promise<void>;\n}\n\ninterface DirectAsk {\n  readonly id: string;\n  readonly fromMemberId: string;\n  readonly toMemberId: string;\n  readonly createdAt: number;\n  readonly promise: Promise<string>;\n  readonly resolve: (message: string) => void;\n  readonly reject: (error: unknown) => void;\n}\n\nexport interface NativeTeamChildIntercomInput {\n  readonly rootSessionId: string;\n  readonly agent: string;\n  /** Generated addressable identity. Absent only when its claim could not be written. */\n  readonly identity?: string;\n  readonly inline?: boolean;\n  readonly runId: string;\n  readonly childIndex?: number;\n  readonly task?: TeamTaskMetadata;\n}\n\nclass NativeTeamDirectChannel {\n  private readonly members = new Map<string, DirectMember>();\n  private readonly asks = new Map<string, DirectAsk>();\n  private readonly delivered = new BoundedKeySet<string>(MAX_IDEMPOTENCY_KEYS);\n\n  private disposed = false;\n\n  constructor(private readonly root: TeamRootContext) {}\n\n  bindMain(context: TeamMemberContext, transport: NativeTeamTransport): void {\n    this.members.set(context.memberId, {\n      context,\n      deliver: async (message) => {\n        transport.sendMessage(\n          {\n            customType: TEAM_MESSAGE_CUSTOM_TYPE,\n            content: message.content,\n            display: true,\n            details: message.details,\n          },\n          { triggerTurn: true, deliverAs: 'steer' },\n        );\n      },\n    });\n  }\n\n  bindChild(input: NativeTeamChildIntercomInput): DoomChildSessionIntercom | undefined {\n    if (input.rootSessionId !== this.root.rootSessionId || this.disposed) return undefined;\n    const memberId = directMemberName(input);\n    const context: TeamMemberContext = {\n      ...this.root,\n      memberId,\n      token: newToken(),\n      role: 'subagent',\n      agent: input.agent,\n      ...(input.inline ? { inline: true } : {}),\n      runId: input.runId,\n      ...(input.childIndex === undefined ? {} : { childIndex: input.childIndex }),\n      ...(input.task === undefined ? {} : { task: validateTask(input.task) }),\n    };\n    if (this.members.has(memberId)) throw new Error(`Native team member '${memberId}' already exists.`);\n    this.members.set(memberId, { context });\n    let disposed = false;\n    const dispose = (): void => {\n      if (disposed) return;\n      disposed = true;\n      this.disposeMember(memberId);\n    };\n    return {\n      bindRuntime: (runtime: DoomChildSessionRuntime): DoomChildSessionTool => {\n        const member = this.members.get(memberId);\n        if (!member || disposed) throw new Error(`Native team member '${memberId}' is no longer active.`);\n        member.deliver = (message) => runtime.steer(message.content);\n        return {\n          name: NATIVE_TEAM_TOOL_NAME,\n          description: 'Communicate with active native agents in this root session.',\n          parameters: TeamToolParamsSchema,\n          execute: async (operationId, rawParams, signal, onUpdate) => {\n            const result = await this.execute(\n              memberId,\n              operationId,\n              rawParams,\n              signal,\n              onUpdate && ((update) => onUpdate(toChildSessionToolResult(update))),\n            );\n            return toChildSessionToolResult(result);\n          },\n        };\n      },\n      dispose,\n    };\n  }\n\n  disposeMember(memberId: string): void {\n    this.members.delete(memberId);\n    for (const [id, ask] of this.asks) {\n      if (ask.fromMemberId === memberId || ask.toMemberId === memberId) {\n        ask.reject(new Error(`Native team member '${memberId}' became unreachable before replying.`));\n        this.asks.delete(id);\n      }\n    }\n  }\n\n  dispose(): void {\n    this.disposed = true;\n    for (const ask of this.asks.values()) ask.reject(new Error('Native team channel is no longer active.'));\n    this.asks.clear();\n    this.members.clear();\n    this.delivered.clear();\n  }\n\n  snapshots(): NativeTeamMemberSnapshot[] {\n    return [...this.members.values()].map((member) => publicMember(member.context));\n  }\n\n  hasMember(query: string | undefined): boolean {\n    return this.findMember(query) !== undefined;\n  }\n\n  hasAsk(requestId: string | undefined): boolean {\n    return requestId !== undefined && this.asks.has(requestId);\n  }\n\n  pending(memberId: string): Array<{ id: string; fromMemberId: string; createdAt: number }> {\n    return [...this.asks.values()]\n      .filter((ask) => ask.toMemberId === memberId)\n      .map(({ id, fromMemberId, createdAt }) => ({ id, fromMemberId, createdAt }))\n      .sort((left, right) => left.createdAt - right.createdAt || left.id.localeCompare(right.id));\n  }\n\n  async execute(\n    memberId: string,\n    operationId: string,\n    rawParams: unknown,\n    signal?: AbortSignal,\n    onUpdate?: (result: AgentToolResult<Record<string, unknown>>) => void,\n  ): Promise<AgentToolResult<Record<string, unknown>>> {\n    const params = parseTeamToolParams(rawParams);\n    const member = this.members.get(memberId);\n    if (!member) throw new Error('This native team member is no longer active.');\n    if (params.action === 'members') {\n      const snapshots = this.snapshots();\n      return {\n        content: [\n          {\n            type: 'text',\n            text: snapshots.length\n              ? snapshots\n                  .map((entry) => `- ${entry.name}${entry.inline ? ' (inline)' : ''}: ${entry.agent ?? entry.name}`)\n                  .join('\\n')\n              : 'No active members.',\n          },\n        ],\n        details: { members: snapshots },\n      };\n    }\n    if (params.action === 'pending') {\n      const asks = this.pending(memberId);\n      return {\n        content: [\n          {\n            type: 'text',\n            text: asks.length\n              ? asks\n                  .map(\n                    (ask) =>\n                      `- ${ask.id}: from ${ask.fromMemberId}. Reply with ${NATIVE_TEAM_TOOL_NAME}({ action: \"reply\", requestId: \"${ask.id}\", message: \"...\" }).`,\n                  )\n                  .join('\\n')\n              : 'No pending native team asks.',\n          },\n        ],\n        details: { pending: asks.map((ask) => ({ id: ask.id, from: ask.fromMemberId })) },\n      };\n    }\n\n    const message = validateMessage(params.message);\n    if (params.action === 'reply') {\n      const request = this.asks.get(params.requestId ?? '');\n      if (!request || request.toMemberId !== memberId) {\n        throw new DoomTeamExpectedError(\n          'recipient_not_found',\n          `No pending intercom ask matches requestId '${params.requestId}'.`,\n          false,\n          'Call intercom({\"action\":\"pending\"}) and retry with an exact requestId.',\n        );\n      }\n      request.resolve(message);\n      this.asks.delete(request.id);\n      return {\n        content: [{ type: 'text', text: `Replied to native team request ${request.id}.` }],\n        details: { requestId: request.id, to: request.fromMemberId },\n      };\n    }\n\n    const target = this.findMember(params.to);\n    if (!target) {\n      throw new DoomTeamExpectedError(\n        'recipient_not_found',\n        `Active intercom member '${params.to}' was not found.`,\n        true,\n        'Call intercom({\"action\":\"members\"}) and retry with an active member id.',\n      );\n    }\n    const messageId = operationMessageId(memberId, operationId);\n    if (params.action === 'send') {\n      if (this.delivered.has(messageId)) {\n        return {\n          content: [{ type: 'text', text: `Message ${messageId} delivered to ${target.context.memberId}.` }],\n          details: { state: 'delivered', delivered: true, messageId, to: target.context.memberId },\n        };\n      }\n      await this.deliver(target, formatDirectMessage(member.context, 'send', messageId, message));\n      this.delivered.add(messageId);\n      return {\n        content: [{ type: 'text', text: `Message ${messageId} delivered to ${target.context.memberId}.` }],\n        details: { state: 'delivered', delivered: true, messageId, to: target.context.memberId },\n      };\n    }\n\n    let ask = this.asks.get(messageId);\n    let delivered = false;\n    if (!ask) {\n      ask = this.createAsk(memberId, target.context.memberId, messageId);\n      delivered = true;\n    }\n    onUpdate?.({\n      content: [{ type: 'text', text: `Waiting for ${target.context.memberId} to reply...` }],\n      details: { action: 'ask', to: target.context.memberId, partial: true },\n    });\n    try {\n      if (delivered) {\n        await this.deliver(target, formatDirectMessage(member.context, 'ask', ask.id, message));\n        signal?.throwIfAborted();\n      }\n      const reply = await Promise.race([\n        ask.promise,\n        delay(params.timeoutMs ?? DEFAULT_ASK_TIMEOUT_MS, signal).then(() => {\n          throw new DoomTeamExpectedError(\n            'reply_timeout',\n            `Timed out waiting for intercom member '${target.context.memberId}' to reply.`,\n            true,\n            'Check member status before deciding whether to ask again.',\n          );\n        }),\n      ]);\n      return {\n        content: [{ type: 'text', text: `Reply from ${target.context.memberId}:\\n${reply}` }],\n        details: { requestId: ask.id, from: target.context.memberId, reply },\n      };\n    } finally {\n      this.asks.delete(ask.id);\n    }\n  }\n\n  private createAsk(fromMemberId: string, toMemberId: string, id: string): DirectAsk {\n    let resolve!: (value: string) => void;\n    let reject!: (error: unknown) => void;\n    const promise = new Promise<string>((next, fail) => {\n      resolve = next;\n      reject = fail;\n    });\n    void promise.catch(() => undefined);\n    const ask: DirectAsk = { id, fromMemberId, toMemberId, createdAt: Date.now(), promise, resolve, reject };\n    this.asks.set(id, ask);\n    return ask;\n  }\n\n  private findMember(query: string | undefined): DirectMember | undefined {\n    if (!query) return undefined;\n    const lowered = query.toLowerCase();\n    const normalized = normalizeTeamMemberName(query);\n    return [...this.members.values()].find(\n      (member) =>\n        member.context.memberId === query ||\n        member.context.memberId === normalized ||\n        member.context.agent?.toLowerCase() === lowered ||\n        member.context.runId?.toLowerCase() === lowered,\n    );\n  }\n\n  private async deliver(target: DirectMember, message: DirectMessage): Promise<void> {\n    if (!target.deliver) {\n      throw new DoomTeamExpectedError(\n        'communication_unavailable',\n        `Intercom member '${target.context.memberId}' is not ready.`,\n        true,\n        'Retry after the child session starts.',\n      );\n    }\n    await target.deliver(message);\n  }\n}\n\nexport interface NativeTeamTransport {\n  sendMessage: ExtensionAPI['sendMessage'];\n  sendUserMessage: ExtensionAPI['sendUserMessage'];\n}\n\nexport interface NativeTeamRuntime {\n  bindMainSession(rootSessionId: string): TeamMemberContext;\n  current(): TeamMemberContext | undefined;\n  snapshot(): NativeTeamSnapshot;\n  execute(\n    operationId: string,\n    rawParams: unknown,\n    signal?: AbortSignal,\n    onUpdate?: (result: AgentToolResult<Record<string, unknown>>) => void,\n  ): Promise<AgentToolResult<Record<string, unknown>>>;\n  undeliverable(): readonly never[];\n  dispose(): void;\n}\n\nclass TeamChannelRuntime implements NativeTeamRuntime {\n  private context: TeamMemberContext | undefined;\n  private directChannel: NativeTeamDirectChannel | undefined;\n\n  constructor(\n    private readonly transport: NativeTeamTransport,\n    private readonly directChannelForRoot: (rootSessionId: string) => NativeTeamDirectChannel,\n  ) {}\n\n  current(): TeamMemberContext | undefined {\n    return this.context;\n  }\n\n  snapshot(): NativeTeamSnapshot {\n    return { members: this.directChannel?.snapshots() ?? [] };\n  }\n\n  undeliverable(): readonly never[] {\n    return [];\n  }\n\n  execute(\n    operationId: string,\n    rawParams: unknown,\n    signal?: AbortSignal,\n    onUpdate?: (result: AgentToolResult<Record<string, unknown>>) => void,\n  ): Promise<AgentToolResult<Record<string, unknown>>> {\n    const context = this.context;\n    if (!context || !this.directChannel) {\n      throw new DoomTeamExpectedError(\n        'communication_unavailable',\n        'Intercom is not active for this session.',\n        true,\n        'Wait for session startup or reload Doom Team.',\n      );\n    }\n    return this.directChannel.execute(context.memberId, operationId, rawParams, signal, onUpdate);\n  }\n\n  bindMainSession(rootSessionId: string): TeamMemberContext {\n    const root = ensureNativeTeamRoot(rootSessionId);\n    this.directChannel = this.directChannelForRoot(root.rootSessionId);\n    this.context = {\n      ...root,\n      memberId: root.mainMemberId,\n      token: newToken(),\n      role: 'main',\n    };\n    this.directChannel.bindMain(this.context, this.transport);\n    return this.context;\n  }\n\n  dispose(): void {\n    this.directChannel?.dispose();\n    this.directChannel = undefined;\n    this.context = undefined;\n  }\n}\n\nexport type NativeTeamChannelContract = {\n  createRuntime(pi: ExtensionAPI): NativeTeamRuntime;\n  createHeadlessRuntime(transport: NativeTeamTransport): NativeTeamRuntime;\n  createNativeChildIntercom(input: NativeTeamChildIntercomInput): DoomChildSessionIntercom | undefined;\n};\n\nexport function ensureNativeTeamRoot(rootSessionId: string): TeamRootContext {\n  const normalizedSessionId = rootSessionId.trim();\n  if (!normalizedSessionId) throw new Error('A root session id is required for native team communication.');\n  return {\n    version: TEAM_ROOT_VERSION,\n    teamId: teamIdForSession(normalizedSessionId),\n    rootSessionId: normalizedSessionId,\n    mainMemberId: MAIN_MEMBER_ID,\n  };\n}\n\nexport class NativeTeamChannelService implements NativeTeamChannelContract {\n  private readonly runtimes = new WeakMap<ExtensionAPI, NativeTeamRuntime>();\n  private readonly directChannels = new Map<string, NativeTeamDirectChannel>();\n\n  private directChannelForRoot(rootSessionId: string): NativeTeamDirectChannel {\n    const existing = this.directChannels.get(rootSessionId);\n    if (existing) return existing;\n    const channel = new NativeTeamDirectChannel(ensureNativeTeamRoot(rootSessionId));\n    this.directChannels.set(rootSessionId, channel);\n    return channel;\n  }\n\n  createNativeChildIntercom(input: NativeTeamChildIntercomInput): DoomChildSessionIntercom | undefined {\n    return this.directChannels.get(input.rootSessionId)?.bindChild(input);\n  }\n\n  createRuntime(pi: ExtensionAPI): NativeTeamRuntime {\n    const existing = this.runtimes.get(pi);\n    if (existing) return existing;\n    const runtime = new TeamChannelRuntime(pi, (rootSessionId) => this.directChannelForRoot(rootSessionId));\n    this.runtimes.set(pi, runtime);\n    return runtime;\n  }\n\n  createHeadlessRuntime(transport: NativeTeamTransport): NativeTeamRuntime {\n    return new TeamChannelRuntime(transport, (rootSessionId) => this.directChannelForRoot(rootSessionId));\n  }\n}\n","/**\n * Debounced grouping for successful completion notifications.\n *\n * WHY THIS EXISTS:\n * A fan-out run's children tend to finish within milliseconds of each other.\n * Notifying once per child turns a five-way parallel run into five separate\n * interruptions for the operator instead of one. This holds a *successful*\n * completion briefly so siblings finishing in the same short window arrive as\n * a single grouped message.\n *\n * DESIGN PATTERNS (ported as-is from\n * `doom-pi-subagents/src/runs/background/completionBatcher.ts` - this\n * module's logic was not one of the flagged predecessor bugs):\n * - A hard `maxWaitMs` cap, measured from the first item in the group, means\n *   a debounce that keeps getting reset by new arrivals cannot hold a group\n *   open forever\n * - After a group emits, arrivals within `stragglerWindowMs` join a shorter\n *   \"straggler\" group (`stragglerDebounceMs`/`stragglerMaxWaitMs`): a single\n *   slow sibling still gets grouped with whoever else trails in soon after,\n *   rather than waiting out the full debounce alone\n * - `push()` is the only entry point that arms timers; `flush()` and\n *   `dispose()` both go through the same `clearTimers`/emit path, so there is\n *   one place a leak could be introduced\n * - Disabled mode (`config.enabled === false`) degrades to \"emit immediately,\n *   one item at a time\" rather than a special code path elsewhere: every\n *   caller of `push()` behaves the same regardless of whether batching is on\n *\n * WHY THIS OWNS ITS OWN TIMERS RATHER THAN REGISTERING WITH `PollScheduler`:\n * Same reasoning as `spawnHandshake.ts`'s documented exception, and for the\n * same underlying reason: `PollScheduler`'s floor is 200ms, and this\n * batcher's default `debounceMs` is 150ms - below the floor before backoff\n * even starts growing it. Coupling a sub-200ms debounce to a shared tick that\n * is explicitly designed to back off toward 5s while idle would make the\n * debounce it exists to provide unreliable. A completion batcher is also\n * short-lived and per-group (bounded by `maxWaitMs`, at most ~1s), the same\n * shape as a handshake wait, not a long-lived background subscriber.\n *\n * AVOID:\n * - Calling `push()` for a failed or paused completion; this batcher has no\n *   opinion on what should bypass it; that decision belongs to the caller\n *   (`notify.ts`), which flushes and emits those immediately instead\n */\n\nexport interface CompletionBatchConfig {\n  enabled?: boolean;\n  /** Idle window after each arrival; resets on every new item. */\n  debounceMs?: number;\n  /** Hard cap measured from the first item in a group. */\n  maxWaitMs?: number;\n  /** Shorter idle window for straggler groups. */\n  stragglerDebounceMs?: number;\n  /** Shorter hard cap for straggler groups. */\n  stragglerMaxWaitMs?: number;\n  /** Arrivals within this window after an emit join a straggler group. */\n  stragglerWindowMs?: number;\n}\n\nexport interface ResolvedCompletionBatchConfig {\n  enabled: boolean;\n  debounceMs: number;\n  maxWaitMs: number;\n  stragglerDebounceMs: number;\n  stragglerMaxWaitMs: number;\n  stragglerWindowMs: number;\n}\n\nexport const DEFAULT_COMPLETION_BATCH_CONFIG: ResolvedCompletionBatchConfig = {\n  enabled: true,\n  debounceMs: 150,\n  maxWaitMs: 1000,\n  stragglerDebounceMs: 75,\n  stragglerMaxWaitMs: 400,\n  stragglerWindowMs: 2000,\n};\n\nfunction parsePositiveInt(value: unknown): number | undefined {\n  if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < 1) return undefined;\n  return value;\n}\n\nexport function resolveCompletionBatchConfig(override?: CompletionBatchConfig): ResolvedCompletionBatchConfig {\n  return {\n    enabled: typeof override?.enabled === 'boolean' ? override.enabled : DEFAULT_COMPLETION_BATCH_CONFIG.enabled,\n    debounceMs: parsePositiveInt(override?.debounceMs) ?? DEFAULT_COMPLETION_BATCH_CONFIG.debounceMs,\n    maxWaitMs: parsePositiveInt(override?.maxWaitMs) ?? DEFAULT_COMPLETION_BATCH_CONFIG.maxWaitMs,\n    stragglerDebounceMs:\n      parsePositiveInt(override?.stragglerDebounceMs) ?? DEFAULT_COMPLETION_BATCH_CONFIG.stragglerDebounceMs,\n    stragglerMaxWaitMs:\n      parsePositiveInt(override?.stragglerMaxWaitMs) ?? DEFAULT_COMPLETION_BATCH_CONFIG.stragglerMaxWaitMs,\n    stragglerWindowMs:\n      parsePositiveInt(override?.stragglerWindowMs) ?? DEFAULT_COMPLETION_BATCH_CONFIG.stragglerWindowMs,\n  };\n}\n\ntype TimerHandle = ReturnType<typeof setTimeout>;\n\ninterface TimerApi {\n  setTimeout(handler: () => void, delayMs: number): TimerHandle;\n  clearTimeout(handle: TimerHandle): void;\n}\n\nconst defaultTimers: TimerApi = {\n  setTimeout: (handler, delayMs) => setTimeout(handler, delayMs),\n  clearTimeout: (handle) => clearTimeout(handle),\n};\n\nexport interface CompletionBatcherOptions<T> {\n  config: ResolvedCompletionBatchConfig;\n  emit: (items: T[]) => void;\n  timers?: TimerApi;\n  now?: () => number;\n}\n\nexport interface CompletionBatcher<T> {\n  /** Add a batchable item. Emits immediately, alone, when batching is disabled. */\n  push(item: T): void;\n  /** Emit any held items immediately as a single group. No-op when nothing is held. */\n  flush(): void;\n  /** Clear timers and return items that were never emitted, without emitting them. */\n  dispose(): T[];\n}\n\n/**\n * Create a completion batcher. Single-use per registration: it holds at most\n * one open group at a time. `flush()` forces emission (used by the caller to\n * drain a group before an immediate, unbatched emit for a failure/pause);\n * `dispose()` tears down timers for reload/shutdown without emitting.\n */\nexport function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>): CompletionBatcher<T> {\n  const timers = options.timers ?? defaultTimers;\n  const now = options.now ?? Date.now;\n  const config = options.config;\n\n  if (!config.enabled) {\n    return {\n      push(item: T) {\n        options.emit([item]);\n      },\n      flush() {\n        /* nothing is ever held when disabled */\n      },\n      dispose() {\n        return [];\n      },\n    };\n  }\n\n  let pending: T[] = [];\n  let debounceTimer: TimerHandle | undefined;\n  let maxWaitTimer: TimerHandle | undefined;\n  let straggler = false;\n  let lastEmitAt: number | undefined;\n\n  const clearTimers = (): void => {\n    if (debounceTimer !== undefined) {\n      timers.clearTimeout(debounceTimer);\n      debounceTimer = undefined;\n    }\n    if (maxWaitTimer !== undefined) {\n      timers.clearTimeout(maxWaitTimer);\n      maxWaitTimer = undefined;\n    }\n  };\n\n  const emitGroup = (): void => {\n    clearTimers();\n    if (pending.length === 0) return;\n    const items = pending;\n    pending = [];\n    lastEmitAt = now();\n    options.emit(items);\n  };\n\n  return {\n    push(item: T) {\n      if (pending.length === 0) {\n        straggler = lastEmitAt !== undefined && now() - lastEmitAt < config.stragglerWindowMs;\n      }\n      pending.push(item);\n\n      if (debounceTimer !== undefined) timers.clearTimeout(debounceTimer);\n      const debounceDelay = straggler ? config.stragglerDebounceMs : config.debounceMs;\n      debounceTimer = timers.setTimeout(emitGroup, debounceDelay);\n      debounceTimer.unref?.();\n\n      if (maxWaitTimer === undefined) {\n        const maxWaitDelay = straggler ? config.stragglerMaxWaitMs : config.maxWaitMs;\n        maxWaitTimer = timers.setTimeout(emitGroup, maxWaitDelay);\n        maxWaitTimer.unref?.();\n      }\n    },\n    flush: emitGroup,\n    dispose() {\n      clearTimers();\n      const abandoned = pending;\n      pending = [];\n      return abandoned;\n    },\n  };\n}\n","/**\n * Formats a run's terminal result into a completion notification and hands\n * it to `ResultWatcher` as its `ResultConsumer`, batching successful\n * completions and bypassing that batching for anything that needs the\n * operator's attention right away.\n *\n * WHY `completion-dedupe.ts` IS NOT PORTED:\n * The predecessor deduped completion notifications with its own TTL-keyed\n * map (`completion-dedupe.ts`), independently of the identically-shaped TTL\n * dedupe `resultWatcher.ts` already does before it ever calls a consumer.\n * Those two copies could disagree - the exact bug class `resultWatcher.ts`'s\n * header now documents fixing. This package has exactly one producer of\n * completions today: `ResultWatcher`, which only calls its consumer once per\n * `runId` per TTL window. `CompletionNotifier.deliver()` is that consumer, so\n * it trusts that guarantee instead of re-implementing it. The predecessor\n * needed its own copy because it had two independent producers (async result\n * files AND a synchronous foreground-run event); this package is async-only\n * (see `spawnHandshake.ts`'s header) and has not ported foreground runs. IF\n * a second completion producer is added later, `deliver()` can no longer\n * assume `ResultWatcher` already deduped for it, and this module will need\n * its own dedupe again at that point - not before.\n *\n * DESIGN PATTERNS:\n * - `deliver()` matches `ResultConsumer`'s exact shape\n *   (`(result: RunResultFile) => boolean | Promise<boolean>`), so this class\n *   is meant to be registered directly as `ResultWatcher`'s consumer, not\n *   subscribed to a separate event bus the way the predecessor's notifier\n *   subscribed to two\n * - Batching (`completionBatcher.ts`) only ever holds a *successful*\n *   completion. A failure or a pause is exactly the situation batching's\n *   debounce would otherwise delay reporting, so those flush whatever is\n *   already held for the same group and emit immediately, unbatched\n * - One batcher per group key (by `sessionId`, falling back to `cwd`, then a\n *   shared `'unknown'` bucket), created lazily and kept for the process\n *   lifetime: siblings of the same run share a group, unrelated runs never\n *   hold each other up\n * - `deliver()`'s returned promise resolves only once the item's group\n *   actually emits (immediately for a bypass, after the batcher's debounce\n *   for a grouped success). `ResultWatcher` awaits this before deciding\n *   whether to release the claim, so a claim legitimately stays in flight for\n *   as long as its group is held open - that is intended, not a stall\n *\n * WHY `sendMessage` IS INERT UNTIL A HOST IS ATTACHED:\n * The host channel arrives at runtime, not at construction: this is a\n * container singleton, and the `ExtensionAPI` that owns the chat surface only\n * exists once `extensions/pi.ts` is activated. `attachHost` is what closes\n * that gap, and until it is called - in the runner child, in a test, or in\n * any process with no TUI - returning `false` rather than claiming success is\n * deliberate. It is the honest answer (\"this was not actually shown to\n * anyone\"), and it is what lets `ResultWatcher`'s retry keep the claim around\n * to be flushed later instead of dropping the completion on the floor.\n *\n * AVOID:\n * - Reintroducing a dedupe map here \"just in case\"; see the header note above\n * - Calling `batcher.push()` for anything whose status is not `'completed'`\n */\n\nimport { formatAgentIdentity } from '../agentIdentity';\nimport {\n  type CompletionBatchConfig,\n  type CompletionBatcher,\n  createCompletionBatcher,\n  resolveCompletionBatchConfig,\n} from '../completionBatcher';\nimport type { RunResultFile } from '../resultWatcher';\n\nexport type CompletionStatus = 'completed' | 'failed' | 'paused';\n\nconst EMPTY_OUTPUT = '(no output)';\nconst UNKNOWN_VALUE = 'unknown';\nconst RECENT_TRANSCRIPT_LINES = 80;\nconst SINGLE_SUCCESS_ACTION = 'Handle this result now: incorporate it, reject it with a reason, or mark it irrelevant.';\nconst GROUPED_SUCCESS_ACTION =\n  'Handle each result now: incorporate it, reject it with a reason, or mark it irrelevant.';\n\n/** What a completion actually renders as, independent of the raw result shape. */\nexport interface CompletionNotifyDetails {\n  agent: string;\n  /** Generated addressable identity, absent for a run that predates identities. */\n  identity?: string;\n  inline?: boolean;\n  /**\n   * The run this completion belongs to.\n   *\n   * Load-bearing, not decoration: a completion is the ONLY message the model\n   * gets when a background run ends, and every follow-up it might want -\n   * `{action:'status', id}`, `steer`, `resume`, tailing a transcript - is\n   * keyed by run id. Without it the model has to re-list every run and guess\n   * which one just finished, which is exactly the wasted turn the sibling\n   * implementation avoids by putting `<task-id>` in its own notification.\n   */\n  runId: string;\n  status: CompletionStatus;\n  resultPreview: string;\n  taskInfo?: string;\n  durationMs?: number;\n  sessionLabel?: string;\n  sessionValue?: string;\n  handoffPath?: string;\n}\n\n/**\n * Return the one next action justified by this result. A usable summary should\n * be handled directly. Transcript recovery is reserved for missing or\n * insufficient output, and every example matches the strict status schema.\n */\nfunction completionAction(details: CompletionNotifyDetails): string {\n  const hasPreview = details.resultPreview.trim().length > 0;\n  const transcriptRequest = `{ action: \"status\", id: \"${details.runId}\", transcriptLines: ${RECENT_TRANSCRIPT_LINES} }`;\n  if (details.status === 'completed') {\n    return hasPreview\n      ? SINGLE_SUCCESS_ACTION\n      : `No summary was produced. Inspect recent output with ${transcriptRequest} before handling this result.`;\n  }\n  if (details.status === 'paused') {\n    return `Run is paused. Inspect it with { action: \"status\", id: \"${details.runId}\" }, then restore it only if status reports it as resumable.`;\n  }\n  return hasPreview\n    ? `Use the failure summary first. If it does not explain the failure, inspect recent output with ${transcriptRequest}.`\n    : `No failure summary was produced. Inspect recent output with ${transcriptRequest}.`;\n}\n\nfunction formatSessionLine(details: CompletionNotifyDetails): string | undefined {\n  if (!details.sessionValue) return undefined;\n  return details.sessionLabel ? `${details.sessionLabel}: ${details.sessionValue}` : details.sessionValue;\n}\n\n/** Who finished, preferring the generated identity and falling back to the bare agent name. */\nfunction completionLabel(details: CompletionNotifyDetails): string {\n  return formatAgentIdentity(details.identity, details.inline) ?? details.agent;\n}\n\nexport function formatSingleCompletion(details: CompletionNotifyDetails): string {\n  const sessionLine = formatSessionLine(details);\n  return [\n    `Background task ${details.status}: **${completionLabel(details)}**${details.taskInfo ?? ''}`,\n    `run id: ${details.runId}`,\n    '',\n    details.resultPreview.trim() ? details.resultPreview : EMPTY_OUTPUT,\n    details.handoffPath ? '' : undefined,\n    details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,\n    sessionLine ? '' : undefined,\n    sessionLine,\n    '',\n    completionAction(details),\n  ]\n    .filter((line) => line !== undefined)\n    .join('\\n');\n}\n\nexport function formatGroupedCompletion(details: CompletionNotifyDetails[]): string {\n  const header = `Background tasks completed (${details.length}): ${details.map((d) => `**${completionLabel(d)}**${d.taskInfo ?? ''}`).join(', ')}`;\n  const blocks: string[] = [header, ''];\n  for (let index = 0; index < details.length; index++) {\n    const detail = details[index];\n    if (!detail) continue;\n    const sessionLine = formatSessionLine(detail);\n    const hasPreview = detail.resultPreview.trim().length > 0;\n    blocks.push(`${index + 1}. ${completionLabel(detail)}${detail.taskInfo ?? ''} - run id: ${detail.runId}`);\n    blocks.push(hasPreview ? detail.resultPreview : EMPTY_OUTPUT);\n    if (detail.handoffPath) blocks.push(`Parallel handoff: ${detail.handoffPath}`);\n    if (sessionLine) blocks.push(sessionLine);\n    if (!hasPreview) blocks.push(completionAction(detail));\n    blocks.push('');\n  }\n  blocks.push(GROUPED_SUCCESS_ACTION);\n  return blocks.join('\\n').trimEnd();\n}\n\n/**\n * A single line naming what finished, for an operator-facing notification.\n *\n * Separate from `formatSingleCompletion` because the two have different\n * readers. That one is written for the model and embeds the run's full result\n * preview; this one goes to `DoomHeadlessClient.notify`, which collapses every\n * newline to a space and truncates at 4096 characters\n * (`packages/core/doompi-core/src/schemas/notification.ts`), and on the web\n * additionally drives a browser notification. Feeding the model-facing text to\n * that channel is what turns a completion into a wall of run-on prose.\n */\nexport function formatCompletionHeadline(details: CompletionNotifyDetails[]): string {\n  const first = details[0];\n  if (!first) return 'Background task finished';\n  if (details.length === 1) {\n    return `Background task ${first.status}: ${completionLabel(first)}${first.taskInfo ?? ''} (${first.runId})`;\n  }\n  return `Background tasks finished (${details.length}): ${details\n    .map((detail) => `${completionLabel(detail)}${detail.taskInfo ?? ''}`)\n    .join(', ')}`;\n}\n/** Narrow an opaque `RunResultFile` field to a string, the same defensive read used throughout. */\nfunction asString(value: unknown): string | undefined {\n  return typeof value === 'string' ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\nfunction completionGroupKey(result: RunResultFile): string {\n  const sessionId = asString(result.sessionId)?.trim();\n  if (sessionId) return `session:${sessionId}`;\n  const cwd = asString(result.cwd)?.trim();\n  return cwd ? `cwd:${cwd}` : UNKNOWN_VALUE;\n}\n\n/** Turn a raw, opaque result record into what `formatSingleCompletion`/`formatGroupedCompletion` render. */\nexport function buildCompletionDetails(result: RunResultFile): CompletionNotifyDetails {\n  const agent = asString(result.agent) ?? UNKNOWN_VALUE;\n  const identity = asString(result.identity);\n  const inline = result.inline === true;\n  const summary = asString(result.summary) ?? '';\n  const success = typeof result.success === 'boolean' ? result.success : undefined;\n  const state = asString(result.state);\n  const paused = success === false && (state === 'paused' || summary.startsWith('Paused after interrupt.'));\n  const status: CompletionStatus = paused ? 'paused' : success === false ? 'failed' : 'completed';\n\n  const taskIndex = asNumber(result.taskIndex);\n  const totalTasks = asNumber(result.totalTasks);\n  const taskInfo =\n    taskIndex !== undefined && totalTasks !== undefined ? ` (${taskIndex + 1}/${totalTasks})` : undefined;\n\n  const parallelHandoff =\n    typeof result.parallelHandoff === 'object' && result.parallelHandoff !== null\n      ? (result.parallelHandoff as { path?: unknown })\n      : undefined;\n  const handoffPath = asString(parallelHandoff?.path);\n\n  const shareUrl = asString(result.shareUrl);\n  const shareError = asString(result.shareError);\n  const sessionFile = asString(result.sessionFile);\n  const session = shareUrl\n    ? { label: 'Session', value: shareUrl }\n    : shareError\n      ? { label: 'Session share error', value: shareError }\n      : sessionFile\n        ? { label: 'Session file', value: sessionFile }\n        : undefined;\n\n  return {\n    agent,\n    ...(identity ? { identity, inline } : {}),\n    // `RunResultFile` guarantees `runId` (see `resultWatcher.ts`), so there is\n    // no honest fallback to invent here - an empty string would be a run id the\n    // model could not use, dressed up as one it could.\n    runId: result.runId,\n    status,\n    resultPreview: summary,\n    ...(taskInfo ? { taskInfo } : {}),\n    ...(asNumber(result.durationMs) !== undefined ? { durationMs: asNumber(result.durationMs) } : {}),\n    ...(handoffPath ? { handoffPath } : {}),\n    ...(session ? { sessionLabel: session.label, sessionValue: session.value } : {}),\n  };\n}\n\ninterface PendingCompletion {\n  details: CompletionNotifyDetails;\n  triggerTurn: boolean;\n  resolve(delivered: boolean): void;\n}\n\n/**\n * The host capability this notifier needs, narrowed to the one method it\n * calls. Structural rather than `ExtensionAPI` itself so the runs domain does\n * not take a dependency on the host type for a single call, and so a test can\n * supply a recorder without constructing a whole extension API.\n *\n * `sendMessage` may return a promise. The Pi host renders synchronously and\n * returns `void`; a headless host has to reach the session over async calls\n * (`session.appendCustomEntry`, `session.admitPrompt`), and the notifier must\n * be able to tell a settled delivery from a started one - see `sendMessage`\n * below for why that distinction decides whether a completion can be lost.\n */\nexport interface CompletionNotifyHost {\n  sendMessage(\n    message: { customType: string; content: string; display: boolean; details?: CompletionNotifyDetails[] },\n    options?: { triggerTurn?: boolean; deliverAs?: 'steer' },\n  ): void | Promise<void>;\n}\n\nexport type CompletionNotifierContract = {\n  /** Matches `ResultConsumer` exactly; register this directly with `ResultWatcher.start()`. */\n  deliver(result: RunResultFile): Promise<boolean>;\n  /**\n   * Give the notifier the host channel to render into. Called by the parent\n   * composition root (`extensions/pi.ts`); until it is, `sendMessage` stays\n   * inert and honestly reports non-delivery - see the module header.\n   */\n  attachHost(host: CompletionNotifyHost): void;\n  /** Flush every held batch immediately (unemitted items resolve `false`) and stop accepting new ones. */\n  dispose(): void;\n};\n\n/**\n * The custom-message type the parent renders completions under. The literal is\n * shared by the producer here and the TUI renderer registered for it\n * (`(frontend)/message/_lib/subagent-notify.cli.ts`, which draws through\n * `completionNotice.ts`), and by the headless facet, which persists the same\n * type as a session entry so a cockpit transcript records what was delivered.\n */\nexport const SUBAGENT_NOTIFY_MESSAGE_TYPE = 'subagent-notify';\n\nexport class CompletionNotifier implements CompletionNotifierContract {\n  /**\n   * Runtime tuning seam for tests, kept out of the dependency constructor.\n   */\n  protected readonly batchConfig: CompletionBatchConfig | undefined = undefined;\n\n  private readonly batchers = new Map<string, CompletionBatcher<PendingCompletion>>();\n  private disposed = false;\n  private host: CompletionNotifyHost | undefined;\n\n  /**\n   * Last host attachment wins. A reload that rebuilds the extension against a\n   * fresh `ExtensionAPI` re-attaches rather than stacking channels, matching\n   * how every other registration in `extensions/pi.ts` is idempotent.\n   */\n  attachHost(host: CompletionNotifyHost): void {\n    this.host = host;\n  }\n\n  /**\n   * Deliver a formatted completion message. Inert until `attachHost` supplies\n   * a host (see the module header for why non-delivery is reported honestly\n   * rather than optimistically).\n   *\n   * Returns `boolean` for a host that delivered synchronously and a promise\n   * for one that did not. Resolving optimistically would be a silent data\n   * loss: consumers call `acknowledgeHandoff` on `true`\n   * (`services/teamRuntime/index.ts`, `services/nativeRunCoordinator/index.ts`),\n   * which drops `ResultWatcher`'s claim, so a completion reported as delivered\n   * and then rejected is gone for good. A rejection therefore maps to `false`,\n   * exactly as a synchronous throw always has, and the claim survives for a\n   * retry.\n   */\n  protected sendMessage(\n    content: string,\n    options: { triggerTurn: boolean; details: CompletionNotifyDetails[] },\n  ): boolean | Promise<boolean> {\n    if (!this.host) return false;\n    try {\n      const pending = this.host.sendMessage(\n        { customType: SUBAGENT_NOTIFY_MESSAGE_TYPE, content, display: true, details: options.details },\n        { triggerTurn: options.triggerTurn, deliverAs: 'steer' },\n      );\n      return pending === undefined\n        ? true\n        : pending.then(\n            () => true,\n            () => false,\n          );\n    } catch {\n      return false;\n    }\n  }\n\n  async deliver(result: RunResultFile): Promise<boolean> {\n    if (result.internal === true) return true;\n    if (this.disposed) return false;\n    const details = buildCompletionDetails(result);\n    const triggerTurn = result.triggerTurn !== false;\n\n    return new Promise<boolean>((resolve) => {\n      const item: PendingCompletion = { details, triggerTurn, resolve };\n      const batcher = this.getBatcher(result);\n      if (details.status !== 'completed') {\n        // A failure or a pause must not sit behind a debounce meant for\n        // grouping good news; flush whatever this group was already holding,\n        // then emit this one immediately, unbatched.\n        batcher.flush();\n        this.emit([item]);\n        return;\n      }\n      batcher.push(item);\n    });\n  }\n\n  dispose(): void {\n    if (this.disposed) return;\n    this.disposed = true;\n    for (const batcher of this.batchers.values()) {\n      for (const item of batcher.dispose()) item.resolve(false);\n    }\n    this.batchers.clear();\n  }\n\n  private getBatcher(result: RunResultFile): CompletionBatcher<PendingCompletion> {\n    const key = completionGroupKey(result);\n    let batcher = this.batchers.get(key);\n    if (!batcher) {\n      batcher = createCompletionBatcher<PendingCompletion>({\n        config: resolveCompletionBatchConfig(this.batchConfig),\n        emit: (items) => this.emit(items),\n      });\n      this.batchers.set(key, batcher);\n    }\n    return batcher;\n  }\n\n  /**\n   * The batcher's `emit` callback: format the group (single vs. grouped\n   * rendering, `formatSingleCompletion`/`formatGroupedCompletion`) and hand\n   * it to `sendMessage`. Deliberately not `async`: `createCompletionBatcher`'s\n   * `emit` option is a synchronous callback (see its own contract). When the\n   * host delivers asynchronously the items resolve once that settles, which\n   * `deliver()`'s contract already allows - see the module header on a claim\n   * legitimately staying in flight.\n   */\n  private emit(items: PendingCompletion[]): void {\n    if (items.length === 0) return;\n    const details = items.map((item) => item.details);\n    const content = details.length === 1 ? formatSingleCompletion(details[0]!) : formatGroupedCompletion(details);\n    const delivered = this.sendMessage(content, {\n      triggerTurn: items.some((item) => item.triggerTurn),\n      details,\n    });\n    if (typeof delivered === 'boolean') {\n      for (const item of items) item.resolve(delivered);\n      return;\n    }\n    void delivered.then((settled) => {\n      for (const item of items) item.resolve(settled);\n    });\n  }\n}\n","/**\n * One master tick that drives every background subscriber in the runner\n * process: channels, watchers, inspectors, anything that used to own its own\n * `setInterval`.\n *\n * WHY ONE TICK AND NOT ONE TIMER PER SUBSCRIBER:\n * The predecessor package (`doom-pi-subagents`) gave every channel, watcher\n * and inspector its own independent interval. None of them coordinated, all of\n * them kept firing when nothing was happening, and the parent process burned\n * CPU while completely idle. A single scheduler that every subscriber reports\n * to can decide, once, whether there is any reason to keep ticking quickly.\n *\n * IDLE BACKOFF:\n * The tick interval starts at `floorMs`. A tick where nothing reported work\n * multiplies the interval by `backoffMultiplier`, capped at `ceilingMs`. A tick\n * where anything reported work resets it straight back to `floorMs`. \"Reported\n * work\" means a subscriber's `run()` returned `true`; returning `false` or\n * `void` means it checked and found nothing to do.\n *\n * WATCH-FIRST, POLL AS A SAFETY NET:\n * The intended pattern is: a subscriber's own `intervalMs` is set generously\n * (roughly 4x looser than how quickly you actually want it checked), and a\n * filesystem watch is the fast path. When the watch fires, its handler calls\n * `wake()`, which runs every subscriber immediately regardless of backoff.\n * Polling on `intervalMs` only exists to cover the platforms and mount types\n * where filesystem watches are unreliable or simply do not fire. Neither path\n * is trusted alone: the watch gives latency, the poll interval gives a bound\n * on how late a check can ever be.\n *\n * DESIGN PATTERNS:\n * - Subscribers are checked for both \"due\" (their own `intervalMs` has\n *   elapsed) and \"forced\" (a `wake()` call), so a fast-changing subscriber and\n *   a rarely-changing one can share one clock without either starving\n * - A subscriber's key is internal and never the caller-supplied `id`, so two\n *   subscribers that reuse the same `id` string (a plausible mistake with\n *   per-run subscriber names) cannot make one's `unregister()` delete the\n *   other's registration\n * - Synchronous subscribers still complete in the same tick. Async subscribers\n *   are awaited sequentially, and forced wakes coalesce behind the active tick,\n *   so slow filesystem work never creates overlapping scans\n *\n * AVOID:\n * - Reading `this.floorMs` (or the other seam fields) from the constructor:\n *   field initializer order runs the base class's defaults before a test\n *   subclass's overrides are applied, so a value read in the constructor would\n *   see the base default even when a subclass overrides it. Everything that\n *   needs these values reads them lazily, from `start()` or `tick()`, which run\n *   after construction is complete\n * - Letting a subscriber's thrown error escape `tick()`; it must not stop the\n *   tick or affect its peers. It is recorded rather than discarded, since a\n *   subscriber that throws every tick otherwise looks identical to an idle one\n */\n\n/** Minimum spacing between ticks once nothing has reported work in a while. */\nconst DEFAULT_FLOOR_MS = 200;\n/** Ceiling the backoff grows toward while idle. */\nconst DEFAULT_CEILING_MS = 5_000;\n/** Growth factor applied to the tick interval on every idle tick. */\nconst DEFAULT_BACKOFF_MULTIPLIER = 2;\n\nexport interface PollSubscription {\n  /** For readability in logs and error messages only; not used as a map key. */\n  id: string;\n  /** How often this subscriber is checked, in milliseconds. Must be positive. */\n  intervalMs: number;\n  /**\n   * Called when due. Return `true` when it did real work, which resets the\n   * scheduler's backoff to the floor. Return `false` or nothing when there was\n   * nothing to do, which lets idle backoff continue growing.\n   */\n  run: () => boolean | void | Promise<boolean | undefined>;\n}\n\nexport type PollSchedulerContract = {\n  /** Register a subscriber. Call the returned function to unregister it. */\n  register(subscription: PollSubscription): () => void;\n  /** Run every subscriber immediately, bypassing backoff and due-checks. */\n  wake(): void;\n  /** Begin ticking. Idempotent: a second call while running does nothing. */\n  start(): void;\n  /** Stop ticking and clear the pending timer. Idempotent. */\n  stop(): void;\n};\n\ninterface InternalSubscriber extends PollSubscription {\n  /** `undefined` until the first tick runs it; never `0`, which a test clock may legitimately start at. */\n  lastRunAt: number | undefined;\n}\n\nexport class PollScheduler implements PollSchedulerContract {\n  /**\n   * Runtime tuning seams for tests, kept out of the dependency constructor.\n   */\n  protected readonly floorMs: number = DEFAULT_FLOOR_MS;\n  protected readonly ceilingMs: number = DEFAULT_CEILING_MS;\n  protected readonly backoffMultiplier: number = DEFAULT_BACKOFF_MULTIPLIER;\n\n  protected now(): number {\n    return Date.now();\n  }\n\n  /**\n   * Records a subscriber that threw. Overridable, and deliberately not a\n   * stdio write: this runs inside a detached runner whose stdout is the child's\n   * captured transcript. The composition root routes these into that process's\n   * own diagnostics; the default keeps the most recent one queryable so a\n   * failing subscriber can still be found after the fact.\n   */\n  protected onSubscriberError(id: string, error: unknown): void {\n    this.lastSubscriberError = { id, error, at: this.now() };\n    this.subscriberErrorCount += 1;\n  }\n\n  /** The most recent subscriber failure, for diagnostics. */\n  lastSubscriberError: { id: string; error: unknown; at: number } | undefined;\n  /** How many subscriber failures this scheduler has absorbed. */\n  subscriberErrorCount = 0;\n\n  private readonly subscribers = new Map<number, InternalSubscriber>();\n  private nextSubscriberKey = 0;\n  private timer: ReturnType<typeof setTimeout> | undefined;\n  private currentIntervalMs: number | undefined;\n  private running = false;\n  private tickRunning = false;\n  private forcedTickQueued = false;\n  private generation = 0;\n\n  register(subscription: PollSubscription): () => void {\n    if (!(subscription.intervalMs > 0)) {\n      throw new Error(`Poll subscriber \"${subscription.id}\" must have a positive intervalMs.`);\n    }\n    const key = this.nextSubscriberKey++;\n    this.subscribers.set(key, { ...subscription, lastRunAt: undefined });\n    return () => {\n      this.subscribers.delete(key);\n    };\n  }\n\n  start(): void {\n    if (this.running) return;\n    this.running = true;\n    this.generation += 1;\n    this.currentIntervalMs = this.floorMs;\n    this.tick(false);\n  }\n\n  stop(): void {\n    this.running = false;\n    this.generation += 1;\n    this.forcedTickQueued = false;\n    if (this.timer) clearTimeout(this.timer);\n    this.timer = undefined;\n  }\n\n  wake(): void {\n    if (!this.running) return;\n    if (this.timer) clearTimeout(this.timer);\n    this.timer = undefined;\n    this.tick(true);\n  }\n\n  /**\n   * Run every due subscriber (or, when `forced`, every subscriber), fold the\n   * outcome into the backoff curve, and schedule the next tick.\n   */\n  private tick(forced: boolean): void {\n    if (this.tickRunning) {\n      this.forcedTickQueued ||= forced;\n      return;\n    }\n\n    this.tickRunning = true;\n    const generation = this.generation;\n    const timestamp = this.now();\n    const subscribers = [...this.subscribers.values()];\n    let workHappened = false;\n    let anySubscriberRan = false;\n\n    const finish = (): void => {\n      if (generation === this.generation && anySubscriberRan) {\n        const previousIntervalMs = this.currentIntervalMs ?? this.floorMs;\n        this.currentIntervalMs = workHappened\n          ? this.floorMs\n          : Math.min(previousIntervalMs * this.backoffMultiplier, this.ceilingMs);\n      }\n      this.tickRunning = false;\n      if (!this.running) return;\n      if (this.forcedTickQueued || generation !== this.generation) {\n        this.forcedTickQueued = false;\n        this.tick(true);\n        return;\n      }\n      this.scheduleNext();\n    };\n\n    const visit = (index: number): void => {\n      if (generation !== this.generation) {\n        finish();\n        return;\n      }\n      for (let current = index; current < subscribers.length; current += 1) {\n        const subscriber = subscribers[current];\n        if (!subscriber) continue;\n        const due =\n          forced || subscriber.lastRunAt === undefined || timestamp - subscriber.lastRunAt >= subscriber.intervalMs;\n        if (!due) continue;\n        subscriber.lastRunAt = timestamp;\n        anySubscriberRan = true;\n        try {\n          const result = subscriber.run();\n          if (result instanceof Promise) {\n            void result.then(\n              (worked) => {\n                if (worked) workHappened = true;\n                visit(current + 1);\n              },\n              (error: unknown) => {\n                this.onSubscriberError(subscriber.id, error);\n                visit(current + 1);\n              },\n            );\n            return;\n          }\n          if (result) workHappened = true;\n        } catch (error) {\n          this.onSubscriberError(subscriber.id, error);\n        }\n      }\n      finish();\n    };\n\n    visit(0);\n  }\n\n  private scheduleNext(): void {\n    if (!this.running) return;\n    const delayMs = this.currentIntervalMs ?? this.floorMs;\n    this.timer = setTimeout(() => this.tick(false), delayMs);\n    // A pending background poll must never be the reason the process stays\n    // alive; `unref` is optional only because some test timer shims omit it.\n    this.timer.unref?.();\n  }\n}\n","import { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\n\nimport { writeAtomicJson } from '../atomicJson';\nimport { DoomTeamExpectedError } from '../errors';\nimport { scopeRunsDir, type SessionScope } from '../sessionPaths';\n\nconst HASH_ALGORITHM = 'sha256';\nconst HASH_ENCODING = 'hex';\n\ninterface OperationRecord<TResult> {\n  version: 1;\n  operationId: string;\n  argumentHash: string;\n  runIds: string[];\n  state: 'pending' | 'completed';\n  createdAt: number;\n  result?: TResult;\n}\n\nexport type OperationStart<TResult> =\n  | { kind: 'new'; record: OperationRecord<TResult> }\n  | { kind: 'replay'; record: OperationRecord<TResult> };\n\nfunction hashArguments(args: unknown): string {\n  return createHash(HASH_ALGORITHM).update(JSON.stringify(args)).digest(HASH_ENCODING);\n}\n\nfunction journalPath(scope: SessionScope, operationId: string): string {\n  const safeId = createHash(HASH_ALGORITHM).update(operationId).digest(HASH_ENCODING);\n  return path.join(scopeRunsDir(scope), '..', 'operations', `${safeId}.json`);\n}\n\nfunction readRecord<TResult>(file: string): OperationRecord<TResult> {\n  return JSON.parse(fs.readFileSync(file, 'utf8')) as OperationRecord<TResult>;\n}\n\n/** Persist replay identity and run ids before any side effect is started. */\nexport function startOperation<TResult>(\n  scope: SessionScope,\n  operationId: string,\n  args: unknown,\n  runIds: string[],\n): OperationStart<TResult> {\n  const file = journalPath(scope, operationId);\n  const argumentHash = hashArguments(args);\n  fs.mkdirSync(path.dirname(file), { recursive: true });\n  const record: OperationRecord<TResult> = {\n    version: 1,\n    operationId,\n    argumentHash,\n    runIds,\n    state: 'pending',\n    createdAt: Date.now(),\n  };\n  try {\n    fs.writeFileSync(file, JSON.stringify(record), { flag: 'wx', mode: 0o600 });\n    return { kind: 'new', record };\n  } catch (error) {\n    if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;\n    const existing = readRecord<TResult>(file);\n    if (existing.argumentHash !== argumentHash) {\n      throw new DoomTeamExpectedError(\n        'operation_conflict',\n        `Operation '${operationId}' was already used with different arguments.`,\n        false,\n        'Submit the operation as a new tool call.',\n      );\n    }\n    return { kind: 'replay', record: existing };\n  }\n}\n\nexport function completeOperation<TResult>(\n  scope: SessionScope,\n  operationId: string,\n  record: OperationRecord<TResult>,\n  result: TResult,\n): void {\n  writeAtomicJson(journalPath(scope, operationId), { ...record, state: 'completed', result });\n}\n","/**\n * Formatting utilities for display output.\n *\n * DESIGN PATTERNS:\n * - Every function here is presentation only. Nothing it returns is parsed back,\n *   so rounding and truncation are free to favour readability\n * - Truncation limits are supplied per call site through the `expanded` flag so a\n *   detail pane and a one-line status row share one implementation\n *\n * AVOID:\n * - Round-tripping these strings; `formatTokens` and `formatDuration` are lossy\n * - Widening the tool-call preview limits without checking the narrowest surface\n *   that renders them\n */\n\nimport type { Usage } from '../../types';\nimport { splitKnownThinkingSuffix, THINKING_LEVELS } from '../modelInfo';\n\nconst TOKENS_PER_K = 1000;\nconst TOKENS_FRACTIONAL_K_LIMIT = 10000;\nconst MS_PER_SECOND = 1000;\nconst MS_PER_MINUTE = 60000;\nconst COST_DECIMAL_PLACES = 4;\nconst SECONDS_DECIMAL_PLACES = 1;\nconst K_DECIMAL_PLACES = 1;\nconst BASH_PREVIEW_LIMIT = 60;\nconst BASH_PREVIEW_LIMIT_EXPANDED = 240;\nconst ARGS_PREVIEW_LIMIT = 40;\nconst ARGS_PREVIEW_LIMIT_EXPANDED = 160;\nconst TRUNCATION_ELLIPSIS = '...';\nconst HOME_SHORTHAND = '~';\n\n/**\n * Format token count with k suffix for large numbers\n */\nexport function formatTokens(n: number): string {\n  if (n < TOKENS_PER_K) return String(n);\n  if (n < TOKENS_FRACTIONAL_K_LIMIT) return `${(n / TOKENS_PER_K).toFixed(K_DECIMAL_PLACES)}k`;\n  return `${Math.round(n / TOKENS_PER_K)}k`;\n}\n\nexport function formatModelThinking(model?: string, thinking?: string): string {\n  const parsed = model ? splitKnownThinkingSuffix(model) : undefined;\n  let displayModel = parsed?.baseModel ?? model;\n  const explicitThinking = THINKING_LEVELS.find((level) => level === thinking?.trim());\n  // A suffix on the model string is the caller's most specific intent, so it wins\n  // over the separately configured level.\n  const displayThinking = parsed?.thinkingSuffix ? parsed.thinkingSuffix.slice(1) : explicitThinking;\n  if (displayModel) {\n    const slashIdx = displayModel.lastIndexOf('/');\n    if (slashIdx !== -1) displayModel = displayModel.slice(slashIdx + 1);\n  }\n  return [displayModel, displayThinking ? `thinking ${displayThinking}` : undefined].filter(Boolean).join(' · ');\n}\n\n/**\n * Format usage statistics into a compact string\n */\nexport function formatUsage(u: Usage, model?: string): string {\n  const parts: string[] = [];\n  if (u.turns) parts.push(`${u.turns} turn${u.turns > 1 ? 's' : ''}`);\n  if (u.input) parts.push(`in:${formatTokens(u.input)}`);\n  if (u.output) parts.push(`out:${formatTokens(u.output)}`);\n  if (u.cacheRead) parts.push(`R${formatTokens(u.cacheRead)}`);\n  if (u.cacheWrite) parts.push(`W${formatTokens(u.cacheWrite)}`);\n  if (u.cost) parts.push(`$${u.cost.toFixed(COST_DECIMAL_PLACES)}`);\n  if (model) parts.push(model);\n  return parts.join(' ');\n}\n\n/**\n * Format duration in human-readable form\n */\nexport function formatDuration(ms: number): string {\n  if (ms < MS_PER_SECOND) return `${ms}ms`;\n  if (ms < MS_PER_MINUTE) return `${(ms / MS_PER_SECOND).toFixed(SECONDS_DECIMAL_PLACES)}s`;\n  return `${Math.floor(ms / MS_PER_MINUTE)}m${Math.floor((ms % MS_PER_MINUTE) / MS_PER_SECOND)}s`;\n}\n\n/**\n * Format a tool call for display\n */\nexport function formatToolCall(name: string, args: Record<string, unknown>, expanded = false): string {\n  switch (name) {\n    case 'bash': {\n      const command = typeof args.command === 'string' ? args.command : '';\n      const maxLength = expanded ? BASH_PREVIEW_LIMIT_EXPANDED : BASH_PREVIEW_LIMIT;\n      return `$ ${command.slice(0, maxLength)}${command.length > maxLength ? TRUNCATION_ELLIPSIS : ''}`;\n    }\n    case 'read':\n    case 'write':\n    case 'edit': {\n      const target =\n        typeof args.path === 'string' ? args.path : typeof args.file_path === 'string' ? args.file_path : '';\n      return `${name} ${shortenPath(target)}`;\n    }\n    default: {\n      const s = JSON.stringify(args);\n      const maxLength = expanded ? ARGS_PREVIEW_LIMIT_EXPANDED : ARGS_PREVIEW_LIMIT;\n      return `${name} ${s.slice(0, maxLength)}${s.length > maxLength ? TRUNCATION_ELLIPSIS : ''}`;\n    }\n  }\n}\n\n/**\n * Shorten a path by replacing home directory with ~\n */\nexport function shortenPath(p: string): string {\n  const home = process.env.HOME;\n  if (home && p.startsWith(home)) {\n    return `${HOME_SHORTHAND}${p.slice(home.length)}`;\n  }\n  return p;\n}\n","/**\n * Reads and renders a run's child transcript for the fleet detail pane.\n *\n * NOT A PORT:\n * The predecessor's `fleetTranscript.ts` parsed the HOST agent's own session\n * JSONL. The child transcript is a separate record, not the host's session\n * file. Translating the predecessor's parser would build a reader for a format\n * nothing here writes, so this reads the child transcript's\n * actual record shapes (`message`/`tool_start`/`tool_end`/`stdout`/`stderr`/\n * `truncated`) directly.\n *\n * READ THE RECORD, NOT THE SUMMARY:\n * Older child records flattened each message to a `text` field by recognising\n * only `{type:'text'}`. An assistant\n * turn made of a `thinking` block plus `toolCall` blocks therefore flattens to\n * nothing, and the writer omits the field entirely - which is what produced\n * rows of bare `assistant` headers with no content under them. The writer does\n * still persist the whole `message.content` array verbatim, so this module\n * parses THAT: thinking becomes its own event, and a turn with no text emits no\n * assistant event at all. Same reasoning for `argsPayload` (full tool arguments,\n * written all along, previously unread) and for `role: 'toolResult'` records,\n * which used to be dropped so a reader could see what ran but never what came\n * back.\n *\n * INCREMENTAL BY CONSTRUCTION:\n * A transcript is append-only and can reach 50 MiB, while the fleet overlay\n * re-checks the selected run roughly once a second. Re-reading and re-parsing\n * the whole file on every change makes cost grow with run length, so the reader\n * is resumable (`readFleetTranscriptTail`): it reads only the bytes appended\n * since the last call, and the renderer keeps one rendered block per event so\n * an append re-renders only the new and mutated ones. Steady-state cost is\n * proportional to what arrived, not to what the file holds.\n *\n * DESIGN PATTERNS:\n * - Reading is tolerant, not strict: the writer appends lines as a run\n *   progresses, so the last line on disk may be a partial write mid-flush.\n *   A line that fails to parse is dropped rather than failing the whole read\n * - `tool_start`/`tool_end`/`toolResult` are folded into ONE `tool` event keyed\n *   by `toolCallId`, so the pane reads as a sequence of turns rather than three\n *   lines per call. Calls interleave and `tool_end` arrives BEFORE its\n *   `toolResult`, so the fold map retains an entry for as long as its event is\n *   retained rather than closing it out on `tool_end`\n * - A `tool_end` with no matching start (the start fell outside the retained\n *   window) still renders on its own rather than being dropped, since it is\n *   still evidence of what ran\n *\n * AVOID:\n * - Reusing a `FleetTranscriptTail` after passing it as `previous`. The reader\n *   takes ownership of its `events` and fold map instead of copying them, which\n *   is the whole point of resuming; the returned tail supersedes it\n */\n\nimport * as fs from 'node:fs';\n\nexport type FleetTranscriptEventKind = 'user' | 'assistant' | 'thinking' | 'tool' | 'notice' | 'stdout' | 'stderr';\n\nexport interface FleetTranscriptEvent {\n  kind: FleetTranscriptEventKind;\n  at: number;\n  text: string;\n  /** Tool name, present only for `kind: 'tool'`. */\n  name?: string;\n  /** Present only for `kind: 'tool'`: `'running'` until a matching `tool_end` arrives. */\n  status?: 'running' | 'ok' | 'error';\n  /** Tool arguments parsed from `argsPayload`, when the writer recorded them. */\n  args?: Record<string, unknown>;\n  /** Tool output, folded in from the matching `toolResult` record. */\n  result?: string;\n  /** Set when the writer bounded `result` at its payload cap. */\n  resultTruncated?: boolean;\n  /** `tool_end` timestamp, for the call's duration. */\n  endedAt?: number;\n  /** Model that produced an assistant turn, when reported. */\n  model?: string;\n}\n\nexport interface FleetTranscript {\n  events: FleetTranscriptEvent[];\n  warning?: string;\n}\n\n/** One retained tool event and where it sits in `events`, so a later fold can mark it dirty. */\ninterface FleetTranscriptToolEntry {\n  event: FleetTranscriptEvent;\n  index: number;\n}\n\n/**\n * A resume point for `readFleetTranscriptTail`.\n *\n * `byteOffset` is deliberately the end of the last COMPLETE line rather than\n * the file size: a partial trailing line is left unconsumed so the next read\n * picks it up whole, instead of being dropped as unparseable the way a\n * whole-file read has to.\n */\nexport interface FleetTranscriptTail extends FleetTranscript {\n  path: string;\n  byteOffset: number;\n  /** Size observed at this read. A later shrink means the file was replaced, forcing a full re-read. */\n  size: number;\n  toolCalls: Map<string, FleetTranscriptToolEntry>;\n  /** Earliest index whose content changed in this read. Undefined when only appends happened. */\n  firstDirtyIndex: number | undefined;\n  /** Cumulative events dropped from the front by the retention cap. */\n  droppedEvents: number;\n}\n\n/**\n * Retention cap. Bounds memory and worst-case render cost independently of how\n * long a run goes on; `droppedEvents` keeps the fact that a window was applied\n * visible, so a tail is never mistaken for a whole run.\n */\nexport const MAX_RETAINED_EVENTS = 1000;\n\nconst NEWLINE_BYTE = 0x0a;\n\ninterface RawRecord {\n  recordType?: string;\n  ts?: number;\n  role?: string;\n  text?: string;\n  toolCallId?: string;\n  toolName?: string;\n  isError?: boolean;\n  argsPreview?: string;\n  argsPayload?: string;\n  outputTruncated?: boolean;\n  model?: string;\n  message?: { role?: string; content?: unknown };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction parseLine(line: string): RawRecord | undefined {\n  const trimmed = line.trim();\n  if (!trimmed) return undefined;\n  try {\n    const parsed: unknown = JSON.parse(trimmed);\n    return isRecord(parsed) ? (parsed as RawRecord) : undefined;\n  } catch {\n    // The writer appends line-by-line; a trailing partial write on the last\n    // line is expected while a run is in flight, not evidence of corruption.\n    return undefined;\n  }\n}\n\n/**\n * Split an assistant turn's raw content into its thinking and its prose.\n *\n * Returns undefined when the record carried no content array, so the caller can\n * fall back to the writer's flattened `text` rather than treating a shape this\n * does not recognise as an empty turn.\n */\nfunction splitAssistantContent(content: unknown): { thinking: string[]; text: string } | undefined {\n  if (!Array.isArray(content)) return undefined;\n  const thinking: string[] = [];\n  const texts: string[] = [];\n  for (const part of content) {\n    if (!part || typeof part !== 'object') continue;\n    const record = part as Record<string, unknown>;\n    if (record.type === 'thinking') {\n      const value = typeof record.thinking === 'string' ? record.thinking : '';\n      if (value.trim()) thinking.push(value);\n      continue;\n    }\n    // Anything else - toolCall in particular - is represented by its own event,\n    // so it must not be folded into the assistant turn's text.\n    if (record.type === 'text' && typeof record.text === 'string') texts.push(record.text);\n  }\n  return { thinking, text: texts.join('\\n') };\n}\n\nfunction parseArgsPayload(payload: string | undefined): Record<string, unknown> | undefined {\n  if (!payload) return undefined;\n  try {\n    const parsed: unknown = JSON.parse(payload);\n    return isRecord(parsed) ? parsed : undefined;\n  } catch {\n    // The writer bounds this payload, so a long argument set can land here\n    // truncated mid-JSON. The preview still renders; the args just stay absent.\n    return undefined;\n  }\n}\n\nfunction emptyTail(transcriptPath: string, warning?: string): FleetTranscriptTail {\n  return {\n    path: transcriptPath,\n    events: [],\n    byteOffset: 0,\n    size: 0,\n    toolCalls: new Map(),\n    firstDirtyIndex: undefined,\n    droppedEvents: 0,\n    ...(warning ? { warning } : {}),\n  };\n}\n\n/** Read exactly the appended range, so cost tracks what arrived rather than what the file holds. */\nfunction readRange(filePath: string, offset: number, length: number): Buffer {\n  const handle = fs.openSync(filePath, 'r');\n  try {\n    const buffer = Buffer.allocUnsafe(length);\n    let read = 0;\n    while (read < length) {\n      const chunk = fs.readSync(handle, buffer, read, length - read, offset + read);\n      if (chunk <= 0) break;\n      read += chunk;\n    }\n    return read === length ? buffer : buffer.subarray(0, read);\n  } finally {\n    fs.closeSync(handle);\n  }\n}\n\nfunction markDirty(tail: FleetTranscriptTail, index: number): void {\n  if (tail.firstDirtyIndex === undefined || index < tail.firstDirtyIndex) tail.firstDirtyIndex = index;\n}\n\nfunction pushEvent(tail: FleetTranscriptTail, event: FleetTranscriptEvent): number {\n  tail.events.push(event);\n  return tail.events.length - 1;\n}\n\n/** Apply the retention cap, keeping every index that survives it consistent. */\nfunction applyRetention(tail: FleetTranscriptTail): void {\n  const excess = tail.events.length - MAX_RETAINED_EVENTS;\n  if (excess <= 0) return;\n  tail.events.splice(0, excess);\n  tail.droppedEvents += excess;\n  if (tail.firstDirtyIndex !== undefined) tail.firstDirtyIndex = Math.max(0, tail.firstDirtyIndex - excess);\n  for (const [callId, entry] of tail.toolCalls) {\n    const shifted = entry.index - excess;\n    if (shifted < 0) tail.toolCalls.delete(callId);\n    else entry.index = shifted;\n  }\n}\n\nfunction consumeMessage(tail: FleetTranscriptTail, record: RawRecord): void {\n  const at = record.ts ?? 0;\n  if (record.role === 'toolResult') {\n    const entry = record.toolCallId ? tail.toolCalls.get(record.toolCallId) : undefined;\n    // A result whose call fell outside the retained window has nothing to\n    // attach to; the call itself is already gone, so the output would be\n    // unattributable rather than useful.\n    if (!entry) return;\n    entry.event.result = record.text ?? '';\n    entry.event.resultTruncated = record.outputTruncated === true;\n    if (record.isError === true) entry.event.status = 'error';\n    markDirty(tail, entry.index);\n    return;\n  }\n  if (record.role === 'user') {\n    const text = record.text ?? '';\n    if (text.trim()) pushEvent(tail, { kind: 'user', at, text });\n    return;\n  }\n  if (record.role === 'assistant') {\n    const parts = splitAssistantContent(record.message?.content);\n    for (const thinking of parts?.thinking ?? []) pushEvent(tail, { kind: 'thinking', at, text: thinking });\n    const text = parts ? parts.text : (record.text ?? '');\n    // A turn that only thought and called tools has no prose of its own. Both\n    // are already represented, so emitting a header for it says nothing.\n    if (text.trim()) {\n      pushEvent(tail, { kind: 'assistant', at, text, ...(record.model ? { model: record.model } : {}) });\n    }\n    return;\n  }\n  if (record.role === 'custom') {\n    // Host-injected notices (skill suggestions, hook output) are part of what\n    // the child was told, so they belong in the transcript rather than nowhere.\n    const text = record.text ?? '';\n    if (text.trim()) pushEvent(tail, { kind: 'notice', at, text });\n  }\n}\n\nfunction consumeRecord(tail: FleetTranscriptTail, record: RawRecord): void {\n  const at = record.ts ?? 0;\n  if (record.recordType === 'message') return consumeMessage(tail, record);\n  if (record.recordType === 'tool_start') {\n    const args = parseArgsPayload(record.argsPayload);\n    const event: FleetTranscriptEvent = {\n      kind: 'tool',\n      at,\n      text: record.argsPreview ?? '',\n      ...(record.toolName ? { name: record.toolName } : {}),\n      status: 'running',\n      ...(args ? { args } : {}),\n    };\n    const index = pushEvent(tail, event);\n    if (record.toolCallId) tail.toolCalls.set(record.toolCallId, { event, index });\n    return;\n  }\n  if (record.recordType === 'tool_end') {\n    const entry = record.toolCallId ? tail.toolCalls.get(record.toolCallId) : undefined;\n    if (entry) {\n      // An error reported by either half of the call is the call's outcome.\n      entry.event.status = record.isError === true || entry.event.status === 'error' ? 'error' : 'ok';\n      entry.event.endedAt = at;\n      markDirty(tail, entry.index);\n      return;\n    }\n    pushEvent(tail, {\n      kind: 'tool',\n      at,\n      text: '',\n      ...(record.toolName ? { name: record.toolName } : {}),\n      status: record.isError === true ? 'error' : 'ok',\n    });\n    return;\n  }\n  if (record.recordType === 'stdout' || record.recordType === 'stderr') {\n    pushEvent(tail, { kind: record.recordType, at, text: record.text ?? '' });\n  }\n  // 'truncated' carries no displayable content of its own; the events\n  // recorded before it already show what happened up to the cutoff.\n}\n\n/**\n * Read whatever has been appended since `previous`, or the whole file when no\n * resume point is given.\n *\n * Never throws: a missing or unreadable file is a normal state (the run has\n * not started writing yet, or was cleaned up), reported through `warning`\n * rather than an exception the caller would have to guard against.\n */\nexport function readFleetTranscriptTail(transcriptPath: string, previous?: FleetTranscriptTail): FleetTranscriptTail {\n  let size: number;\n  try {\n    size = fs.statSync(transcriptPath).size;\n  } catch (cause) {\n    return emptyTail(transcriptPath, cause instanceof Error ? cause.message : String(cause));\n  }\n\n  // A shrink means the file was replaced rather than appended to, so nothing\n  // parsed from the old one can be trusted to still describe it.\n  const resumable =\n    previous !== undefined &&\n    previous.path === transcriptPath &&\n    previous.warning === undefined &&\n    size >= previous.byteOffset;\n\n  const tail: FleetTranscriptTail = resumable\n    ? { ...previous, size, firstDirtyIndex: undefined, warning: undefined }\n    : emptyTail(transcriptPath);\n  tail.size = size;\n  if (size <= tail.byteOffset) return tail;\n\n  let chunk: Buffer;\n  try {\n    chunk = readRange(transcriptPath, tail.byteOffset, size - tail.byteOffset);\n  } catch (cause) {\n    return { ...tail, warning: cause instanceof Error ? cause.message : String(cause) };\n  }\n\n  // Split at the last newline: 0x0A cannot occur inside a UTF-8 multi-byte\n  // sequence, so this is a byte boundary that is also a character boundary.\n  const lastNewline = chunk.lastIndexOf(NEWLINE_BYTE);\n  const complete = lastNewline === -1 ? undefined : chunk.subarray(0, lastNewline + 1);\n  const remainder = chunk.subarray(lastNewline + 1);\n\n  // A trailing line with no newline after it is ambiguous: either a write\n  // caught mid-flush, or simply the last record of a file the writer did not\n  // terminate. Parsing decides - a half-written record cannot be valid JSON,\n  // since it is missing its closing brace - so a complete record is never\n  // withheld just because nothing followed it, and a partial one is left\n  // unconsumed for the next read to pick up whole.\n  const pending = remainder.length > 0 ? parseLine(remainder.toString('utf-8')) : undefined;\n  tail.byteOffset += (complete?.length ?? 0) + (pending ? remainder.length : 0);\n  if (!complete && !pending) return tail;\n\n  for (const line of complete ? complete.toString('utf-8').split(/\\r?\\n/) : []) {\n    const record = parseLine(line);\n    if (record) consumeRecord(tail, record);\n  }\n  if (pending) consumeRecord(tail, pending);\n  applyRetention(tail);\n  return tail;\n}\n\n/** Whole-file read, for callers with no incremental state to keep. */\nexport function readFleetTranscript(transcriptPath: string): FleetTranscript {\n  const tail = readFleetTranscriptTail(transcriptPath);\n  return tail.warning ? { events: tail.events, warning: tail.warning } : { events: tail.events };\n}\n\n// ============================================================================\n// Rendering\n// ============================================================================\n","/**\n * Plain-text renderings for the `subagent` status action, for the MODEL rather\n * than for a terminal.\n *\n * STATUS CONTRACT:\n * - `{ action: \"status\" }` returns the fleet overview\n * - `{ action: \"status\", id }` returns one run's state\n * - `{ action: \"status\", id, transcriptLines }` returns a bounded transcript tail\n *\n * There is no `view` discriminator. The schema rejects unknown fields, so every\n * recovery example must use one of the exact shapes above.\n *\n * WHY THIS IS NOT `tui/fleet.ts` OR `renderFleetTranscript`:\n * Those exist, they are correct, and they are wired to the `/fleet` slash\n * command, but each takes a `Theme` and emits ANSI escapes for a human reader.\n * A tool result is read by a model, where escape sequences are noise. This\n * module reuses the pure transcript reader and formats model-facing text.\n *\n * DELIBERATELY NOT SUPPORTED: `index`.\n * A fanout child is its own run with its own id, not an index into another run.\n * Accepting and ignoring an index would create a false affordance.\n */\n\nimport { formatAgentIdentity } from '../agentIdentity';\nimport type { AsyncRunStatus } from '../asyncExecution';\nimport type { TrackedAsyncJob } from '../asyncJobTracker';\nimport { formatDuration } from '../displayFormat';\nimport { type FleetTranscriptEvent, readFleetTranscript } from '../fleetTranscript';\nimport { isSuspendedRunResumable, type SuspendedRun } from '../suspendedRuns';\n\n/** Default transcript tail length. Matches the value the tool description has always advertised. */\nexport const DEFAULT_TRANSCRIPT_LINES = 80;\n\nfunction age(job: TrackedAsyncJob, now: number): string {\n  return job.startedAt ? formatDuration(Math.max(0, now - job.startedAt)) : 'unknown';\n}\n\n/**\n * The active-fleet overview: every run this session is tracking, one per line.\n *\n * Takes `now` rather than calling `Date.now()` so a test asserting rendered\n * ages does not have to freeze global time.\n */\nexport function formatFleetView(\n  jobs: TrackedAsyncJob[],\n  now: number = Date.now(),\n  suspended: SuspendedRun[] = [],\n): string {\n  if (jobs.length === 0 && suspended.length === 0) {\n    return 'No runs tracked in this session. A run appears here once it has been launched from this session.';\n  }\n\n  const lines = [`${jobs.length} active run${jobs.length === 1 ? '' : 's'}:`];\n  for (const job of jobs) {\n    // The run id stays the leading token: it is what `{ action: \"status\", id }`\n    // resolves against, and the identity is offered as the friendlier alias.\n    const parts = [`- ${job.runId}`];\n    if (job.identity) parts.push(formatAgentIdentity(job.identity, job.inline)!);\n    parts.push(job.status ?? 'starting', age(job, now));\n    if (job.activityState) parts.push(job.activityState);\n    if (job.attentionReason) parts.push(job.attentionReason);\n    if (job.error) parts.push(`error: ${job.error}`);\n    lines.push(parts.join(' · '));\n  }\n  if (suspended.length > 0) {\n    lines.push('', `${suspended.length} suspended run${suspended.length === 1 ? '' : 's'}:`);\n    for (const run of suspended) {\n      const recovery = isSuspendedRunResumable(run)\n        ? `restore with { action: \"restore\", id: \"${run.runId}\" }`\n        : 'not resumable; submit a new explicit run';\n      const label = formatAgentIdentity(run.identity, run.inline);\n      lines.push(`- ${run.runId} (${label ? `${label}, ` : ''}${run.agent}, ${run.runtime}): ${recovery}`);\n    }\n  }\n  if (jobs.length > 0) {\n    lines.push('');\n    lines.push(`Inspect one with { action: \"status\", id: \"<run id>\", transcriptLines: ${DEFAULT_TRANSCRIPT_LINES} }.`);\n  }\n  return lines.join('\\n');\n}\n\n/** Tool output shown to the model, bounded so one long result cannot crowd out the rest of the tail. */\nconst TOOL_RESULT_PREVIEW_LINES = 5;\n\nfunction formatEvent(event: FleetTranscriptEvent): string {\n  if (event.kind === 'tool') {\n    const status = event.status === 'running' ? '…' : event.status === 'error' ? 'error' : 'ok';\n    const args = event.args ? JSON.stringify(event.args) : event.text;\n    const header = `[tool ${status}] ${event.name ?? 'tool'}${args ? ` ${args}` : ''}`;\n    const result = event.result?.trimEnd();\n    if (!result) return header;\n    // The result is the half the model most needs: it is what the call\n    // actually learned, and it used to be dropped entirely.\n    const body = result.split('\\n');\n    const shown = body.slice(0, TOOL_RESULT_PREVIEW_LINES);\n    const hidden = body.length - shown.length;\n    return [header, ...shown.map((line) => `  ${line}`), hidden > 0 ? `  … +${hidden} lines` : undefined]\n      .filter((line): line is string => line !== undefined)\n      .join('\\n');\n  }\n  return `[${event.kind}] ${event.text}`;\n}\n\n/**\n * A run's transcript tail.\n *\n * Bounded from the END, not the start: a caller asking for 80 lines of a\n * long-running child wants the most recent 80, not the first 80 of its\n * startup. When the window drops anything, the fact that it did is stated,\n * so a reader never mistakes a tail for the whole run.\n */\nexport function formatRunTranscript(status: AsyncRunStatus | undefined, maxLines: number): string {\n  const transcriptPath = status?.transcriptPath;\n  if (!transcriptPath) {\n    return status\n      ? 'This run has no transcript. Artifacts were disabled for it (artifacts: false), so nothing was recorded.'\n      : 'No status found for this run, so there is no transcript to read.';\n  }\n\n  const transcript = readFleetTranscript(transcriptPath);\n  if (transcript.warning) {\n    return `Transcript at '${transcriptPath}' could not be read: ${transcript.warning}`;\n  }\n  if (transcript.events.length === 0) {\n    return `Transcript at '${transcriptPath}' is empty. The run has not written anything yet.`;\n  }\n\n  const rendered = transcript.events.flatMap((event) => formatEvent(event).split('\\n'));\n  const kept = rendered.slice(-maxLines);\n  const dropped = rendered.length - kept.length;\n  const header =\n    dropped > 0\n      ? `Last ${kept.length} of ${rendered.length} transcript lines (${dropped} earlier line(s) not shown):`\n      : `Transcript (${kept.length} line(s)):`;\n  return [header, '', ...kept].join('\\n');\n}\n","import { randomUUID } from 'node:crypto';\n\nimport { resolveRootSessionId } from '@agimon-ai/doompi-core/childProcess';\nimport type { AgentToolResult } from '@earendil-works/pi-agent-core';\nimport type { ExtensionContext } from '@earendil-works/pi-coding-agent';\n\nimport {\n  normalizeSubagentToolParams,\n  SUBAGENT_ACTION_FIELDS,\n  SUBAGENT_ACTIONS,\n  type SubagentAction,\n  type SubagentToolParams,\n} from '../../schemas/subagentTool';\nimport type { AgentConfig, AgentScope, AgentDiscoveryContract } from '../../types/agent';\nimport { formatAgentIdentity } from '../agentIdentity';\nimport { agentHasWriteTools } from '../agentMemory';\nimport { type AsyncJobTrackerContract, resolveTrackedRunId } from '../asyncJobTracker';\nimport { loadConfig } from '../config';\nimport { DoomTeamExpectedError, invalidRequest } from '../errors';\nimport type { ManagementActionsContract, StatusActionResult } from '../managementActions';\nimport { normalizeParentModel } from '../modelFallback';\nimport { authenticatedModelInfos } from '../modelResolution';\nimport { completeOperation, startOperation } from '../operationJournal';\nimport { isPiRuntime } from '../runtimeRegistry';\nimport { createSessionScope, type SessionScope } from '../sessionPaths';\nimport {\n  captureSessionForkSource,\n  forkRequestFields,\n  type SpawnPlannerContract,\n  type SpawnPlanRequest,\n  type SpawnPlanResult,\n} from '../spawnPlan';\nimport { DEFAULT_TRANSCRIPT_LINES, formatFleetView, formatRunTranscript } from '../statusViews';\nimport {\n  clearSuspendedRun,\n  formatSuspendedRuns,\n  isSuspendedRunResumable,\n  listSuspendedRuns,\n  type SuspendedRun,\n} from '../suspendedRuns';\n\nexport const SUBAGENT_TOOL_NAME = 'subagent';\nexport const IMPLEMENTED_SUBAGENT_ACTIONS: ReadonlySet<string> = new Set(Object.values(SUBAGENT_ACTIONS));\n\nexport type SubagentToolDetails = Record<string, unknown>;\n\nfunction textResult<T extends SubagentToolDetails>(text: string, details: T): AgentToolResult<T> {\n  return { content: [{ type: 'text', text }], details };\n}\n\nfunction progressResult(text: string, action: SubagentAction): AgentToolResult<SubagentToolDetails> {\n  return textResult(text, { action, partial: true });\n}\n\nfunction progressMessage(params: SubagentToolParams): string | undefined {\n  switch (params.action) {\n    case SUBAGENT_ACTIONS.run:\n      return `Starting ${params.requests.length} subagent${params.requests.length === 1 ? '' : 's'}...`;\n    case SUBAGENT_ACTIONS.steer:\n      return `Steering subagent ${params.id}...`;\n    case SUBAGENT_ACTIONS.stop:\n      return `Requesting stop for subagent ${params.id}...`;\n    case SUBAGENT_ACTIONS.restore:\n      return `Restoring subagent ${params.id}...`;\n    default:\n      return undefined;\n  }\n}\n\nfunction scopeOrDefault(scope: AgentScope | undefined): AgentScope {\n  return scope ?? 'both';\n}\n\n/** The agent roster, as the model reads it. Shared with the headless tool so both hosts word it alike. */\nexport function formatAgentList(agents: AgentConfig[]): string {\n  return [\n    'Executable agents:',\n    ...(agents.length\n      ? agents\n          .toSorted((left, right) => left.name.localeCompare(right.name))\n          .map((agent) => `- ${agent.name} (${agent.source}): ${agent.description}`)\n      : ['- (none)']),\n  ].join('\\n');\n}\n\n/**\n * The fields of an agent a caller may see. Deliberately not the whole\n * `AgentConfig`: `systemPrompt` and `filePath` are ours, not the model's.\n */\nexport function publicAgent(agent: AgentConfig): Record<string, unknown> {\n  const tools = [...(agent.tools ?? []), ...(agent.mcpDirectTools ?? []).map((tool) => `mcp:${tool}`)];\n  return {\n    name: agent.name,\n    source: agent.source,\n    description: agent.description,\n    runtime: agent.runtime ?? 'pi',\n    writeCapable: agentHasWriteTools(agent),\n    ...(agent.model ? { model: agent.model } : {}),\n    ...(agent.fallbackModels?.length ? { fallbackModels: agent.fallbackModels } : {}),\n    ...(tools.length ? { tools } : {}),\n  };\n}\n\nfunction publicSuspendedRun(run: SuspendedRun): SuspendedRun & { resumable: boolean } {\n  return { ...run, resumable: isSuspendedRunResumable(run) };\n}\n\n/** One agent in full, as the model reads it. Shared with the headless tool. */\nexport function formatAgentDetail(agent: AgentConfig): string {\n  const detail = publicAgent(agent);\n  return [\n    `Agent: ${agent.name} (${agent.source})`,\n    `Description: ${agent.description}`,\n    `Runtime: ${String(detail.runtime)}`,\n    `Write capable: ${detail.writeCapable ? 'yes' : 'no'}`,\n    ...(agent.model ? [`Model: ${agent.model}`] : []),\n    ...(Array.isArray(detail.tools) ? [`Tools: ${detail.tools.join(', ')}`] : []),\n  ].join('\\n');\n}\n\nfunction requireNonblank(record: Record<string, unknown>, field: string, action: string): void {\n  if (typeof record[field] !== 'string' || !record[field].trim()) {\n    throw invalidRequest(`action='${action}' requires nonblank '${field}'.`, 'Correct the request and retry.');\n  }\n}\n\nexport function validateParams(input: unknown): SubagentToolParams {\n  const raw = normalizeSubagentToolParams(input);\n  if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {\n    throw invalidRequest('subagent parameters must be an object.', 'Call subagent with one documented action shape.');\n  }\n  const record = raw as Record<string, unknown>;\n  const action = record.action;\n  if (typeof action !== 'string' || !IMPLEMENTED_SUBAGENT_ACTIONS.has(action)) {\n    throw invalidRequest(\n      `Unsupported or missing subagent action ${JSON.stringify(action)}.`,\n      `Use one of: ${[...IMPLEMENTED_SUBAGENT_ACTIONS].join(', ')}.`,\n    );\n  }\n  const allowed = SUBAGENT_ACTION_FIELDS[action as SubagentAction] as readonly string[];\n  const unknown = Object.keys(record).filter((field) => !allowed.includes(field));\n  if (unknown.length) {\n    throw invalidRequest(\n      `action='${action}' does not accept: ${unknown.join(', ')}.`,\n      'Remove unknown fields and retry.',\n    );\n  }\n  if (action === SUBAGENT_ACTIONS.run && (!Array.isArray(record.requests) || record.requests.length === 0)) {\n    throw invalidRequest(\"action='run' requires a nonempty 'requests' array.\", 'Add at least one agent and task.');\n  }\n  if (action === SUBAGENT_ACTIONS.steer) {\n    requireNonblank(record, 'id', action);\n    requireNonblank(record, 'message', action);\n  }\n  if (action === SUBAGENT_ACTIONS.stop || action === SUBAGENT_ACTIONS.restore) requireNonblank(record, 'id', action);\n  return raw as SubagentToolParams;\n}\n\nexport interface SubagentToolContract {\n  execute(\n    id: string,\n    rawParams: unknown,\n    signal: AbortSignal | undefined,\n    onUpdate: ((result: AgentToolResult<SubagentToolDetails>) => void) | undefined,\n    ctx: ExtensionContext,\n  ): Promise<AgentToolResult<SubagentToolDetails>>;\n}\n\nexport class SubagentToolService implements SubagentToolContract {\n  constructor(\n    private readonly planner: SpawnPlannerContract,\n    private readonly management: ManagementActionsContract,\n    private readonly tracker: AsyncJobTrackerContract,\n    private readonly discovery: AgentDiscoveryContract,\n    private readonly environment: Readonly<Record<string, string | undefined>>,\n  ) {}\n\n  private sessionScope(ctx: ExtensionContext): SessionScope {\n    return createSessionScope(resolveRootSessionId(ctx.sessionManager.getSessionId(), this.environment));\n  }\n\n  private trackOutcomes(result: SpawnPlanResult, ctx: ExtensionContext): SpawnPlanResult {\n    const scope = this.sessionScope(ctx);\n    this.management.bindSessionScope(scope);\n    const jobs = this.tracker.forSession(ctx.sessionManager.getSessionId(), scope);\n    for (const outcome of result.outcomes) {\n      if (outcome.runId) {\n        jobs.track(\n          outcome.runId,\n          outcome.identity ? { identity: outcome.identity, inline: outcome.inline ?? false } : undefined,\n        );\n      }\n    }\n    return result;\n  }\n\n  private buildSpawnRequest(\n    operationId: string,\n    params: Extract<SubagentToolParams, { action: 'run' }>,\n    ctx: ExtensionContext,\n    preallocatedRunIds: string[],\n  ): SpawnPlanRequest {\n    const tasks = params.requests.map((request) => {\n      if (!request.agent.trim() || !request.task.trim()) {\n        throw invalidRequest(\n          'Every run request requires nonblank agent and task values.',\n          'Correct the request and retry.',\n        );\n      }\n      return {\n        agent: request.agent.trim(),\n        ...(request.inlineAgent ? { inlineAgent: request.inlineAgent } : {}),\n        task: request.task.trim(),\n        ...(request.cwd ? { cwd: request.cwd } : {}),\n        ...(request.model ? { model: request.model } : {}),\n        ...(request.runtime ? { runtime: request.runtime } : {}),\n      };\n    });\n    const parentForkSource = captureSessionForkSource(ctx.sessionManager, 'tool');\n    const parentModel = normalizeParentModel(ctx.model);\n    const scope = this.sessionScope(ctx);\n    return {\n      tasks,\n      cwd: ctx.cwd,\n      agentScope: scopeOrDefault(params.scope),\n      sessionScope: scope,\n      parentSessionId: ctx.sessionManager.getSessionId(),\n      ...forkRequestFields(parentForkSource),\n      ...(params.concurrency !== undefined ? { concurrency: params.concurrency } : {}),\n      ...(params.artifacts !== undefined ? { artifacts: params.artifacts } : {}),\n      availableModels: authenticatedModelInfos(ctx.modelRegistry),\n      ...(parentModel ? { parentModel } : {}),\n      operationId,\n      preallocatedRunIds,\n    };\n  }\n\n  private async executeRun(\n    operationId: string,\n    params: Extract<SubagentToolParams, { action: 'run' }>,\n    ctx: ExtensionContext,\n  ): Promise<AgentToolResult<SubagentToolDetails>> {\n    const scope = this.sessionScope(ctx);\n    this.management.bindSessionScope(scope);\n    const operation = startOperation<AgentToolResult<SubagentToolDetails>>(\n      scope,\n      operationId,\n      params,\n      params.requests.map(() => randomUUID()),\n    );\n    if (operation.kind === 'replay') {\n      if (operation.record.state === 'completed' && operation.record.result) return operation.record.result;\n      throw new DoomTeamExpectedError(\n        'delivery_unconfirmed',\n        `Operation '${operationId}' is already pending for runs: ${operation.record.runIds.join(', ')}.`,\n        true,\n        'Call subagent({\"action\":\"status\"}) and do not submit the run again.',\n      );\n    }\n    const result = this.trackOutcomes(\n      await this.planner.spawn(\n        this.buildSpawnRequest(operationId, params, ctx, operation.record.runIds),\n        loadConfig().config,\n      ),\n      ctx,\n    );\n    const started = result.outcomes.filter((outcome) => outcome.runId);\n    const failed = result.outcomes.filter((outcome) => !outcome.runId);\n    const outcomeLines = result.outcomes.map((outcome) => {\n      const label = formatAgentIdentity(outcome.identity, outcome.inline) ?? outcome.agent;\n      const result = outcome.runId ? outcome.runId : `failed: ${outcome.error ?? 'unknown error'}`;\n      return `- ${label}: ${result}${outcome.warning ? `\\n  Warning: ${outcome.warning}` : ''}`;\n    });\n    if (started.length === 0 && failed.length > 0) {\n      throw new DoomTeamExpectedError(\n        'runtime_unavailable',\n        `No requested subagent started.\\n${outcomeLines.join('\\n')}`,\n        true,\n        'Correct the reported launch failures. If an agent name is uncertain, call subagent({\"action\":\"agents\"}) before retrying only corrected requests.',\n      );\n    }\n    const subagentLabel = result.outcomes.length === 1 ? 'subagent' : 'subagents';\n    const summary =\n      failed.length === 0\n        ? `Started ${started.length} ${subagentLabel}:`\n        : `Started ${started.length}/${result.outcomes.length} ${subagentLabel}; ${failed.length} failed:`;\n    const next =\n      failed.length === 0\n        ? 'Completion will arrive asynchronously. Continue only non-overlapping work, or end your turn.'\n        : 'Completion will arrive asynchronously for started runs. Do not resubmit them; retry only corrected failed entries.';\n    const response = textResult([summary, ...outcomeLines, '', next].join('\\n'), {\n      spawn: result,\n      started: started.length,\n      failed: failed.length,\n    });\n    completeOperation(scope, operationId, operation.record, response);\n    return response;\n  }\n\n  private executeAgents(\n    params: Extract<SubagentToolParams, { action: 'agents' }>,\n    ctx: ExtensionContext,\n  ): AgentToolResult<SubagentToolDetails> {\n    const cwd = params.cwd ?? ctx.cwd;\n    const scope = scopeOrDefault(params.scope);\n    if (!params.name) {\n      const result = this.discovery.discover(cwd, scope);\n      return textResult(formatAgentList(result.agents), { agents: result.agents.map(publicAgent) });\n    }\n    const agent = this.discovery.find(cwd, scope, params.name);\n    if (!agent) {\n      const candidates = this.discovery\n        .discover(cwd, scope)\n        .agents.map((candidate) => candidate.name)\n        .toSorted();\n      throw new DoomTeamExpectedError(\n        'agent_not_found',\n        `No executable agent matches '${params.name}'.${candidates.length ? ` Available: ${candidates.join(', ')}.` : ''}`,\n        false,\n        'Call subagent({\"action\":\"agents\"}) and retry with an exact name.',\n      );\n    }\n    return textResult(formatAgentDetail(agent), { agent: publicAgent(agent) });\n  }\n\n  private async executeManagement(\n    params: Exclude<SubagentToolParams, { action: 'run' } | { action: 'agents' }>,\n    ctx: ExtensionContext,\n    signal?: AbortSignal,\n    preallocatedRunIds?: string[],\n    operationId?: string,\n  ): Promise<AgentToolResult<SubagentToolDetails>> {\n    const scope = this.sessionScope(ctx);\n    this.management.bindSessionScope(scope);\n    const jobs = this.tracker.forSession(ctx.sessionManager.getSessionId(), scope);\n    switch (params.action) {\n      case SUBAGENT_ACTIONS.status: {\n        const suspendedRuns = listSuspendedRuns(scope);\n        if (!('id' in params)) {\n          if ('transcriptLines' in params && params.transcriptLines !== undefined) {\n            throw invalidRequest(\n              'transcriptLines requires a run id.',\n              'Add id or omit transcriptLines for fleet status.',\n            );\n          }\n          const runs = jobs.list();\n          return textResult(formatFleetView(runs, Date.now(), suspendedRuns), {\n            fleet: runs,\n            suspended: suspendedRuns.map(publicSuspendedRun),\n          });\n        }\n        const runId = params.id;\n        if (!runId) {\n          throw invalidRequest(\n            'transcriptLines requires a run id.',\n            'Add id or omit transcriptLines for fleet status.',\n          );\n        }\n        const suspended = suspendedRuns.find((run) => run.runId === runId);\n        if (suspended && params.transcriptLines === undefined) {\n          const resumable = isSuspendedRunResumable(suspended);\n          const recovery = resumable\n            ? `Restore it with { action: \"restore\", id: \"${suspended.runId}\" }.`\n            : 'It is not resumable; submit a new explicit run.';\n          return textResult(`Run '${suspended.runId}' is suspended. ${recovery}`, {\n            suspended: publicSuspendedRun(suspended),\n          });\n        }\n        const result: StatusActionResult = this.management.status(runId);\n        if (!result.status && !result.runDir && !result.resultPath && !suspended) {\n          throw new DoomTeamExpectedError(\n            'run_not_found',\n            `No run matches '${runId}'.`,\n            false,\n            'Call subagent({\"action\":\"status\"}) and retry with an exact id.',\n          );\n        }\n        if (params.transcriptLines !== undefined) {\n          return textResult(formatRunTranscript(result.status, params.transcriptLines ?? DEFAULT_TRANSCRIPT_LINES), {\n            transcript: { runId: result.runId },\n          });\n        }\n        return textResult(\n          result.status ? `Run '${result.runId}': ${result.status.state}` : `Run '${result.runId}' has no status yet.`,\n          { status: result },\n        );\n      }\n      case SUBAGENT_ACTIONS.stop: {\n        const id = resolveTrackedRunId(jobs, params.id);\n        const result = await this.management.stop(id, params.reason);\n        return textResult(`Stop requested for '${id}'.`, { control: result });\n      }\n      case SUBAGENT_ACTIONS.steer: {\n        const id = resolveTrackedRunId(jobs, params.id);\n        const runtime = jobs.get(id)?.runtime;\n        if (runtime && !isPiRuntime(runtime)) {\n          throw new DoomTeamExpectedError(\n            'unsupported_operation',\n            `Run '${id}' uses '${runtime}', which does not support steering.`,\n            false,\n            `Use subagent({\"action\":\"stop\",\"id\":\"${id}\"}) to terminate it.`,\n          );\n        }\n        const result = await this.management.steer(id, params.message, undefined, signal);\n        return textResult(`Steer request '${result.requestId}' for '${id}' is ${result.state}: ${result.message}`, {\n          steer: result,\n        });\n      }\n      case SUBAGENT_ACTIONS.suspended: {\n        const runs = listSuspendedRuns(scope);\n        return textResult(runs.length ? formatSuspendedRuns(runs) : 'No suspended subagents in this session.', {\n          suspended: runs.map(publicSuspendedRun),\n        });\n      }\n      case SUBAGENT_ACTIONS.restore: {\n        const record = listSuspendedRuns(scope).find((run) => run.runId === params.id);\n        if (!record) {\n          throw new DoomTeamExpectedError(\n            'run_not_found',\n            `No suspended run matches '${params.id}'.`,\n            false,\n            'Call subagent({\"action\":\"suspended\"}) and retry with an exact id.',\n          );\n        }\n        if (!isSuspendedRunResumable(record)) {\n          throw new DoomTeamExpectedError(\n            'not_resumable',\n            `Suspended run '${params.id}' does not have complete, readable Pi recovery state.`,\n            false,\n            'Submit a new explicit run request instead of restoring this record.',\n          );\n        }\n        const result = this.trackOutcomes(\n          await this.planner.spawn(\n            {\n              single: {\n                agent: record.agent,\n                ...(record.inlineAgent ? { inlineAgent: record.inlineAgent } : {}),\n                task: record.task,\n                cwd: record.cwd,\n                ...(record.model ? { model: record.model } : {}),\n                sessionFile: record.sessionFile,\n                // Carried in so the restored run keeps the identity peers\n                // already know, instead of minting a second one.\n                ...(record.identity ? { identity: record.identity } : {}),\n              },\n              cwd: record.cwd,\n              agentScope: 'both',\n              sessionScope: scope,\n              parentSessionId: ctx.sessionManager.getSessionId(),\n              availableModels: authenticatedModelInfos(ctx.modelRegistry),\n              ...(operationId ? { operationId } : {}),\n              ...(preallocatedRunIds ? { preallocatedRunIds } : {}),\n            },\n            loadConfig().config,\n          ),\n          ctx,\n        );\n        const outcome = result.outcomes[0];\n        if (!outcome?.runId) {\n          throw new DoomTeamExpectedError(\n            'not_resumable',\n            `Could not restore '${params.id}': ${outcome?.error ?? 'the spawn produced no run.'}`,\n            true,\n            'Inspect suspended state, then submit a new explicit run if recovery is not possible.',\n          );\n        }\n        clearSuspendedRun(scope, params.id);\n        const restoredAs = formatAgentIdentity(outcome.identity, outcome.inline) ?? outcome.runId;\n        return textResult(`Restored '${params.id}' as '${restoredAs}' (${outcome.runId}), continuing its transcript.`, {\n          restore: { ...outcome, restoredFrom: params.id },\n        });\n      }\n    }\n  }\n\n  async execute(\n    id: string,\n    rawParams: unknown,\n    signal: AbortSignal | undefined,\n    onUpdate: ((result: AgentToolResult<SubagentToolDetails>) => void) | undefined,\n    ctx: ExtensionContext,\n  ): Promise<AgentToolResult<SubagentToolDetails>> {\n    const params = validateParams(rawParams);\n    const progress = progressMessage(params);\n    if (progress) onUpdate?.(progressResult(progress, params.action));\n    if (params.action === SUBAGENT_ACTIONS.run) return this.executeRun(id, params, ctx);\n    if (params.action === SUBAGENT_ACTIONS.agents) return this.executeAgents(params, ctx);\n    const journaled =\n      params.action === SUBAGENT_ACTIONS.steer ||\n      params.action === SUBAGENT_ACTIONS.stop ||\n      params.action === SUBAGENT_ACTIONS.restore;\n    if (!journaled) return this.executeManagement(params, ctx, signal);\n\n    const scope = this.sessionScope(ctx);\n    this.management.bindSessionScope(scope);\n    const operation = startOperation<AgentToolResult<SubagentToolDetails>>(\n      scope,\n      id,\n      params,\n      params.action === SUBAGENT_ACTIONS.restore ? [randomUUID()] : [],\n    );\n    if (operation.kind === 'replay') {\n      if (operation.record.state === 'completed' && operation.record.result) return operation.record.result;\n      throw new DoomTeamExpectedError(\n        'delivery_unconfirmed',\n        `Operation '${id}' is already pending.`,\n        true,\n        'Inspect run status before retrying this control operation.',\n      );\n    }\n    const response = await this.executeManagement(params, ctx, signal, operation.record.runIds, id);\n    completeOperation(scope, id, operation.record, response);\n    return response;\n  }\n}\n","/**\n * Blocks a turn until one or more tracked async runs finish, need attention,\n * or a timeout elapses - resolving with a status snapshot every time.\n *\n * WHY THIS IS A REDESIGN, NOT A PORT:\n * `doom-pi-subagents/src/runs/background/subagentWait.ts` is 686 lines\n * because it also waits on remembered detached FOREGROUND runs (reading\n * child transcripts byte-range-tailed off disk to render a live preview) and\n * session-scoped background-work PROVIDER items (a separate registration\n * protocol with its own wake channels), on top of async runs. This package is\n * async-only - there is no foreground run mode, and no provider protocol has\n * been ported (see `spawnHandshake.ts`'s header for the same \"async-only\"\n * framing applied elsewhere). Waiting on either would be dead code with\n * nothing to ever populate it. Only the async-run wait survives, rebuilt\n * against what this package actually has.\n *\n * COMPOSITION, NOT REIMPLEMENTATION:\n * `status.json` has one writer (`CoalescedStatusWriter`) and several\n * legitimate readers; this module is not a new one. It reads run state\n * exclusively through `AsyncJobTracker`, which is a push-updated in-memory\n * cache: `ExternalProcessIpc` events and `NativeRunCoordinator` write into it\n * (see `services/teamRuntime`), and it owns no poll loop and no `PollScheduler`\n * subscription. `wait()` never touches `node:fs` and registers no\n * `PollScheduler` subscription of its own - see \"WHY A PRIVATE POLL LOOP\"\n * below for why it still owns a short-lived timer despite that.\n *\n * TARGET SHAPE - `{ id } | { ids } | { all: true }`:\n * One run, several, or every run `AsyncJobTracker` currently has tracked\n * (`list()` IS that set - whatever the run's own spawn path called `track()`\n * for is what \"outstanding\" means here; this module does not independently\n * decide what counts as outstanding). An `id`/`ids` entry not yet tracked is\n * tracked on the caller's behalf, mirroring `track()`'s own idempotent-refresh\n * contract, so a caller does not have to track before it can wait.\n *\n * RETURN-ON-FIRST, NOT WAIT-FOR-ALL:\n * `wait()` resolves the moment ANY targeted run satisfies `waitFor`, not once\n * every targeted run does. This is a deliberate judgement call, not something\n * spelled out in the brief, and it is the more expressive of the two shapes:\n * wait-for-all composes out of return-on-first (call `wait()` again for\n * whatever remains in `WaitOutcome.runs` that has not yet satisfied\n * `waitFor`), but the reverse does not hold - if wait-for-all were the\n * primitive, a caller that wants the NEXT completion (the predecessor's own\n * rolling-replacement fleet-manager loop: wait for one, spawn its\n * replacement, wait again) could only get it by polling. Choosing the shape\n * that does not foreclose the other is why this is return-on-first rather\n * than a use case that happened to need it; the fleet-manager loop is\n * evidence the choice is usable, not the reason for it. If a real caller\n * turns up needing true wait-for-all-at-once as a single call, that is a\n * reason to add it later, built on top of this primitive.\n *\n * TIMEOUT IS A SNAPSHOT, NOT AN ERROR:\n * `wait()` always resolves; it never rejects for a mere timeout. Waiting\n * longer than asked is a normal outcome of an async system, and forcing every\n * caller into a `try`/`catch` for it is how a real error (a thrown bug) ends\n * up caught and swallowed right alongside it - the same reasoning\n * `SpawnHandshake`'s header gives for its own three-outcome, all-resolved\n * design. `WaitOutcome.reason` is `'timeout'`; the caller decides what to do\n * with `WaitOutcome.runs`, which is populated on every path, including this one.\n *\n * `'attention'` MUST WIN EARLY - THE POINT OF THIS INTERNAL SERVICE:\n * `DeliverableGuard.evaluate()` computes `activityState: 'needs_attention'`\n * and `reason: 'missing-deliverable'` after a failed nudge, but has no\n * standing to write `status.json` itself (see its own header). Once whatever\n * calls `evaluate()` folds that result into `status.json` through\n * `CoalescedStatusWriter` - the run's own runner main loop, not yet built -\n * `AsyncJobTracker` picks the fields up on its next poll (see that module's\n * own header note on this), and THIS module is what lets a caller that is\n * blocked in `wait()` ever find out, instead of only discovering it by\n * polling `subagent({ action: \"status\" })` in a loop. `waitFor: 'attention'`\n * returns the instant any targeted run's `activityState` is\n * `'needs_attention'`, before its timeout, before it would ever go terminal.\n * `waitFor: 'completion'` deliberately does the opposite - it waits THROUGH\n * attention, for a caller (an auto-drain loop) that wants to know about\n * results, not about a mid-flight nudge. `'any'` (the default) returns on\n * whichever comes first, matching the predecessor's default behaviour.\n *\n * WHY A PRIVATE POLL LOOP, NOT A SECOND `PollScheduler` SUBSCRIPTION:\n * `PollScheduler` is for long-lived subscribers that back off toward a shared\n * idle ceiling; `wait()` is the opposite shape, a short-lived, bounded call\n * that needs a TIGHT interval for its whole (short) life, the same reasoning\n * `SpawnHandshake`'s header gives for not registering with it either. The loop\n * here only ever reads `AsyncJobTracker`'s already-cached, in-memory state\n * (no `node:fs`, no disk I/O of its own), so polling it every\n * `pollIntervalMs` costs a handful of `Map` reads, not a filesystem round trip.\n *\n * WHY NO EVENT-BUS WAKE (dropped from the predecessor):\n * The predecessor wakes early on `pi.events` firing (an `ExtensionAPI` event\n * bus this package has not built) and otherwise falls back to a fixed poll.\n * With no bus to wake on, this module is poll-only - which is exactly the\n * fallback path the predecessor already had to support for when its own bus\n * was unavailable, so there is no new failure mode here, only a narrower one.\n *\n * AVOID:\n * - Reading `status.json` directly. If a field `wait()` needs is missing from\n *   `TrackedAsyncJob`, that is a reason to extend `AsyncJobTracker` (see its\n *   header's note on `activityState`/`attentionReason` for the last time this\n *   happened), not to open a second read path around it\n * - Treating a run id that was never tracked and has no readable `status.json`\n *   the same as one that is merely slow. `wait()` resolves `'no-active-runs'`\n *   immediately when NONE of the targeted ids ever resolve to a known status,\n *   rather than waiting out the full timeout on nothing\n */\n\nimport type { ActivityState } from '../../types';\nimport type { AsyncJobTrackerContract, TrackedAsyncJobsContract } from '../asyncJobTracker';\nimport type { SessionScope } from '../sessionPaths';\n\n/** States `AsyncJobTracker` (mirroring `staleRunReconciler.ts`) treats as finished. */\nconst TERMINAL_STATES: ReadonlySet<string> = new Set(['complete', 'completed', 'failed', 'paused', 'stopped']);\n\nconst DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;\nconst DEFAULT_POLL_INTERVAL_MS = 250;\nexport type WaitTarget = { id: string } | { ids: string[] } | { all: true };\n\nexport type WaitForMode = 'completion' | 'attention' | 'any';\n\nexport interface WaitRequest {\n  target: WaitTarget;\n  /** Explicit Pi session and immutable owner scope for the targeted run collection. */\n  sessionId: string;\n  sessionScope: SessionScope;\n  /** Defaults to `'any'`. */\n  waitFor?: WaitForMode;\n  /** Defaults to 30 minutes. */\n  timeoutMs?: number;\n  /** Resolves early with `reason: 'aborted'` when this fires. */\n  signal?: AbortSignal;\n}\n\nexport type WaitReason = 'completed' | 'attention' | 'timeout' | 'aborted' | 'no-active-runs';\n\n/** One targeted run's state at the moment `wait()` resolved. */\nexport interface WaitRunSnapshot {\n  runId: string;\n  /** `undefined` when this run has never had a readable `status.json`. */\n  status: string | undefined;\n  activityState?: ActivityState;\n  /** Present alongside `activityState: 'needs_attention'`, e.g. `'missing-deliverable'`. */\n  attentionReason?: string;\n  error?: string;\n  startedAt?: number;\n  updatedAt?: number;\n}\n\nexport interface WaitOutcome {\n  reason: WaitReason;\n  elapsedMs: number;\n  /** Every targeted run's snapshot, regardless of `reason` - populated even on `'timeout'`. */\n  runs: WaitRunSnapshot[];\n}\n\nexport type SubagentWaiterContract = {\n  wait(request: WaitRequest): Promise<WaitOutcome>;\n};\n\nfunction snapshotFrom(runId: string, job: ReturnType<TrackedAsyncJobsContract['get']>): WaitRunSnapshot {\n  if (!job) return { runId, status: undefined };\n  return {\n    runId: job.runId,\n    status: job.status,\n    activityState: job.activityState,\n    attentionReason: job.attentionReason,\n    error: job.error,\n    startedAt: job.startedAt,\n    updatedAt: job.updatedAt,\n  };\n}\n\nfunction isTerminal(snapshot: WaitRunSnapshot): boolean {\n  return snapshot.status !== undefined && TERMINAL_STATES.has(snapshot.status);\n}\n\nfunction needsAttention(snapshot: WaitRunSnapshot): boolean {\n  return snapshot.activityState === 'needs_attention';\n}\n\nfunction satisfies(snapshot: WaitRunSnapshot, waitFor: WaitForMode): boolean {\n  if (waitFor === 'attention') return needsAttention(snapshot);\n  if (waitFor === 'completion') return isTerminal(snapshot);\n  return needsAttention(snapshot) || isTerminal(snapshot);\n}\n\n/** For `waitFor: 'any'` only: which condition actually satisfied it. Attention wins when both happen to be true, since it is the more actionable signal. */\nfunction reasonFor(snapshot: WaitRunSnapshot): WaitReason {\n  return needsAttention(snapshot) ? 'attention' : 'completed';\n}\n\nexport class SubagentWaiter implements SubagentWaiterContract {\n  constructor(private readonly tracker: AsyncJobTrackerContract) {}\n\n  /**\n   * Runtime tuning seams for tests, kept out of the dependency constructor.\n   */\n  protected readonly pollIntervalMs: number = DEFAULT_POLL_INTERVAL_MS;\n  protected readonly defaultTimeoutMs: number = DEFAULT_TIMEOUT_MS;\n\n  protected now(): number {\n    return Date.now();\n  }\n\n  /** Sleep seam so a test can drive this with fake timers without a real delay. */\n  protected sleep(ms: number): Promise<void> {\n    return new Promise((resolve) => {\n      const timer = setTimeout(resolve, ms);\n      timer.unref?.();\n    });\n  }\n\n  async wait(request: WaitRequest): Promise<WaitOutcome> {\n    const startedAt = this.now();\n    const timeoutMs =\n      request.timeoutMs !== undefined && request.timeoutMs > 0 ? request.timeoutMs : this.defaultTimeoutMs;\n    const waitFor = request.waitFor ?? 'any';\n\n    const jobs = this.tracker.forSession(request.sessionId, request.sessionScope);\n    const runIds = this.resolveTargetIds(request.target, jobs);\n    for (const runId of runIds) jobs.track(runId);\n\n    const elapsed = (): number => this.now() - startedAt;\n    const snapshotAll = (): WaitRunSnapshot[] => runIds.map((runId) => snapshotFrom(runId, jobs.get(runId)));\n\n    if (runIds.length === 0) {\n      return { reason: 'no-active-runs', elapsedMs: 0, runs: [] };\n    }\n\n    const initialRuns = snapshotAll();\n    if (initialRuns.every((snapshot) => snapshot.status === undefined)) {\n      return { reason: 'no-active-runs', elapsedMs: elapsed(), runs: initialRuns };\n    }\n\n    for (;;) {\n      const runs = snapshotAll();\n      const satisfied = runs.find((snapshot) => satisfies(snapshot, waitFor));\n      if (satisfied) {\n        // The label reflects what `waitFor` actually asked for, not merely\n        // whatever the snapshot happens to carry: a run that is BOTH terminal\n        // and (independently) still flagged needs_attention must still report\n        // 'completed' for `waitFor: 'completion'`, since attention was never\n        // part of what that mode was watching for.\n        const reason: WaitReason =\n          waitFor === 'completion' ? 'completed' : waitFor === 'attention' ? 'attention' : reasonFor(satisfied);\n        return { reason, elapsedMs: elapsed(), runs };\n      }\n      if (request.signal?.aborted) {\n        return { reason: 'aborted', elapsedMs: elapsed(), runs };\n      }\n      if (elapsed() >= timeoutMs) {\n        return { reason: 'timeout', elapsedMs: elapsed(), runs };\n      }\n      await this.sleep(Math.min(this.pollIntervalMs, Math.max(0, timeoutMs - elapsed())));\n    }\n  }\n\n  private resolveTargetIds(target: WaitTarget, jobs: TrackedAsyncJobsContract): string[] {\n    if ('id' in target) return [target.id];\n    if ('ids' in target) return target.ids;\n    return jobs.list().map((job) => job.runId);\n  }\n}\n","/**\n * Explicit composition for the parent Team extension process.\n *\n * The object graph is deliberately built in one place. Cordis owns the\n * adapter plugin that creates this graph; the graph itself contains ordinary\n * TypeScript objects with constructor-declared dependencies.\n */\n\nimport type { DoomChildSessionServiceProvider } from '@agimon-ai/doompi-core/childSession';\n\nimport { SubagentCapabilityPolicyStore } from '../../schemas/team/capabilityCeiling';\nimport { AdmissionGate } from '../admissionGate';\nimport { AgentDiscoveryService } from '../agentDiscovery';\nimport { SkillDiscoveryService } from '../agentSkills';\nimport { AsyncSubagentSpawner } from '../asyncExecution';\nimport { AsyncJobTracker, TERMINAL_ASYNC_JOB_STATES } from '../asyncJobTracker';\nimport { ExternalProcessIpc, type ExternalProcessEvent } from '../externalProcessIpc';\nimport { ManagementActions } from '../managementActions';\nimport { McpDirectToolResolverBinding } from '../mcpDirectToolAllowlist';\nimport { NativeRunCoordinator } from '../nativeRunCoordinator';\nimport type { NativeRunProjectionSink } from '../nativeRunProjection';\nimport { NativeTeamChannelService } from '../nativeTeamChannel';\nimport { CompletionNotifier } from '../notify';\nimport { PollScheduler } from '../pollScheduler';\nimport type { ConcurrencyEventReporter } from '../runWithConcurrency';\nimport { SpawnPlanner } from '../spawnPlan';\nimport { SubagentToolService } from '../subagentTool';\nimport { SubagentWaiter } from '../subagentWait';\n\nconst ignoreConcurrencyEvent: ConcurrencyEventReporter = () => undefined;\n\n/** Services used by the parent Pi adapter, grouped as one lifecycle-owned graph. */\nexport interface TeamExtensionRuntime {\n  readonly subagentTool: SubagentToolService;\n  readonly teamChannel: NativeTeamChannelService;\n  readonly pollScheduler: PollScheduler;\n  readonly asyncJobTracker: AsyncJobTracker;\n  readonly nativeRuns: NativeRunCoordinator;\n  readonly subagentWaiter: SubagentWaiter;\n  readonly asyncSubagentSpawner: AsyncSubagentSpawner;\n  readonly discovery: AgentDiscoveryService;\n  readonly skills: SkillDiscoveryService;\n  readonly spawnPlanner: SpawnPlanner;\n  readonly completionNotifier: CompletionNotifier;\n  readonly externalProcesses: ExternalProcessIpc;\n  readonly dispose: () => void;\n  readonly management: ManagementActions;\n  readonly capabilityPolicies: SubagentCapabilityPolicyStore;\n  readonly mcpToolResolver: McpDirectToolResolverBinding;\n  readonly reportConcurrencyEvent: ConcurrencyEventReporter;\n}\n\n/** Lazy dependencies supplied by the owning Pi or headless host. */\nexport interface TeamExtensionRuntimeOptions {\n  readonly environment: Readonly<Record<string, string | undefined>>;\n  readonly childSessions?: DoomChildSessionServiceProvider;\n  readonly nativeRunProjection?: NativeRunProjectionSink;\n}\n\n/** Build one fresh parent graph for one Team Cordis adapter fiber. */\nexport function createTeamExtensionRuntime(\n  reportConcurrencyEvent: ConcurrencyEventReporter | undefined,\n  options: TeamExtensionRuntimeOptions,\n): TeamExtensionRuntime {\n  const report = reportConcurrencyEvent ?? ignoreConcurrencyEvent;\n  const pollScheduler = new PollScheduler();\n  const asyncJobTracker = new AsyncJobTracker();\n  const admission = new AdmissionGate({\n    countLiveRuns: (scope) =>\n      asyncJobTracker\n        .forSession(scope.rootSessionId, scope)\n        .list()\n        .filter((job) => job.status === undefined || !TERMINAL_ASYNC_JOB_STATES.has(job.status)).length,\n  });\n  const subagentWaiter = new SubagentWaiter(asyncJobTracker);\n  const externalProcesses = new ExternalProcessIpc();\n  const asyncSubagentSpawner = new AsyncSubagentSpawner(externalProcesses);\n  const discovery = new AgentDiscoveryService(options.environment);\n  const skills = new SkillDiscoveryService();\n  const capabilityPolicies = new SubagentCapabilityPolicyStore();\n  const mcpToolResolver = new McpDirectToolResolverBinding();\n  const completionNotifier = new CompletionNotifier();\n  const nativeRuns = new NativeRunCoordinator(\n    options.childSessions,\n    asyncJobTracker,\n    completionNotifier,\n    options.nativeRunProjection,\n  );\n  const teamChannel = new NativeTeamChannelService();\n  const spawnPlanner = new SpawnPlanner(\n    discovery,\n    asyncSubagentSpawner,\n    capabilityPolicies,\n    skills,\n    report,\n    mcpToolResolver,\n    admission,\n    options.childSessions,\n    nativeRuns,\n    teamChannel,\n  );\n  const management = new ManagementActions(asyncJobTracker, nativeRuns, externalProcesses);\n  const onExternalEvent = (event: ExternalProcessEvent): void => {\n    const sessionId = event.scope.rootSessionId;\n    if ('message' in event) {\n      const { message } = event;\n      if (message.kind === 'status') asyncJobTracker.upsertExternal(sessionId, event.scope, message.status);\n      if (message.kind === 'error') {\n        asyncJobTracker.markExternalFailed(sessionId, event.scope, message.runId, message.error);\n        void completionNotifier\n          .deliver({ runId: message.runId, agent: 'external', success: false, summary: message.error })\n          .then((delivered) => {\n            if (delivered) asyncJobTracker.acknowledgeHandoff(sessionId, message.runId);\n          });\n      }\n      if (message.kind === 'result') {\n        if (!asyncJobTracker.acceptExternalResult(sessionId, event.scope, message.runId, message.result)) return;\n        void completionNotifier.deliver({ ...message.result, runId: message.runId }).then((delivered) => {\n          if (delivered) asyncJobTracker.acknowledgeHandoff(sessionId, message.runId);\n        });\n      }\n      return;\n    }\n    const jobs = asyncJobTracker.forSession(sessionId, event.scope);\n    const job = jobs.get(event.runId);\n    if (!job || (job.status && TERMINAL_ASYNC_JOB_STATES.has(job.status))) return;\n    const error = `External runner process exited unexpectedly (${event.signal ?? `code ${event.code ?? 'unknown'}`}).`;\n    asyncJobTracker.markExternalFailed(sessionId, event.scope, event.runId, error);\n    void completionNotifier\n      .deliver({ runId: event.runId, agent: job.agent ?? 'external', success: false, summary: error })\n      .then((delivered) => {\n        if (delivered) asyncJobTracker.acknowledgeHandoff(sessionId, event.runId);\n      });\n  };\n  const unsubscribeExternal = externalProcesses.subscribe(onExternalEvent);\n  const subagentTool = new SubagentToolService(\n    spawnPlanner,\n    management,\n    asyncJobTracker,\n    discovery,\n    options.environment,\n  );\n\n  const dispose = (): void => {\n    unsubscribeExternal();\n    externalProcesses.close();\n  };\n\n  return Object.freeze({\n    subagentTool,\n    teamChannel,\n    pollScheduler,\n    asyncJobTracker,\n    nativeRuns,\n    subagentWaiter,\n    asyncSubagentSpawner,\n    discovery,\n    skills,\n    spawnPlanner,\n    completionNotifier,\n    externalProcesses,\n    dispose,\n    management,\n    capabilityPolicies,\n    mcpToolResolver,\n    reportConcurrencyEvent: report,\n  });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAIA,MAAa,4CAA4B,IAAI,IAAI;CAAC;CAAY;CAAa;CAAU;CAAU;AAAS,CAAC;AACzG,MAAM,uBAAuB;;;;;;;;AAoE7B,SAAgB,oBAAoB,MAAgC,IAAoB;CACtF,MAAM,OAAO,KAAK,KAAK;CACvB,MAAM,UAAU,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,CAAC,QAAQ,UAAU,UAAU,MAAM,MAAM,WAAW,EAAE,CAAC;CACnG,MAAM,QAAQ,QAAQ,MAAM,UAAU,UAAU,EAAE;CAClD,IAAI,OAAO,OAAO;CAClB,IAAI,QAAQ,WAAW,GAAG,OAAO,QAAQ;CACzC,IAAI,QAAQ,WAAW,GAAG;EACxB,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,YAAY;EACrC,MAAM,QAAQ,KAAK,QAAQ,QAAQ,IAAI,UAAU,YAAY,MAAM,MAAM;EACzE,IAAI,MAAM,WAAW,GAAG,OAAO,MAAM,EAAE,CAAE;EAC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zB,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,OAAO;EAAE,IAAI;EAAO,SAAS,EAAE,QAAQ,gBAAgB;CAAE;CAE3D,MAAM,QAAS,MAAmC;CAClD,IAAI,OAAO,UAAU,YAAY,CAAC,OAAO,UAAU,KAAK,GACtD,OAAO;EAAE,IAAI;EAAO,SAAS,EAAE,QAAQ,kBAAkB;CAAE;CAE7D,IAAI,CAAC,kBAAkB,SAAS,KAAK,GACnC,OAAO;EAAE,IAAI;EAAO,SAAS;GAAE,QAAQ;GAAuB;EAAM;CAAE;CAExE,OAAO;EAAE,IAAI;EAAa;CAAW;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACHA,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAChC,MAAM,kBAAkB;AACxB,MAAM,gBAAgB;AACtB,MAAM,wBAAwB;;AAE9B,MAAM,qBAAqB;;;;;;;;;AAU3B,MAAa,cAAiC,OAAO,OAAO;CAC1D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;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