@bastani/atomic 0.9.73 → 0.9.74-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (193) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  7. package/dist/builtin/workflows/README.md +2 -2
  8. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  9. package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
  10. package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
  13. package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
  14. package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
  15. package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
  18. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  19. package/dist/builtin/workflows/builtin/goal.js +4 -4
  20. package/dist/builtin/workflows/builtin/index.js +9 -9
  21. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  22. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  23. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  24. package/dist/builtin/workflows/package.json +1 -1
  25. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  26. package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
  27. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
  28. package/dist/builtin/workflows/src/index.js +393 -62
  29. package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
  30. package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
  31. package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
  32. package/dist/config.d.ts +2 -0
  33. package/dist/config.d.ts.map +1 -1
  34. package/dist/config.js +4 -0
  35. package/dist/config.js.map +1 -1
  36. package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
  37. package/dist/core/agent-session-background-compaction.js +2 -1
  38. package/dist/core/agent-session-background-compaction.js.map +1 -1
  39. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  40. package/dist/core/agent-session-compaction.js +98 -4
  41. package/dist/core/agent-session-compaction.js.map +1 -1
  42. package/dist/core/agent-session-detached-tools.d.ts +20 -5
  43. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  44. package/dist/core/agent-session-detached-tools.js +97 -21
  45. package/dist/core/agent-session-detached-tools.js.map +1 -1
  46. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  47. package/dist/core/agent-session-message-queue.js +2 -1
  48. package/dist/core/agent-session-message-queue.js.map +1 -1
  49. package/dist/core/agent-session-methods.d.ts +3 -1
  50. package/dist/core/agent-session-methods.d.ts.map +1 -1
  51. package/dist/core/agent-session-methods.js.map +1 -1
  52. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  53. package/dist/core/agent-session-persistent-custom-messages.js +12 -4
  54. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  55. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  56. package/dist/core/agent-session-prompt.js +33 -0
  57. package/dist/core/agent-session-prompt.js.map +1 -1
  58. package/dist/core/compaction/background-compaction.d.ts +11 -5
  59. package/dist/core/compaction/background-compaction.d.ts.map +1 -1
  60. package/dist/core/compaction/background-compaction.js +19 -10
  61. package/dist/core/compaction/background-compaction.js.map +1 -1
  62. package/dist/core/compaction/compaction-boundary.d.ts +10 -0
  63. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  64. package/dist/core/compaction/compaction-boundary.js +30 -2
  65. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  66. package/dist/core/compaction/compaction-runner.d.ts +7 -0
  67. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  68. package/dist/core/compaction/compaction-runner.js +13 -5
  69. package/dist/core/compaction/compaction-runner.js.map +1 -1
  70. package/dist/core/compaction/compaction-types.d.ts +1 -1
  71. package/dist/core/compaction/compaction-types.js +1 -1
  72. package/dist/core/compaction/compaction-types.js.map +1 -1
  73. package/dist/core/compaction/deleted-ranges.d.ts +17 -2
  74. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  75. package/dist/core/compaction/deleted-ranges.js +44 -5
  76. package/dist/core/compaction/deleted-ranges.js.map +1 -1
  77. package/dist/core/compaction/history-recall.d.ts +32 -0
  78. package/dist/core/compaction/history-recall.d.ts.map +1 -0
  79. package/dist/core/compaction/history-recall.js +275 -0
  80. package/dist/core/compaction/history-recall.js.map +1 -0
  81. package/dist/core/compaction/index.d.ts +2 -0
  82. package/dist/core/compaction/index.d.ts.map +1 -1
  83. package/dist/core/compaction/index.js +2 -0
  84. package/dist/core/compaction/index.js.map +1 -1
  85. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  86. package/dist/core/compaction/pi-summary-fallback.js +1 -0
  87. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  88. package/dist/core/compaction/planner-outcome.d.ts +14 -0
  89. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  90. package/dist/core/compaction/planner-outcome.js +8 -0
  91. package/dist/core/compaction/planner-outcome.js.map +1 -1
  92. package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
  93. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  94. package/dist/core/compaction/range-planner-diagnostics.js +67 -24
  95. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  96. package/dist/core/compaction/range-planner.d.ts +7 -4
  97. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  98. package/dist/core/compaction/range-planner.js +43 -19
  99. package/dist/core/compaction/range-planner.js.map +1 -1
  100. package/dist/core/compaction/refusal-recovery.d.ts +27 -0
  101. package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
  102. package/dist/core/compaction/refusal-recovery.js +65 -0
  103. package/dist/core/compaction/refusal-recovery.js.map +1 -0
  104. package/dist/core/compaction/region-trimming.d.ts +23 -0
  105. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  106. package/dist/core/compaction/region-trimming.js +59 -15
  107. package/dist/core/compaction/region-trimming.js.map +1 -1
  108. package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
  109. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
  110. package/dist/core/compaction/structured-compaction-input.js +30 -17
  111. package/dist/core/compaction/structured-compaction-input.js.map +1 -1
  112. package/dist/core/compaction/transcript-serialization.d.ts +9 -3
  113. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  114. package/dist/core/compaction/transcript-serialization.js +18 -10
  115. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  116. package/dist/core/messages.d.ts +5 -1
  117. package/dist/core/messages.d.ts.map +1 -1
  118. package/dist/core/messages.js +21 -3
  119. package/dist/core/messages.js.map +1 -1
  120. package/dist/core/session-manager-core.js +1 -1
  121. package/dist/core/session-manager-core.js.map +1 -1
  122. package/dist/core/session-manager-history.d.ts +1 -1
  123. package/dist/core/session-manager-history.d.ts.map +1 -1
  124. package/dist/core/session-manager-history.js +2 -5
  125. package/dist/core/session-manager-history.js.map +1 -1
  126. package/dist/core/settings-defaults.d.ts +2 -0
  127. package/dist/core/settings-defaults.d.ts.map +1 -1
  128. package/dist/core/settings-defaults.js +2 -0
  129. package/dist/core/settings-defaults.js.map +1 -1
  130. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  131. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  132. package/dist/core/settings-manager-basic-accessors.js +3 -0
  133. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  134. package/dist/core/settings-schema.d.ts +2 -0
  135. package/dist/core/settings-schema.d.ts.map +1 -1
  136. package/dist/core/settings-schema.js +4 -0
  137. package/dist/core/settings-schema.js.map +1 -1
  138. package/dist/core/storage/session/conformance.d.ts.map +1 -1
  139. package/dist/core/storage/session/conformance.js +12 -0
  140. package/dist/core/storage/session/conformance.js.map +1 -1
  141. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.js +3 -0
  143. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  144. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  145. package/dist/core/storage/session/legacy-session-store.js +3 -0
  146. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  147. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  148. package/dist/core/storage/session/memory-session-store.js +3 -0
  149. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  150. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  151. package/dist/core/storage/session/sql-session-store.js +12 -3
  152. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  153. package/dist/core/storage/session/types.d.ts +3 -0
  154. package/dist/core/storage/session/types.d.ts.map +1 -1
  155. package/dist/core/storage/session/types.js +3 -0
  156. package/dist/core/storage/session/types.js.map +1 -1
  157. package/dist/core/tools/history-protocol.d.ts +3 -0
  158. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  159. package/dist/core/tools/history-protocol.js +7 -87
  160. package/dist/core/tools/history-protocol.js.map +1 -1
  161. package/dist/core/tools/history-transcript.d.ts +24 -0
  162. package/dist/core/tools/history-transcript.d.ts.map +1 -0
  163. package/dist/core/tools/history-transcript.js +110 -0
  164. package/dist/core/tools/history-transcript.js.map +1 -0
  165. package/dist/index.d.ts +1 -1
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/main-session.d.ts.map +1 -1
  169. package/dist/main-session.js +21 -5
  170. package/dist/main-session.js.map +1 -1
  171. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  172. package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
  173. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  174. package/dist/modes/interactive/interactive-render-chat.js +2 -2
  175. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  176. package/dist/session-id-target.d.ts +1 -0
  177. package/dist/session-id-target.d.ts.map +1 -1
  178. package/dist/session-id-target.js +3 -0
  179. package/dist/session-id-target.js.map +1 -1
  180. package/docs/compaction/reference.md +3 -2
  181. package/docs/compaction.md +35 -7
  182. package/docs/development.md +1 -1
  183. package/docs/sdk/reference.md +6 -5
  184. package/docs/sessions.md +3 -3
  185. package/docs/settings.md +3 -0
  186. package/docs/storage.md +2 -0
  187. package/docs/workflows/api-reference.md +15 -3
  188. package/docs/workflows/authoring.md +2 -2
  189. package/docs/workflows/operations.md +1 -0
  190. package/docs/workflows/reliable-design.md +1 -1
  191. package/npm-shrinkwrap.json +32 -32
  192. package/package.json +3 -3
  193. package/schemas/settings.schema.json +5 -0
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-detached-tools.js","sourceRoot":"","sources":["../../src/core/agent-session-detached-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAUrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAwB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE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AAC,CAAC;IAClE,iHAAiH;IACjH,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;QAC9D,MAAM,uBAAuB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC7C,OAAO;IACR,CAAC;IACD,MAAM,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACrE,0BAA0B,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,iBAAiB;IACjB,sBAAsB;IACtB,qBAAqB;IACrB,2BAA2B;IAC3B,kBAAkB;CAClB,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AssistantMessage, ToolCall, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAfterToolCallResult,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolResult,\n} from \"@earendil-works/pi-agent-core\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { deliverHeldTaskCompletions } from \"./agent-session-tasks.js\";\nimport { finalizeToolResult } from \"./agent-session-tool-hooks.ts\";\nimport { type ErrorFieldValue, serializeErrorCause } from \"./error-contract.ts\";\nimport type { ExtensionToolContext } from \"./extensions/context-types.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { MAX_TOOL_DETACHMENT_AFTER_MS, ToolDetachmentError } from \"./tool-detachment-errors.ts\";\nimport {\n\tresolveToolConcurrency,\n\ttype ToolConcurrencyMode,\n\ttype ToolExecutionScheduler,\n} from \"./tools/tool-concurrency.ts\";\n\n/** How long a call of a `detachable` tool runs inline before the session lets it go on without the session. */\nexport interface ToolDetachmentPolicy {\n\t/** Milliseconds a detachable call may run inline; a call still running after that detaches. */\n\treadonly afterMs: number;\n}\n\n/** The outcome of a detached tool call, in the shape the agent loop records as that call's result. */\nexport interface DetachedToolResult {\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\treadonly result: AgentToolResult;\n\treadonly isError: boolean;\n}\n\n/** A tool call that outlived the run that issued it. */\nexport interface DetachedToolCall {\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Settles once the operation ends. Never rejects: a thrown error becomes an `isError` result. */\n\treadonly result: Promise<DetachedToolResult>;\n\t/** Cancel the operation; `reason` reaches the tool through its abort signal. */\n\tabort(reason?: Error | DOMException | string): void;\n}\n\ninterface DetachmentState {\n\tpolicy: ToolDetachmentPolicy | undefined;\n\t/** Calls detached by the session's runs and not yet taken by the host. */\n\treadonly detached: Map<string, DetachedToolCall>;\n\t/** How each detachable tool's work starts, and the session's context for a call of it, by tool name. */\n\treadonly executes: Map<string, DetachableWork>;\n\treadonly concurrency: Map<string, AgentTool[\"concurrency\"]>;\n\t/** For a tool that detaches only some of its calls, which ones, by tool name. */\n\treadonly detachesCall: Map<string, DetachesCall>;\n\t/** What the session's calls still running hold of it: their places in its tool scheduler. */\n\treadonly holds: Set<CallHold>;\n}\n\n/** How a detachable tool's work starts, and the session's tool context for a call of it. */\ninterface DetachableWork {\n\treadonly execute: DetachableExecute;\n\treadonly context: DetachableContext;\n}\n\nconst states = new WeakMap<object, DetachmentState>();\n\nconst DETACHED_PLACEHOLDER_TEXT =\n\t\"This tool call continues after the run ends; its result is recorded when it arrives.\";\n\nfunction detachmentState(session: AgentSession): DetachmentState {\n\tlet state = states.get(session);\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tpolicy: undefined,\n\t\t\tdetached: new Map(),\n\t\t\texecutes: new Map(),\n\t\t\tconcurrency: new Map(),\n\t\t\tdetachesCall: new Map(),\n\t\t\tholds: new Set(),\n\t\t};\n\t\tstates.set(session, state);\n\t}\n\treturn state;\n}\n\n/** Whether the host set a detachment policy on this session, so its detachable calls may outlive its runs. */\nexport function hasToolDetachment(session: AgentSession): boolean {\n\treturn states.get(session)?.policy !== undefined;\n}\n\nexport function isDetachedToolCall(session: AgentSession, toolCallId: string): boolean {\n\treturn states.get(session)?.detached.has(toolCallId) === true;\n}\n\n/** Whether `toolCallId` is a call of the assistant message the loop is executing, not a call nested inside a tool. */\nfunction isTopLevelToolCall(session: AgentSession, toolCallId: string): boolean {\n\tconst messages = session.agent.state.messages;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role !== \"assistant\") continue;\n\t\treturn message.content.some((part) => part.type === \"toolCall\" && part.id === toolCallId);\n\t}\n\treturn false;\n}\n\nfunction errorToolResult(error: Error | DOMException | string | object): AgentToolResult {\n\tconst failure = typedFailure(error);\n\treturn {\n\t\tcontent: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }],\n\t\tdetails: failure === undefined ? undefined : { error: failure },\n\t};\n}\n\n/**\n * The typed failure a detached call's error result carries in `details.error`, so a host branches on its `code`\n * instead of its text: the error's own JSON form when it has one, otherwise what its properties give. An error whose\n * `toJSON()` throws gets the latter too, marked `serialization: \"fallback\"`. Undefined for an error without a string\n * `code`.\n */\nfunction typedFailure(error: Error | DOMException | string | object): DetachedCallFailure | undefined {\n\tif (!(error instanceof Error)) return undefined;\n\tconst { code } = error as { readonly code?: unknown };\n\tif (typeof code !== \"string\") return undefined;\n\tconst json = (error as { readonly toJSON?: () => DetachedCallFailure }).toJSON;\n\tif (typeof json !== \"function\") return failureOf(error, code);\n\ttry {\n\t\treturn json.call(error);\n\t} catch {\n\t\treturn { ...failureOf(error, code), serialization: \"fallback\" };\n\t}\n}\n\nfunction failureOf(error: Error, code: string): DetachedCallFailure {\n\tconst { hint, retryable, fields } = error as {\n\t\treadonly hint?: unknown;\n\t\treadonly retryable?: unknown;\n\t\treadonly fields?: unknown;\n\t};\n\tconst cause = serializeErrorCause(error.cause);\n\treturn {\n\t\tname: error.name,\n\t\tcode,\n\t\tmessage: error.message,\n\t\t...(typeof hint === \"string\" ? { hint } : {}),\n\t\t...(typeof retryable === \"boolean\" ? { retryable } : {}),\n\t\t...(isErrorFields(fields) ? { fields } : {}),\n\t\t...(cause === undefined ? {} : { cause }),\n\t};\n}\n\nfunction isErrorFields(value: unknown): value is Readonly<Record<string, ErrorFieldValue>> {\n\tif (typeof value !== \"object\" || value === null || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(\n\t\t(field) => field === null || [\"string\", \"number\", \"boolean\"].includes(typeof field),\n\t);\n}\n\n/** A cause in a {@link DetachedCallFailure}'s chain, without stack traces. */\nexport type DetachedCallFailureCause = {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly code?: string;\n\treadonly cause?: DetachedCallFailureCause;\n};\n\n/** A detached call's typed failure, as its error result's `details.error` reports it. */\nexport type DetachedCallFailure = {\n\treadonly name: string;\n\treadonly code: string;\n\treadonly message: string;\n\treadonly hint?: string;\n\treadonly retryable?: boolean;\n\treadonly fields?: Readonly<Record<string, ErrorFieldValue>>;\n\treadonly cause?: DetachedCallFailureCause;\n\t/** The error's own `toJSON()` threw, so this carries only what the error's properties give. */\n\treadonly serialization?: \"fallback\";\n};\n\n/**\n * Runs a callback in the async context of this module's load, outside every session. A detachable call's work and\n * every reaction waiting on it start here: a promise reaction keeps the async context it was created in alive, so work\n * started inside a session would keep that session reachable for as long as the call runs.\n */\nconst outsideAnySession = AsyncLocalStorage.snapshot();\n\ntype ToolParams = Parameters<AgentTool[\"execute\"]>[1];\ntype ToolUpdate = Parameters<AgentTool[\"execute\"]>[3];\n\n/**\n * Starts a detachable call's work directly on its tool definition, outside the session's tool wrappers: a wrapper\n * awaiting the work would hold the session's extension runner for as long as the call waits.\n */\nexport type DetachableExecute = (\n\ttoolCallId: string,\n\tparams: ToolParams,\n\tsignal: AbortSignal,\n\tonUpdate: ToolUpdate,\n\tcontext: ExtensionToolContext,\n) => ReturnType<AgentTool[\"execute\"]>;\n\n/** The session's tool context for a call, bound to the call's own abort signal. */\nexport type DetachableContext = (toolCallId: string, signal: AbortSignal) => ExtensionToolContext;\n\n/** Whether one call of a tool may detach, decided from the call's arguments. */\nexport type DetachesCall = (params: ToolParams) => boolean;\n\nconst readinessCallbacks = new WeakMap<AbortSignal, () => void>();\n\n/** Marks the durable handoff of a call ready for detachment. No-op without a waiting detachment policy. */\nexport function markToolCallReadyForDetachment(signal: AbortSignal): void {\n\treadinessCallbacks.get(signal)?.();\n}\n\n/** Whether this call must prepare a durable handoff before it can detach. */\nexport function toolCallNeedsDetachmentHandoff(signal: AbortSignal | undefined): boolean {\n\treturn signal !== undefined && readinessCallbacks.has(signal);\n}\n\n/**\n * What a detachable call's work reaches of its session, only while the call runs inline. Detaching clears it, so\n * the work keeps neither the agent loop nor the session's context reachable for as long as it goes on.\n */\ninterface InlineSession {\n\tonUpdate: ToolUpdate;\n\tcontext: ExtensionToolContext | undefined;\n}\n\n/** Session-free facts a detached call's context still answers. */\ninterface DetachedCallFacts {\n\treadonly sessionId: string;\n\treadonly toolCallId: string;\n\treadonly cwd: string;\n}\n\n/** The session's tool context for a call started again, or undefined once the session has closed. */\ntype StartingContext = (toolCallId: string, signal: AbortSignal) => ExtensionToolContext | undefined;\n\n/** When a detachable call's work starts, and what of the session's context it has. */\ninterface OperationStart {\n\t/** The session's context for a call that starts inline: the work keeps it until the call detaches. */\n\treadonly inlineContext?: DetachableContext;\n\t/** The session's context for a call started again: the work has it only while it starts, until its first await. */\n\treadonly startingContext?: StartingContext;\n\t/** `now` starts the work before returning; a promise starts it once it resolves; absent, on the next tick. */\n\treadonly when?: \"now\" | Promise<void>;\n}\n\n/*\n * The helpers below are module-level on purpose. A closure keeps every scope it is nested in, so a reaction created\n * inside a function that can see the session would keep the session reachable while the call waits.\n */\n\n/**\n * What a running detachable call holds of its session: its place in the session's tool scheduler, so an exclusive\n * call never overlaps another, and the gate its run waits on while the call runs inline. The call's one reaction to\n * its work settling lets both go; closing the session lets the place go first, since nothing is scheduled there any\n * more, so a call that outlives its session keeps none of the scheduler's state (#4403).\n */\ninterface CallHold {\n\tpermit: SchedulerPermit | undefined;\n\tgate: ((value: symbol) => void) | undefined;\n\tholds: Set<CallHold> | undefined;\n}\n\nfunction holdCall(holds: Set<CallHold>, permit: SchedulerPermit): CallHold {\n\tconst hold: CallHold = { permit, gate: undefined, holds };\n\tholds.add(hold);\n\treturn hold;\n}\n\n/** The call's work settled: give its place in the scheduler back and open the gate of a run waiting inline. */\nfunction letGo(hold: CallHold): void {\n\tconst { permit, gate } = hold;\n\thold.permit = undefined;\n\thold.gate = undefined;\n\thold.holds?.delete(hold);\n\thold.holds = undefined;\n\tpermit?.release();\n\tgate?.(INLINE);\n}\n\n/**\n * Give back the scheduler places of the session's calls still running, once the session is closing and nothing new\n * is scheduled on it. While a call still waits for its place behind them, as a reopened session's redispatched calls\n * can, they all keep their places, so that call starts only once the work before it has settled. The calls go on;\n * each still delivers its result when its work settles.\n */\nexport function releaseDetachedCallHolds(session: AgentSession): void {\n\tconst holds = states.get(session)?.holds;\n\tif (holds === undefined || [...holds].some((hold) => hold.permit?.granted() === false)) return;\n\tfor (const hold of holds) {\n\t\tconst permit = hold.permit;\n\t\thold.permit = undefined;\n\t\thold.holds = undefined;\n\t\tpermit?.release();\n\t}\n\tholds.clear();\n}\n\nfunction startOperation(\n\ttoolName: string,\n\texecute: DetachableExecute,\n\tparams: ToolParams,\n\tinline: InlineSession,\n\tfacts: DetachedCallFacts,\n\thold: CallHold,\n\tstart: OperationStart,\n): { readonly call: DetachedToolCall; readonly settled: Promise<AgentToolResult>; readonly signal: AbortSignal } {\n\treturn outsideAnySession(() => {\n\t\tconst controller = new AbortController();\n\t\tif (start.inlineContext !== undefined) inline.context = start.inlineContext(facts.toolCallId, controller.signal);\n\t\tconst onUpdate = inline.onUpdate === undefined ? undefined : forwardedUpdate(inline);\n\t\tconst context = callContext(inline, facts);\n\t\tconst begin = (): ReturnType<AgentTool[\"execute\"]> =>\n\t\t\tbeginWork(execute, facts.toolCallId, params, controller.signal, onUpdate, context, inline, start);\n\t\tconst settled =\n\t\t\tstart.when === \"now\"\n\t\t\t\t? new Promise<AgentToolResult>((resolve) => resolve(begin()))\n\t\t\t\t: (start.when ?? Promise.resolve()).then(begin);\n\t\treturn {\n\t\t\tsettled,\n\t\t\tsignal: controller.signal,\n\t\t\tcall: {\n\t\t\t\ttoolCallId: facts.toolCallId,\n\t\t\t\ttoolName,\n\t\t\t\tresult: settledResult(toolName, facts.toolCallId, settled, hold),\n\t\t\t\tabort: abortWith(controller),\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction beginWork(\n\texecute: DetachableExecute,\n\ttoolCallId: string,\n\tparams: ToolParams,\n\tsignal: AbortSignal,\n\tonUpdate: ToolUpdate,\n\tcontext: ExtensionToolContext,\n\tinline: InlineSession,\n\tstart: OperationStart,\n): ReturnType<AgentTool[\"execute\"]> {\n\tif (start.startingContext === undefined) return execute(toolCallId, params, signal, onUpdate, context);\n\tinline.context = start.startingContext(toolCallId, signal);\n\ttry {\n\t\treturn execute(toolCallId, params, signal, onUpdate, context);\n\t} finally {\n\t\tinline.context = undefined;\n\t}\n}\n\n/** Progress a call reports reaches the agent loop while the call runs inline; once it detaches, it is dropped. */\nfunction forwardedUpdate(inline: InlineSession): NonNullable<ToolUpdate> {\n\treturn (partialResult) => inline.onUpdate?.(partialResult);\n}\n\n/**\n * The context a detachable call's work receives: the session's tool context while the call runs inline. Once the call\n * detaches it answers only `cwd`, and any other use throws {@link ToolDetachmentError} `context-detached`.\n */\nfunction callContext(inline: InlineSession, facts: DetachedCallFacts): ExtensionToolContext {\n\treturn new Proxy({} as ExtensionToolContext, {\n\t\tget(_target, key) {\n\t\t\tconst live = inline.context;\n\t\t\tif (live !== undefined) return Reflect.get(live, key);\n\t\t\tif (key === \"cwd\") return facts.cwd;\n\t\t\t// Not a thenable, and nothing for inspection to find.\n\t\t\tif (key === \"then\" || typeof key === \"symbol\") return undefined;\n\t\t\tthrow new ToolDetachmentError(\"context-detached\", {\n\t\t\t\tsessionId: facts.sessionId,\n\t\t\t\ttoolCallId: facts.toolCallId,\n\t\t\t});\n\t\t},\n\t\thas(_target, key) {\n\t\t\tconst live = inline.context;\n\t\t\treturn live === undefined ? key === \"cwd\" : Reflect.has(live, key);\n\t\t},\n\t});\n}\n\n/**\n * The call's one reaction to its work settling: it lets the call's hold go and makes the call's result. It is built\n * apart from the call's abort, so it keeps the call's names and hold, not its controller.\n */\nfunction settledResult(\n\ttoolName: string,\n\ttoolCallId: string,\n\tsettled: Promise<AgentToolResult>,\n\thold: CallHold,\n): Promise<DetachedToolResult> {\n\treturn settled.then(\n\t\t(value): DetachedToolResult => {\n\t\t\tletGo(hold);\n\t\t\treturn { toolCallId, toolName, result: value, isError: value.isError === true };\n\t\t},\n\t\t(error: Error | DOMException | string | object): DetachedToolResult => {\n\t\t\tletGo(hold);\n\t\t\treturn { toolCallId, toolName, result: errorToolResult(error), isError: true };\n\t\t},\n\t);\n}\n\nfunction abortWith(controller: AbortController): DetachedToolCall[\"abort\"] {\n\treturn (reason) => controller.abort(reason);\n}\n\nconst INLINE = Symbol(\"inline\");\nconst DETACH = Symbol(\"detach\");\n\ninterface SchedulerPermit {\n\treadonly grantedLater: Promise<void> | undefined;\n\t/** Whether the scheduler has given the call its place yet. */\n\tgranted(): boolean;\n\trelease(): void;\n}\n\nfunction takeSchedulerPermit(scheduler: ToolExecutionScheduler, mode: ToolConcurrencyMode): SchedulerPermit {\n\treturn outsideAnySession(() => {\n\t\tconst granted = Promise.withResolvers<void>();\n\t\tconst held = Promise.withResolvers<void>();\n\t\tlet grantedNow = false;\n\t\tvoid scheduler.schedule(mode, () => {\n\t\t\tgrantedNow = true;\n\t\t\tgranted.resolve();\n\t\t\treturn held.promise;\n\t\t});\n\t\treturn {\n\t\t\tgrantedLater: grantedNow ? undefined : granted.promise,\n\t\t\tgranted: () => grantedNow,\n\t\t\trelease: () => held.resolve(),\n\t\t};\n\t});\n}\n\n/** Forget the session's detachable tools before its tools are registered again, so a removed tool is not one. */\nexport function forgetDetachableTools(session: AgentSession): void {\n\tconst state = states.get(session);\n\tstate?.executes.clear();\n\tstate?.concurrency.clear();\n\tstate?.detachesCall.clear();\n}\n\n/**\n * Run a call of a detachable tool inline until the session's detachment policy elapses, then let it go on without\n * the run. The loop then records a placeholder that never reaches the transcript, listeners, or the provider, and\n * the run ends after its turn so the host can release the session and hand the result back later.\n *\n * The call keeps its declared concurrency: it starts once the calls before it in the session's scheduler allow, and\n * it holds its place there until its work settles, also after it detaches, so an exclusive call never overlaps another\n * call of the session. Closing the session gives the place back.\n */\nexport function detachableTool(\n\tsession: AgentSession,\n\ttool: AgentTool,\n\texecute: DetachableExecute,\n\tcreateContext: DetachableContext,\n\tdetachesCall?: DetachesCall,\n\trequiresReady = false,\n): AgentTool {\n\tconst state = detachmentState(session);\n\tstate.executes.set(tool.name, { execute, context: createContext });\n\tstate.concurrency.set(tool.name, tool.concurrency);\n\tif (detachesCall !== undefined) state.detachesCall.set(tool.name, detachesCall);\n\treturn {\n\t\t...tool,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\tconst policy = state.policy;\n\t\t\tif (policy === undefined || !isTopLevelToolCall(session, toolCallId) || detachesCall?.(params) === false)\n\t\t\t\treturn tool.execute(toolCallId, params, signal, onUpdate);\n\t\t\tconst permit = takeSchedulerPermit(\n\t\t\t\tsession._toolExecutionScheduler,\n\t\t\t\tresolveToolConcurrency(tool.concurrency, params as Record<string, unknown>),\n\t\t\t);\n\t\t\tif (permit.grantedLater !== undefined) await permit.grantedLater;\n\t\t\tconst hold = holdCall(state.holds, permit);\n\t\t\tconst inline: InlineSession = { onUpdate, context: undefined };\n\t\t\tlet operation: ReturnType<typeof startOperation>;\n\t\t\ttry {\n\t\t\t\toperation = startOperation(\n\t\t\t\t\ttool.name,\n\t\t\t\t\texecute,\n\t\t\t\t\tparams,\n\t\t\t\t\tinline,\n\t\t\t\t\tdetachedCallFacts(session, toolCallId),\n\t\t\t\t\thold,\n\t\t\t\t\t{ inlineContext: createContext },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tletGo(hold);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst { call, settled, signal: operationSignal } = operation;\n\t\t\tconst forwardAbort = (): void => call.abort(signal?.reason);\n\t\t\tif (signal?.aborted) forwardAbort();\n\t\t\telse signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n\t\t\t// The run waits on this gate alone: it settles at the threshold even while the call goes on, so no reaction\n\t\t\t// created in the run's context stays on the call once it detaches.\n\t\t\tconst gate = Promise.withResolvers<symbol>();\n\t\t\thold.gate = gate.resolve;\n\t\t\tlet ready = !requiresReady;\n\t\t\tlet elapsed = false;\n\t\t\tif (requiresReady)\n\t\t\t\treadinessCallbacks.set(operationSignal, () => {\n\t\t\t\t\tready = true;\n\t\t\t\t\tif (elapsed) gate.resolve(DETACH);\n\t\t\t\t});\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\telapsed = true;\n\t\t\t\tif (ready) gate.resolve(DETACH);\n\t\t\t}, policy.afterMs);\n\t\t\ttry {\n\t\t\t\tif ((await gate.promise) === INLINE) return await settled;\n\t\t\t} finally {\n\t\t\t\thold.gate = undefined;\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treadinessCallbacks.delete(operationSignal);\n\t\t\t\tsignal?.removeEventListener(\"abort\", forwardAbort);\n\t\t\t}\n\t\t\tinline.onUpdate = undefined;\n\t\t\tinline.context = undefined;\n\t\t\tstate.detached.set(toolCallId, call);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: DETACHED_PLACEHOLDER_TEXT }],\n\t\t\t\tdetails: undefined,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction detachedCallFacts(session: AgentSession, toolCallId: string): DetachedCallFacts {\n\treturn { sessionId: session.sessionManager.getSessionId(), toolCallId, cwd: session._cwd };\n}\n\nfunction isDetachedPlaceholder(detached: ReadonlyMap<string, DetachedToolCall>, message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && detached.has((message as ToolResultMessage).toolCallId);\n}\n\n/**\n * The placeholder a detached call leaves in the loop is no tool result: drop its events, take it out of the live\n * transcript, and leave it out of the turn and run summaries. Returns the event to process, or `undefined`.\n */\nexport function withoutDetachedPlaceholders(session: AgentSession, event: AgentEvent): AgentEvent | undefined {\n\tconst detached = states.get(session)?.detached;\n\tif (detached === undefined || detached.size === 0) return event;\n\tswitch (event.type) {\n\t\tcase \"tool_execution_end\":\n\t\t\treturn detached.has(event.toolCallId) ? undefined : event;\n\t\tcase \"message_start\":\n\t\t\treturn isDetachedPlaceholder(detached, event.message) ? undefined : event;\n\t\tcase \"message_end\": {\n\t\t\tif (!isDetachedPlaceholder(detached, event.message)) return event;\n\t\t\t// Agent-core appended the placeholder to its live transcript before notifying listeners.\n\t\t\tconst messages = session.agent.state.messages;\n\t\t\tconst index = messages.lastIndexOf(event.message);\n\t\t\tif (index >= 0) messages.splice(index, 1);\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"turn_end\": {\n\t\t\tconst toolResults = event.toolResults.filter((result) => !detached.has(result.toolCallId));\n\t\t\treturn toolResults.length === event.toolResults.length ? event : { ...event, toolResults };\n\t\t}\n\t\tcase \"agent_end\": {\n\t\t\tconst messages = event.messages.filter((message) => !isDetachedPlaceholder(detached, message));\n\t\t\treturn messages.length === event.messages.length ? event : { ...event, messages };\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n\nexport function setToolDetachment(this: AgentSession, policy: ToolDetachmentPolicy | undefined): void {\n\tif (\n\t\tpolicy !== undefined &&\n\t\t!(Number.isFinite(policy.afterMs) && policy.afterMs >= 0 && policy.afterMs <= MAX_TOOL_DETACHMENT_AFTER_MS)\n\t)\n\t\tthrow new ToolDetachmentError(\"invalid-policy\", {\n\t\t\tsessionId: this.sessionManager.getSessionId(),\n\t\t\tfield: \"afterMs\",\n\t\t\tvalue: String(policy.afterMs),\n\t\t});\n\tdetachmentState(this).policy = policy === undefined ? undefined : { afterMs: policy.afterMs };\n}\n\nexport function takeDetachedToolCalls(this: AgentSession): DetachedToolCall[] {\n\tconst detached = states.get(this)?.detached;\n\tif (detached === undefined) return [];\n\tconst calls = [...detached.values()];\n\tdetached.clear();\n\treturn calls;\n}\n\n/** A call of a detachable tool in the transcript, with how its tool's work starts in this session. */\ninterface DetachableCall {\n\treadonly toolCall: ToolCall;\n\treadonly work: DetachableWork;\n}\n\n/**\n * The last assistant message of the transcript, the calls of detachable tools it is still waiting on, and whether that\n * message issued a detachable call at all: a transcript that ends on such a turn has not had the model's answer yet.\n * A tool is detachable in this session when the session registered how its work starts.\n */\nfunction pendingDetachableCalls(session: AgentSession): {\n\treadonly assistant: AssistantMessage | undefined;\n\treadonly calls: readonly DetachableCall[];\n\treadonly endsOnDetachableTurn: boolean;\n} {\n\tconst none = { assistant: undefined, calls: [], endsOnDetachableTurn: false };\n\tconst messages = session.sessionManager.buildSessionProjection().messages;\n\tlet index = messages.length - 1;\n\twhile (index >= 0 && messages[index]?.role !== \"assistant\") index--;\n\tconst assistant = messages[index] as AssistantMessage | undefined;\n\tif (assistant?.stopReason !== \"toolUse\") return none;\n\tconst later = messages.slice(index + 1);\n\t// A later turn already moved past the call; only a transcript that ends on it is waiting.\n\tif (later.some((message) => message.role === \"user\" || message.role === \"assistant\")) return none;\n\tconst answered = new Set(\n\t\tlater.flatMap((message) => (message.role === \"toolResult\" ? [(message as ToolResultMessage).toolCallId] : [])),\n\t);\n\tconst state = states.get(session);\n\tconst detachable = assistant.content.flatMap((block): DetachableCall[] => {\n\t\tif (block.type !== \"toolCall\") return [];\n\t\tconst work = state?.executes.get(block.name);\n\t\tif (work === undefined) return [];\n\t\tif (state?.detachesCall.get(block.name)?.(block.arguments as ToolParams) === false) return [];\n\t\treturn [{ toolCall: block as ToolCall, work }];\n\t});\n\treturn {\n\t\tassistant,\n\t\tcalls: detachable.filter(({ toolCall }) => !answered.has(toolCall.id)),\n\t\tendsOnDetachableTurn: detachable.length > 0,\n\t};\n}\n\n/**\n * Whether the transcript ends on a turn that issued a detachable call and has no answer from the model yet, with or\n * without its results: a session reopened after its process died continues that turn instead of being prompted again.\n */\nexport function hasPendingDetachedTurn(this: AgentSession): boolean {\n\treturn pendingDetachableCalls(this).endsOnDetachableTurn;\n}\n\n/**\n * Whether the transcript ends on a turn still waiting for the result of a call of a detachable tool. Nothing may come\n * between such a call and its result, so input that would land there waits until the turn resumes.\n */\nexport function waitsOnDetachedResults(session: AgentSession): boolean {\n\tif (!states.get(session)?.executes.size) return false;\n\treturn pendingDetachableCalls(session).calls.length > 0;\n}\n\n/**\n * Mark every call of a detachable tool that the transcript ends on without a result as in flight, not interrupted,\n * until its result is recorded. A workflow stage resumed after its process died starts those calls again, or records\n * the results that process saved, only once its turn resumes; a chat may show the stage's transcript before then, and\n * must not report them interrupted meanwhile (#4022). Says whether any call was pending.\n */\nexport function holdPendingDetachedCalls(session: AgentSession): boolean {\n\tconst pending = pendingDetachableCalls(session).calls;\n\tif (pending.length === 0) return false;\n\tfor (const { toolCall } of pending) session._reissuedToolCallIds.add(toolCall.id);\n\tsession._refreshFinalizedContext();\n\treturn true;\n}\n\n/**\n * Start again every call of a detachable tool that the transcript ends on without a result: the process that ran\n * them is gone. Each runs with its original id and arguments, so a call may run more than once. Hosts see each call\n * start again, and its result is recorded as that call's once it is handed back. The work has the session's tool\n * context only while it starts, up to its first `await`; from then on its context answers only `cwd`, and it reports\n * no progress. A call the session's scheduler queues behind another gets that context when it starts, if the session\n * is still open then.\n */\nexport function redispatchDetachedToolCalls(this: AgentSession): DetachedToolCall[] {\n\tconst pending = pendingDetachableCalls(this).calls;\n\tif (pending.length === 0) return [];\n\tconst state = detachmentState(this);\n\tfor (const { toolCall } of pending) this._reissuedToolCallIds.add(toolCall.id);\n\tthis._refreshFinalizedContext();\n\treturn pending.map(({ toolCall, work }) => {\n\t\tannounceRestartedCall(this, toolCall);\n\t\tconst inline: InlineSession = { onUpdate: undefined, context: undefined };\n\t\tconst facts = detachedCallFacts(this, toolCall.id);\n\t\tconst params = toolCall.arguments as ToolParams;\n\t\tconst permit = takeSchedulerPermit(\n\t\t\tthis._toolExecutionScheduler,\n\t\t\tresolveToolConcurrency(state.concurrency.get(toolCall.name), params as Record<string, unknown>),\n\t\t);\n\t\treturn startOperation(toolCall.name, work.execute, params, inline, facts, holdCall(state.holds, permit), {\n\t\t\tstartingContext: whileOpen(this, work.context),\n\t\t\twhen: permit.grantedLater ?? \"now\",\n\t\t}).call;\n\t});\n}\n\n/** The session's tool context, only while the session is open; a closed session's call has none. */\nfunction whileOpen(session: AgentSession, createContext: DetachableContext): StartingContext {\n\treturn (toolCallId, signal) =>\n\t\tsession._disposed || sessionGenerationClosing.has(session) ? undefined : createContext(toolCallId, signal);\n}\n\n/**\n * Hosts see a call started again start, as they see the agent loop start one. Session listeners hear it at once, so a\n * host that releases the session right after starting its calls again has seen them start; extensions hear it through\n * the session's event queue, in order with its other events.\n */\nfunction announceRestartedCall(session: AgentSession, toolCall: ToolCall): void {\n\tconst event: AgentEvent = {\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\targs: toolCall.arguments,\n\t};\n\tsession._emit(event);\n\tsession._agentEventQueue = Promise.allSettled([session._agentEventQueue]).then(() =>\n\t\tsession._emitExtensionEvent(event),\n\t);\n}\n\nfunction resultMessage(result: DetachedToolResult): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: result.toolCallId,\n\t\ttoolName: result.toolName,\n\t\tcontent: result.result.content,\n\t\tdetails: result.result.details,\n\t\t...(result.result.usage === undefined ? {} : { usage: result.result.usage }),\n\t\tisError: result.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\n/** A result with what the session's finalization replaced, merged the way the agent loop merges an inline call's. */\nfunction withReplacement(\n\tdetached: DetachedToolResult,\n\treplacement: AfterToolCallResult | undefined,\n): DetachedToolResult {\n\tif (replacement === undefined) return detached;\n\tconst { structuredContent: reported, ...rest } = detached.result;\n\t// Structured content not replaced along with the content may no longer match it.\n\tconst structuredContent = replacement.structuredContent ?? (replacement.content ? undefined : reported);\n\treturn {\n\t\t...detached,\n\t\tresult: {\n\t\t\t...rest,\n\t\t\tcontent: replacement.content ?? rest.content,\n\t\t\tdetails: (replacement.details ?? rest.details) as AgentToolResult[\"details\"],\n\t\t\tusage: replacement.usage ?? rest.usage,\n\t\t\t...(structuredContent === undefined ? {} : { structuredContent }),\n\t\t},\n\t\tisError: replacement.isError ?? detached.isError,\n\t};\n}\n\n/** A detached call's result as it enters history: finalized exactly as the result of an inline call is. */\nasync function finalizedResult(\n\tsession: AgentSession,\n\ttoolCall: ToolCall,\n\treported: DetachedToolResult,\n): Promise<DetachedToolResult> {\n\t// A result handed back across a process boundary may omit its content, as an untyped tool's may.\n\tconst detached = { ...reported, result: { ...reported.result, content: reported.result.content ?? [] } };\n\ttry {\n\t\tconst replacement = await finalizeToolResult(session, {\n\t\t\ttoolCall,\n\t\t\targs: toolCall.arguments,\n\t\t\tresult: detached.result,\n\t\t\tisError: detached.isError,\n\t\t\tparentToolCallId: undefined,\n\t\t\treleasedStage: true,\n\t\t});\n\t\treturn withReplacement(detached, replacement);\n\t} catch (error) {\n\t\t// As the agent loop does when an inline call's finalization throws: the call fails with that error.\n\t\treturn { ...detached, result: errorToolResult(error as Error | string | object), isError: true };\n\t}\n}\n\n/**\n * Wait for the save of a result the session just recorded. A save that failed fails the continuation, which rejects\n * with it; the session's event queue goes on past it, as it does past a failed save inside the agent loop, so the\n * session's later barriers and its disposal do not report the same failure again.\n */\nasync function resultSaved(session: AgentSession): Promise<void> {\n\tconst queue = session._agentEventQueue;\n\ttry {\n\t\tawait queue;\n\t} catch (error) {\n\t\tif (session._agentEventQueue === queue) session._agentEventQueue = queue.catch(() => {});\n\t\tthrow error;\n\t}\n}\n\n/** A new result and the call of the pending turn it answers. */\ninterface Answer {\n\treadonly toolCall: ToolCall;\n\treadonly result: DetachedToolResult;\n}\n\n/** Record each answer as its call's result, in the order given, and refresh the session's context from them. */\nasync function recordAnswers(session: AgentSession, answers: readonly Answer[]): Promise<void> {\n\tfor (const answer of answers) session._reissuedToolCallIds.add(answer.result.toolCallId);\n\ttry {\n\t\tfor (const answer of answers) {\n\t\t\tconst result = await finalizedResult(session, answer.toolCall, answer.result);\n\t\t\tconst message = resultMessage(result);\n\t\t\t// Through the session's event pipeline, as the agent loop records a result: hosts see the call end,\n\t\t\t// and the result is persisted as that call's result.\n\t\t\tsession._handleAgentEvent({\n\t\t\t\ttype: \"tool_execution_end\",\n\t\t\t\ttoolCallId: result.toolCallId,\n\t\t\t\ttoolName: result.toolName,\n\t\t\t\tresult: result.result,\n\t\t\t\tisError: result.isError,\n\t\t\t});\n\t\t\tsession._handleAgentEvent({ type: \"message_start\", message });\n\t\t\tsession._handleAgentEvent({ type: \"message_end\", message });\n\t\t\tawait resultSaved(session);\n\t\t}\n\t} finally {\n\t\tfor (const answer of answers) session._reissuedToolCallIds.delete(answer.result.toolCallId);\n\t\tsession._refreshFinalizedContext();\n\t}\n}\n\n/**\n * Record answers of a turn that still waits on other calls, without continuing it. The session counts as running\n * meanwhile, as it does while a continuation records its results, so a second resume is refused as busy instead of\n * recording beside this one, where neither would see the turn complete and continue it.\n */\nfunction recordWithoutContinuing(session: AgentSession, answers: readonly Answer[]): Promise<void> {\n\treturn trackSessionWork(session, async () => {\n\t\tsession._activePromptCount += 1;\n\t\ttry {\n\t\t\tawait recordAnswers(session, answers);\n\t\t} finally {\n\t\t\tsession._activePromptCount -= 1;\n\t\t}\n\t});\n}\n\n/**\n * Record the results of detached calls the transcript is waiting on, each as its own call's result right after its\n * call, then continue the turn that issued them once every detachable call of that turn has its result. Results may\n * arrive together or across several calls: until the last one arrives, the session records what it is given and\n * resolves without continuing. A result for a call that already has one, or repeated in `results`, is ignored. With\n * no new result, a transcript that ends on a detachable turn whose every call has its result continues that turn\n * (its process stopped before the model answered), and a turn still waiting on a call is left as it is. Each result\n * is finalized as an inline call's is: extension `tool_result` handlers, image normalization and the\n * oversized-output spill.\n */\nexport async function resumeDetachedTurn(this: AgentSession, results: readonly DetachedToolResult[]): Promise<void> {\n\tconst sessionId = this.sessionManager.getSessionId();\n\t// A closed session records nothing: the results stay with the caller for the session reopened from the store.\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\tthrow new ToolDetachmentError(\"session-closed\", { sessionId });\n\tif (this.isStreaming || this._activePromptCount > 0) throw new ToolDetachmentError(\"session-busy\", { sessionId });\n\tconst { assistant, calls, endsOnDetachableTurn } = pendingDetachableCalls(this);\n\tconst issued = new Map(\n\t\tassistant?.content.flatMap((block) => (block.type === \"toolCall\" ? [[block.id, block] as const] : [])) ?? [],\n\t);\n\tconst recorded = new Set(\n\t\tthis.sessionManager\n\t\t\t.buildSessionProjection()\n\t\t\t.messages.flatMap((message) => (message.role === \"toolResult\" ? [message.toolCallId] : [])),\n\t);\n\tconst pending = results.filter((result) => {\n\t\tif (recorded.has(result.toolCallId)) return false;\n\t\trecorded.add(result.toolCallId);\n\t\treturn true;\n\t});\n\tconst answers = pending.flatMap((result) => {\n\t\tconst toolCall = issued.get(result.toolCallId);\n\t\treturn toolCall === undefined ? [] : [{ toolCall, result }];\n\t});\n\tconst unknown = pending.find((result) => !issued.has(result.toolCallId));\n\tif (unknown !== undefined)\n\t\tthrow new ToolDetachmentError(\"unknown-tool-call\", { sessionId, toolCallId: unknown.toolCallId });\n\tif (pending.length === 0 && !(endsOnDetachableTurn && [...issued.keys()].every((id) => recorded.has(id)))) return;\n\tconst detached = states.get(this)?.detached;\n\tfor (const result of pending) detached?.delete(result.toolCallId);\n\t// The turn continues only once every detachable call it issued has a result; until then the results wait for it.\n\tif (calls.some(({ toolCall }) => !recorded.has(toolCall.id))) {\n\t\tawait recordWithoutContinuing(this, answers);\n\t\treturn;\n\t}\n\tawait this._runAgentContinuation(() => recordAnswers(this, answers));\n\tdeliverHeldTaskCompletions(this);\n}\n\nexport const agentSessionDetachedToolMethods = {\n\tsetToolDetachment,\n\thasPendingDetachedTurn,\n\ttakeDetachedToolCalls,\n\tredispatchDetachedToolCalls,\n\tresumeDetachedTurn,\n};\n"]}
1
+ {"version":3,"file":"agent-session-detached-tools.js","sourceRoot":"","sources":["../../src/core/agent-session-detached-tools.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAUrD,OAAO,EAAE,0BAA0B,EAAE,MAAM,0BAA0B,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAwB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACzF,OAAO,EAAE,4BAA4B,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAChG,OAAO,EACN,sBAAsB,GAGtB,MAAM,6BAA6B,CAAC;AA6CrC,MAAM,MAAM,GAAG,IAAI,OAAO,EAA2B,CAAC;AAEtD,MAAM,yBAAyB,GAC9B,sFAAsF,CAAC;AAExF,SAAS,eAAe,CAAC,OAAqB;IAC7C,IAAI,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAChC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,KAAK,GAAG;YACP,MAAM,EAAE,SAAS;YACjB,QAAQ,EAAE,IAAI,GAAG,EAAE;YACnB,QAAQ,EAAE,IAAI,GAAG,EAAE;YACnB,WAAW,EAAE,IAAI,GAAG,EAAE;YACtB,YAAY,EAAE,IAAI,GAAG,EAAE;YACvB,KAAK,EAAE,IAAI,GAAG,EAAE;SAChB,CAAC;QACF,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,C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AAM,IAAI,OAAO;QAAE,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAClE,iHAAiH;IACjH,IAAI,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;QAC9D,MAAM,uBAAuB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC7C,OAAO;IACR,CAAC;IACD,MAAM,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CAAC,aAAa,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;IACrE,0BAA0B,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,iBAAiB;IACjB,sBAAsB;IACtB,qBAAqB;IACrB,0BAA0B;IAC1B,2BAA2B;IAC3B,kBAAkB;CAClB,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { AssistantMessage, ToolCall, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAfterToolCallResult,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tAgentToolResult,\n} from \"@earendil-works/pi-agent-core\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { deliverHeldTaskCompletions } from \"./agent-session-tasks.js\";\nimport { finalizeToolResult } from \"./agent-session-tool-hooks.ts\";\nimport { reportDebug } from \"./debug.ts\";\nimport { type ErrorFieldValue, serializeErrorCause } from \"./error-contract.ts\";\nimport type { ExtensionToolContext } from \"./extensions/context-types.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { MAX_TOOL_DETACHMENT_AFTER_MS, ToolDetachmentError } from \"./tool-detachment-errors.ts\";\nimport {\n\tresolveToolConcurrency,\n\ttype ToolConcurrencyMode,\n\ttype ToolExecutionScheduler,\n} from \"./tools/tool-concurrency.ts\";\n\n/** How long a call of a `detachable` tool runs inline before the session lets it go on without the session. */\nexport interface ToolDetachmentPolicy {\n\t/** Milliseconds a detachable call may run inline; a call still running after that detaches. */\n\treadonly afterMs: number;\n}\n\n/** The outcome of a detached tool call, in the shape the agent loop records as that call's result. */\nexport interface DetachedToolResult {\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\treadonly result: AgentToolResult;\n\treadonly isError: boolean;\n}\n\n/** A tool call that outlived the run that issued it. */\nexport interface DetachedToolCall {\n\treadonly toolCallId: string;\n\treadonly toolName: string;\n\t/** Settles once the operation ends. Never rejects: a thrown error becomes an `isError` result. */\n\treadonly result: Promise<DetachedToolResult>;\n\t/** Cancel the operation; `reason` reaches the tool through its abort signal. */\n\tabort(reason?: Error | DOMException | string): void;\n}\n\ninterface DetachmentState {\n\tpolicy: ToolDetachmentPolicy | undefined;\n\t/** Calls detached by the session's runs and not yet taken by the host. */\n\treadonly detached: Map<string, DetachedToolCall>;\n\t/** How each detachable tool's work starts, and the session's context for a call of it, by tool name. */\n\treadonly executes: Map<string, DetachableWork>;\n\treadonly concurrency: Map<string, AgentTool[\"concurrency\"]>;\n\t/** For a tool that detaches only some of its calls, which ones, by tool name. */\n\treadonly detachesCall: Map<string, DetachesCall>;\n\t/** What the session's calls still running hold of it: their places in its tool scheduler. */\n\treadonly holds: Set<CallHold>;\n}\n\n/** How a detachable tool's work starts, and the session's tool context for a call of it. */\ninterface DetachableWork {\n\treadonly execute: DetachableExecute;\n\treadonly context: DetachableContext;\n}\n\nconst states = new WeakMap<object, DetachmentState>();\n\nconst DETACHED_PLACEHOLDER_TEXT =\n\t\"This tool call continues after the run ends; its result is recorded when it arrives.\";\n\nfunction detachmentState(session: AgentSession): DetachmentState {\n\tlet state = states.get(session);\n\tif (state === undefined) {\n\t\tstate = {\n\t\t\tpolicy: undefined,\n\t\t\tdetached: new Map(),\n\t\t\texecutes: new Map(),\n\t\t\tconcurrency: new Map(),\n\t\t\tdetachesCall: new Map(),\n\t\t\tholds: new Set(),\n\t\t};\n\t\tstates.set(session, state);\n\t}\n\treturn state;\n}\n\n/** Whether the host set a detachment policy on this session, so its detachable calls may outlive its runs. */\nexport function hasToolDetachment(session: AgentSession): boolean {\n\treturn states.get(session)?.policy !== undefined;\n}\n\nexport function isDetachedToolCall(session: AgentSession, toolCallId: string): boolean {\n\treturn states.get(session)?.detached.has(toolCallId) === true;\n}\n\n/** Whether `toolCallId` is a call of the assistant message the loop is executing, not a call nested inside a tool. */\nfunction isTopLevelToolCall(session: AgentSession, toolCallId: string): boolean {\n\tconst messages = session.agent.state.messages;\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message?.role !== \"assistant\") continue;\n\t\treturn message.content.some((part) => part.type === \"toolCall\" && part.id === toolCallId);\n\t}\n\treturn false;\n}\n\nfunction errorToolResult(error: Error | DOMException | string | object): AgentToolResult {\n\tconst failure = typedFailure(error);\n\treturn {\n\t\tcontent: [{ type: \"text\", text: error instanceof Error ? error.message : String(error) }],\n\t\tdetails: failure === undefined ? undefined : { error: failure },\n\t};\n}\n\n/**\n * The typed failure a detached call's error result carries in `details.error`, so a host branches on its `code`\n * instead of its text: the error's own JSON form when it has one, otherwise what its properties give. An error whose\n * `toJSON()` throws gets the latter too, marked `serialization: \"fallback\"`. Undefined for an error without a string\n * `code`.\n */\nfunction typedFailure(error: Error | DOMException | string | object): DetachedCallFailure | undefined {\n\tif (!(error instanceof Error)) return undefined;\n\tconst { code } = error as { readonly code?: unknown };\n\tif (typeof code !== \"string\") return undefined;\n\tconst json = (error as { readonly toJSON?: () => DetachedCallFailure }).toJSON;\n\tif (typeof json !== \"function\") return failureOf(error, code);\n\ttry {\n\t\treturn json.call(error);\n\t} catch {\n\t\treturn { ...failureOf(error, code), serialization: \"fallback\" };\n\t}\n}\n\nfunction failureOf(error: Error, code: string): DetachedCallFailure {\n\tconst { hint, retryable, fields } = error as {\n\t\treadonly hint?: unknown;\n\t\treadonly retryable?: unknown;\n\t\treadonly fields?: unknown;\n\t};\n\tconst cause = serializeErrorCause(error.cause);\n\treturn {\n\t\tname: error.name,\n\t\tcode,\n\t\tmessage: error.message,\n\t\t...(typeof hint === \"string\" ? { hint } : {}),\n\t\t...(typeof retryable === \"boolean\" ? { retryable } : {}),\n\t\t...(isErrorFields(fields) ? { fields } : {}),\n\t\t...(cause === undefined ? {} : { cause }),\n\t};\n}\n\nfunction isErrorFields(value: unknown): value is Readonly<Record<string, ErrorFieldValue>> {\n\tif (typeof value !== \"object\" || value === null || Object.getPrototypeOf(value) !== Object.prototype) return false;\n\treturn Object.values(value).every(\n\t\t(field) => field === null || [\"string\", \"number\", \"boolean\"].includes(typeof field),\n\t);\n}\n\n/** A cause in a {@link DetachedCallFailure}'s chain, without stack traces. */\nexport type DetachedCallFailureCause = {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly code?: string;\n\treadonly cause?: DetachedCallFailureCause;\n};\n\n/** A detached call's typed failure, as its error result's `details.error` reports it. */\nexport type DetachedCallFailure = {\n\treadonly name: string;\n\treadonly code: string;\n\treadonly message: string;\n\treadonly hint?: string;\n\treadonly retryable?: boolean;\n\treadonly fields?: Readonly<Record<string, ErrorFieldValue>>;\n\treadonly cause?: DetachedCallFailureCause;\n\t/** The error's own `toJSON()` threw, so this carries only what the error's properties give. */\n\treadonly serialization?: \"fallback\";\n};\n\n/**\n * Runs a callback in the async context of this module's load, outside every session. A detachable call's work and\n * every reaction waiting on it start here: a promise reaction keeps the async context it was created in alive, so work\n * started inside a session would keep that session reachable for as long as the call runs.\n */\nconst outsideAnySession = AsyncLocalStorage.snapshot();\n\ntype ToolParams = Parameters<AgentTool[\"execute\"]>[1];\ntype ToolUpdate = Parameters<AgentTool[\"execute\"]>[3];\n\n/**\n * Starts a detachable call's work directly on its tool definition, outside the session's tool wrappers: a wrapper\n * awaiting the work would hold the session's extension runner for as long as the call waits.\n */\nexport type DetachableExecute = (\n\ttoolCallId: string,\n\tparams: ToolParams,\n\tsignal: AbortSignal,\n\tonUpdate: ToolUpdate,\n\tcontext: ExtensionToolContext,\n) => ReturnType<AgentTool[\"execute\"]>;\n\n/** The session's tool context for a call, bound to the call's own abort signal. */\nexport type DetachableContext = (toolCallId: string, signal: AbortSignal) => ExtensionToolContext;\n\n/** Whether one call of a tool may detach, decided from the call's arguments. */\nexport type DetachesCall = (params: ToolParams) => boolean;\n\nconst readinessCallbacks = new WeakMap<AbortSignal, () => void>();\n\n/** Marks the durable handoff of a call ready for detachment. No-op without a waiting detachment policy. */\nexport function markToolCallReadyForDetachment(signal: AbortSignal): void {\n\treadinessCallbacks.get(signal)?.();\n}\n\n/** Whether this call must prepare a durable handoff before it can detach. */\nexport function toolCallNeedsDetachmentHandoff(signal: AbortSignal | undefined): boolean {\n\treturn signal !== undefined && readinessCallbacks.has(signal);\n}\n\n/**\n * What a detachable call's work reaches of its session, only while the call runs inline. Detaching clears it, so\n * the work keeps neither the agent loop nor the session's context reachable for as long as it goes on.\n */\ninterface InlineSession {\n\tonUpdate: ToolUpdate;\n\tcontext: ExtensionToolContext | undefined;\n}\n\n/** Session-free facts a detached call's context still answers. */\ninterface DetachedCallFacts {\n\treadonly sessionId: string;\n\treadonly toolCallId: string;\n\treadonly cwd: string;\n}\n\n/** The session's tool context for a call started again, or undefined once the session has closed. */\ntype StartingContext = (toolCallId: string, signal: AbortSignal) => ExtensionToolContext | undefined;\n\n/** When a detachable call's work starts, and what of the session's context it has. */\ninterface OperationStart {\n\t/** The session's context for a call that starts inline: the work keeps it until the call detaches. */\n\treadonly inlineContext?: DetachableContext;\n\t/** The session's context for a call started again: the work has it only while it starts, until its first await. */\n\treadonly startingContext?: StartingContext;\n\t/** `now` starts the work before returning; a promise starts it once it resolves; absent, on the next tick. */\n\treadonly when?: \"now\" | Promise<void>;\n}\n\n/*\n * The helpers below are module-level on purpose. A closure keeps every scope it is nested in, so a reaction created\n * inside a function that can see the session would keep the session reachable while the call waits.\n */\n\n/**\n * What a running detachable call holds of its session: its place in the session's tool scheduler, so an exclusive\n * call never overlaps another, and the gate its run waits on while the call runs inline. The call's one reaction to\n * its work settling lets both go; closing the session lets the place go first, since nothing is scheduled there any\n * more, so a call that outlives its session keeps none of the scheduler's state (#4403).\n */\ninterface CallHold {\n\tpermit: SchedulerPermit | undefined;\n\tgate: ((value: symbol) => void) | undefined;\n\tholds: Set<CallHold> | undefined;\n}\n\nfunction holdCall(holds: Set<CallHold>, permit: SchedulerPermit): CallHold {\n\tconst hold: CallHold = { permit, gate: undefined, holds };\n\tholds.add(hold);\n\treturn hold;\n}\n\n/** The call's work settled: give its place in the scheduler back and open the gate of a run waiting inline. */\nfunction letGo(hold: CallHold): void {\n\tconst { permit, gate } = hold;\n\thold.permit = undefined;\n\thold.gate = undefined;\n\thold.holds?.delete(hold);\n\thold.holds = undefined;\n\tpermit?.release();\n\tgate?.(INLINE);\n}\n\n/**\n * Give back the scheduler places of the session's calls still running, once the session is closing and nothing new\n * is scheduled on it. While a call still waits for its place behind them, as a reopened session's redispatched calls\n * can, they all keep their places, so that call starts only once the work before it has settled. The calls go on;\n * each still delivers its result when its work settles.\n */\nexport function releaseDetachedCallHolds(session: AgentSession): void {\n\tconst holds = states.get(session)?.holds;\n\tif (holds === undefined || [...holds].some((hold) => hold.permit?.granted() === false)) return;\n\tfor (const hold of holds) {\n\t\tconst permit = hold.permit;\n\t\thold.permit = undefined;\n\t\thold.holds = undefined;\n\t\tpermit?.release();\n\t}\n\tholds.clear();\n}\n\nfunction startOperation(\n\ttoolName: string,\n\texecute: DetachableExecute,\n\tparams: ToolParams,\n\tinline: InlineSession,\n\tfacts: DetachedCallFacts,\n\thold: CallHold,\n\tstart: OperationStart,\n): { readonly call: DetachedToolCall; readonly settled: Promise<AgentToolResult>; readonly signal: AbortSignal } {\n\treturn outsideAnySession(() => {\n\t\tconst controller = new AbortController();\n\t\tif (start.inlineContext !== undefined) inline.context = start.inlineContext(facts.toolCallId, controller.signal);\n\t\tconst onUpdate = inline.onUpdate === undefined ? undefined : forwardedUpdate(inline);\n\t\tconst context = callContext(inline, facts);\n\t\tconst begin = (): ReturnType<AgentTool[\"execute\"]> =>\n\t\t\tbeginWork(execute, facts.toolCallId, params, controller.signal, onUpdate, context, inline, start);\n\t\tconst settled =\n\t\t\tstart.when === \"now\"\n\t\t\t\t? new Promise<AgentToolResult>((resolve) => resolve(begin()))\n\t\t\t\t: (start.when ?? Promise.resolve()).then(begin);\n\t\treturn {\n\t\t\tsettled,\n\t\t\tsignal: controller.signal,\n\t\t\tcall: {\n\t\t\t\ttoolCallId: facts.toolCallId,\n\t\t\t\ttoolName,\n\t\t\t\tresult: settledResult(toolName, facts.toolCallId, settled, hold),\n\t\t\t\tabort: abortWith(controller),\n\t\t\t},\n\t\t};\n\t});\n}\n\nfunction beginWork(\n\texecute: DetachableExecute,\n\ttoolCallId: string,\n\tparams: ToolParams,\n\tsignal: AbortSignal,\n\tonUpdate: ToolUpdate,\n\tcontext: ExtensionToolContext,\n\tinline: InlineSession,\n\tstart: OperationStart,\n): ReturnType<AgentTool[\"execute\"]> {\n\tif (start.startingContext === undefined) return execute(toolCallId, params, signal, onUpdate, context);\n\tinline.context = start.startingContext(toolCallId, signal);\n\ttry {\n\t\treturn execute(toolCallId, params, signal, onUpdate, context);\n\t} finally {\n\t\tinline.context = undefined;\n\t}\n}\n\n/** Progress a call reports reaches the agent loop while the call runs inline; once it detaches, it is dropped. */\nfunction forwardedUpdate(inline: InlineSession): NonNullable<ToolUpdate> {\n\treturn (partialResult) => inline.onUpdate?.(partialResult);\n}\n\n/**\n * The context a detachable call's work receives: the session's tool context while the call runs inline. Once the call\n * detaches it answers only `cwd`, and any other use throws {@link ToolDetachmentError} `context-detached`.\n */\nfunction callContext(inline: InlineSession, facts: DetachedCallFacts): ExtensionToolContext {\n\treturn new Proxy({} as ExtensionToolContext, {\n\t\tget(_target, key) {\n\t\t\tconst live = inline.context;\n\t\t\tif (live !== undefined) return Reflect.get(live, key);\n\t\t\tif (key === \"cwd\") return facts.cwd;\n\t\t\t// Not a thenable, and nothing for inspection to find.\n\t\t\tif (key === \"then\" || typeof key === \"symbol\") return undefined;\n\t\t\tthrow new ToolDetachmentError(\"context-detached\", {\n\t\t\t\tsessionId: facts.sessionId,\n\t\t\t\ttoolCallId: facts.toolCallId,\n\t\t\t});\n\t\t},\n\t\thas(_target, key) {\n\t\t\tconst live = inline.context;\n\t\t\treturn live === undefined ? key === \"cwd\" : Reflect.has(live, key);\n\t\t},\n\t});\n}\n\n/**\n * The call's one reaction to its work settling: it lets the call's hold go and makes the call's result. It is built\n * apart from the call's abort, so it keeps the call's names and hold, not its controller.\n */\nfunction settledResult(\n\ttoolName: string,\n\ttoolCallId: string,\n\tsettled: Promise<AgentToolResult>,\n\thold: CallHold,\n): Promise<DetachedToolResult> {\n\treturn settled.then(\n\t\t(value): DetachedToolResult => {\n\t\t\tletGo(hold);\n\t\t\treturn { toolCallId, toolName, result: value, isError: value.isError === true };\n\t\t},\n\t\t(error: Error | DOMException | string | object): DetachedToolResult => {\n\t\t\tletGo(hold);\n\t\t\treturn { toolCallId, toolName, result: errorToolResult(error), isError: true };\n\t\t},\n\t);\n}\n\nfunction abortWith(controller: AbortController): DetachedToolCall[\"abort\"] {\n\treturn (reason) => controller.abort(reason);\n}\n\nconst INLINE = Symbol(\"inline\");\nconst DETACH = Symbol(\"detach\");\n\ninterface SchedulerPermit {\n\treadonly grantedLater: Promise<void> | undefined;\n\t/** Whether the scheduler has given the call its place yet. */\n\tgranted(): boolean;\n\trelease(): void;\n}\n\nfunction takeSchedulerPermit(scheduler: ToolExecutionScheduler, mode: ToolConcurrencyMode): SchedulerPermit {\n\treturn outsideAnySession(() => {\n\t\tconst granted = Promise.withResolvers<void>();\n\t\tconst held = Promise.withResolvers<void>();\n\t\tlet grantedNow = false;\n\t\tvoid scheduler.schedule(mode, () => {\n\t\t\tgrantedNow = true;\n\t\t\tgranted.resolve();\n\t\t\treturn held.promise;\n\t\t});\n\t\treturn {\n\t\t\tgrantedLater: grantedNow ? undefined : granted.promise,\n\t\t\tgranted: () => grantedNow,\n\t\t\trelease: () => held.resolve(),\n\t\t};\n\t});\n}\n\n/** Forget the session's detachable tools before its tools are registered again, so a removed tool is not one. */\nexport function forgetDetachableTools(session: AgentSession): void {\n\tconst state = states.get(session);\n\tstate?.executes.clear();\n\tstate?.concurrency.clear();\n\tstate?.detachesCall.clear();\n}\n\n/**\n * Run a call of a detachable tool inline until the session's detachment policy elapses, then let it go on without\n * the run. The loop then records a placeholder that never reaches the transcript, listeners, or the provider, and\n * the run ends after its turn so the host can release the session and hand the result back later.\n *\n * The call keeps its declared concurrency: it starts once the calls before it in the session's scheduler allow, and\n * it holds its place there until its work settles, also after it detaches, so an exclusive call never overlaps another\n * call of the session. Closing the session gives the place back.\n */\nexport function detachableTool(\n\tsession: AgentSession,\n\ttool: AgentTool,\n\texecute: DetachableExecute,\n\tcreateContext: DetachableContext,\n\tdetachesCall?: DetachesCall,\n\trequiresReady = false,\n): AgentTool {\n\tconst state = detachmentState(session);\n\tstate.executes.set(tool.name, { execute, context: createContext });\n\tstate.concurrency.set(tool.name, tool.concurrency);\n\tif (detachesCall !== undefined) state.detachesCall.set(tool.name, detachesCall);\n\treturn {\n\t\t...tool,\n\t\texecute: async (toolCallId, params, signal, onUpdate) => {\n\t\t\tconst policy = state.policy;\n\t\t\tif (policy === undefined || !isTopLevelToolCall(session, toolCallId) || detachesCall?.(params) === false)\n\t\t\t\treturn tool.execute(toolCallId, params, signal, onUpdate);\n\t\t\tconst permit = takeSchedulerPermit(\n\t\t\t\tsession._toolExecutionScheduler,\n\t\t\t\tresolveToolConcurrency(tool.concurrency, params as Record<string, unknown>),\n\t\t\t);\n\t\t\tif (permit.grantedLater !== undefined) await permit.grantedLater;\n\t\t\tconst hold = holdCall(state.holds, permit);\n\t\t\tconst inline: InlineSession = { onUpdate, context: undefined };\n\t\t\tlet operation: ReturnType<typeof startOperation>;\n\t\t\ttry {\n\t\t\t\toperation = startOperation(\n\t\t\t\t\ttool.name,\n\t\t\t\t\texecute,\n\t\t\t\t\tparams,\n\t\t\t\t\tinline,\n\t\t\t\t\tdetachedCallFacts(session, toolCallId),\n\t\t\t\t\thold,\n\t\t\t\t\t{ inlineContext: createContext },\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tletGo(hold);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst { call, settled, signal: operationSignal } = operation;\n\t\t\tconst forwardAbort = (): void => call.abort(signal?.reason);\n\t\t\tif (signal?.aborted) forwardAbort();\n\t\t\telse signal?.addEventListener(\"abort\", forwardAbort, { once: true });\n\t\t\t// The run waits on this gate alone: it settles at the threshold even while the call goes on, so no reaction\n\t\t\t// created in the run's context stays on the call once it detaches.\n\t\t\tconst gate = Promise.withResolvers<symbol>();\n\t\t\thold.gate = gate.resolve;\n\t\t\tlet ready = !requiresReady;\n\t\t\tlet elapsed = false;\n\t\t\tif (requiresReady)\n\t\t\t\treadinessCallbacks.set(operationSignal, () => {\n\t\t\t\t\tready = true;\n\t\t\t\t\tif (elapsed) gate.resolve(DETACH);\n\t\t\t\t});\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\telapsed = true;\n\t\t\t\tif (ready) gate.resolve(DETACH);\n\t\t\t}, policy.afterMs);\n\t\t\ttry {\n\t\t\t\tif ((await gate.promise) === INLINE) return await settled;\n\t\t\t} finally {\n\t\t\t\thold.gate = undefined;\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treadinessCallbacks.delete(operationSignal);\n\t\t\t\tsignal?.removeEventListener(\"abort\", forwardAbort);\n\t\t\t}\n\t\t\tinline.onUpdate = undefined;\n\t\t\tinline.context = undefined;\n\t\t\tstate.detached.set(toolCallId, call);\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: DETACHED_PLACEHOLDER_TEXT }],\n\t\t\t\tdetails: undefined,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction detachedCallFacts(session: AgentSession, toolCallId: string): DetachedCallFacts {\n\treturn { sessionId: session.sessionManager.getSessionId(), toolCallId, cwd: session._cwd };\n}\n\nfunction isDetachedPlaceholder(detached: ReadonlyMap<string, DetachedToolCall>, message: AgentMessage): boolean {\n\treturn message.role === \"toolResult\" && detached.has((message as ToolResultMessage).toolCallId);\n}\n\n/**\n * The placeholder a detached call leaves in the loop is no tool result: drop its events, take it out of the live\n * transcript, and leave it out of the turn and run summaries. Returns the event to process, or `undefined`.\n */\nexport function withoutDetachedPlaceholders(session: AgentSession, event: AgentEvent): AgentEvent | undefined {\n\tconst detached = states.get(session)?.detached;\n\tif (detached === undefined || detached.size === 0) return event;\n\tswitch (event.type) {\n\t\tcase \"tool_execution_end\":\n\t\t\treturn detached.has(event.toolCallId) ? undefined : event;\n\t\tcase \"message_start\":\n\t\t\treturn isDetachedPlaceholder(detached, event.message) ? undefined : event;\n\t\tcase \"message_end\": {\n\t\t\tif (!isDetachedPlaceholder(detached, event.message)) return event;\n\t\t\t// Agent-core appended the placeholder to its live transcript before notifying listeners.\n\t\t\tconst messages = session.agent.state.messages;\n\t\t\tconst index = messages.lastIndexOf(event.message);\n\t\t\tif (index >= 0) messages.splice(index, 1);\n\t\t\treturn undefined;\n\t\t}\n\t\tcase \"turn_end\": {\n\t\t\tconst toolResults = event.toolResults.filter((result) => !detached.has(result.toolCallId));\n\t\t\treturn toolResults.length === event.toolResults.length ? event : { ...event, toolResults };\n\t\t}\n\t\tcase \"agent_end\": {\n\t\t\tconst messages = event.messages.filter((message) => !isDetachedPlaceholder(detached, message));\n\t\t\treturn messages.length === event.messages.length ? event : { ...event, messages };\n\t\t}\n\t\tdefault:\n\t\t\treturn event;\n\t}\n}\n\nexport function setToolDetachment(this: AgentSession, policy: ToolDetachmentPolicy | undefined): void {\n\tif (\n\t\tpolicy !== undefined &&\n\t\t!(Number.isFinite(policy.afterMs) && policy.afterMs >= 0 && policy.afterMs <= MAX_TOOL_DETACHMENT_AFTER_MS)\n\t)\n\t\tthrow new ToolDetachmentError(\"invalid-policy\", {\n\t\t\tsessionId: this.sessionManager.getSessionId(),\n\t\t\tfield: \"afterMs\",\n\t\t\tvalue: String(policy.afterMs),\n\t\t});\n\tdetachmentState(this).policy = policy === undefined ? undefined : { afterMs: policy.afterMs };\n}\n\nexport function takeDetachedToolCalls(this: AgentSession): DetachedToolCall[] {\n\tconst detached = states.get(this)?.detached;\n\tif (detached === undefined) return [];\n\tconst calls = [...detached.values()];\n\tdetached.clear();\n\treturn calls.filter((call) => !settleStaleCall(this, call));\n}\n\n/**\n * Settle a parked call whose turn the transcript has moved past: nothing waits on its result any more, so cancel its\n * work and report it, so the host never waits for it. Says whether the call was dropped.\n */\nfunction settleStaleCall(session: AgentSession, call: DetachedToolCall): boolean {\n\tif (!transcriptMovedPast(session, call.toolCallId)) return false;\n\treportStaleDetachedCall(session, call);\n\tcall.abort(new DOMException(\"The transcript moved past this detached tool call\", \"AbortError\"));\n\treturn true;\n}\n\n/** The reasons a detached call is dropped: its turn is no longer the one the transcript ends on. */\ntype StaleDetachedCallReason = \"transcript-moved\";\n\n/** The debug record of a detached call the session dropped as stale: no exception, nothing for the host to handle. */\nfunction reportStaleDetachedCall(\n\tsession: AgentSession,\n\tcall: Pick<DetachedToolCall, \"toolCallId\" | \"toolName\">,\n\treason: StaleDetachedCallReason = \"transcript-moved\",\n): void {\n\treportDebug(\"workflow\", \"stale-detached-call\", {\n\t\tsessionId: session.sessionManager.getSessionId(),\n\t\ttoolCallId: call.toolCallId,\n\t\ttoolName: call.toolName,\n\t\treason,\n\t});\n}\n\n/** Whether an assistant message of the session's history issued `toolCallId`, even one a compaction folded into text. */\nfunction wasIssued(session: AgentSession, toolCallId: string): boolean {\n\treturn session.sessionManager\n\t\t.getBranch()\n\t\t.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"assistant\" &&\n\t\t\t\tentry.message.content.some((block) => block.type === \"toolCall\" && block.id === toolCallId),\n\t\t);\n}\n\n/**\n * Whether `toolCallId` was issued by a turn the transcript no longer ends on, or already has its result: a call whose\n * result nothing waits for. A call no message of the history issued is not one, so it reaches its host's checks.\n */\nfunction transcriptMovedPast(session: AgentSession, toolCallId: string): boolean {\n\treturn wasIssued(session, toolCallId) && !trailingToolTurn(session).awaiting.has(toolCallId);\n}\n\n/** A call of a detachable tool in the transcript, with how its tool's work starts in this session. */\ninterface DetachableCall {\n\treadonly toolCall: ToolCall;\n\treadonly work: DetachableWork;\n}\n\n/**\n * The last assistant message of the transcript when it issued tool calls and nothing but results follows it, and the\n * ids of its calls that have no result yet. Any later user or assistant message means a later turn already moved past\n * the calls: only a transcript that ends on the turn is waiting.\n */\nfunction trailingToolTurn(session: AgentSession): {\n\treadonly assistant: AssistantMessage | undefined;\n\treadonly awaiting: ReadonlySet<string>;\n\treadonly entryId?: string;\n} {\n\tconst none = { assistant: undefined, awaiting: new Set<string>() };\n\tconst projection = session.sessionManager.buildSessionProjection();\n\tconst messages = projection.messages;\n\tlet index = messages.length - 1;\n\twhile (index >= 0 && messages[index]?.role !== \"assistant\") index--;\n\tconst assistant = messages[index] as AssistantMessage | undefined;\n\tif (assistant?.stopReason !== \"toolUse\") return none;\n\tconst later = messages.slice(index + 1);\n\tif (later.some((message) => message.role === \"user\" || message.role === \"assistant\")) return none;\n\tconst answered = new Set(\n\t\tlater.flatMap((message) => (message.role === \"toolResult\" ? [(message as ToolResultMessage).toolCallId] : [])),\n\t);\n\tconst awaiting = new Set(\n\t\tassistant.content.flatMap((block) => (block.type === \"toolCall\" && !answered.has(block.id) ? [block.id] : [])),\n\t);\n\tconst entryId = projection.entries.find((entry) => entry.messages.includes(assistant))?.sourceEntry.id;\n\treturn { assistant, awaiting, ...(entryId === undefined ? {} : { entryId }) };\n}\n\n/**\n * The id of the history entry of the turn that still waits for a call's result, or undefined when none does. A\n * compaction keeps this turn out of what it folds into text, whatever entries came after it (#4580).\n */\nexport function awaitedToolTurnEntryId(session: AgentSession): string | undefined {\n\tconst { awaiting, entryId } = trailingToolTurn(session);\n\treturn awaiting.size > 0 ? entryId : undefined;\n}\n\n/**\n * The last assistant message of the transcript, the calls of detachable tools it is still waiting on, and whether that\n * message issued a detachable call at all: a transcript that ends on such a turn has not had the model's answer yet.\n * A tool is detachable in this session when the session registered how its work starts.\n */\nfunction pendingDetachableCalls(session: AgentSession): {\n\treadonly assistant: AssistantMessage | undefined;\n\treadonly calls: readonly DetachableCall[];\n\treadonly endsOnDetachableTurn: boolean;\n} {\n\tconst { assistant, awaiting } = trailingToolTurn(session);\n\tif (assistant === undefined) return { assistant, calls: [], endsOnDetachableTurn: false };\n\tconst state = states.get(session);\n\tconst detachable = assistant.content.flatMap((block): DetachableCall[] => {\n\t\tif (block.type !== \"toolCall\") return [];\n\t\tconst work = state?.executes.get(block.name);\n\t\tif (work === undefined) return [];\n\t\tif (state?.detachesCall.get(block.name)?.(block.arguments as ToolParams) === false) return [];\n\t\treturn [{ toolCall: block as ToolCall, work }];\n\t});\n\treturn {\n\t\tassistant,\n\t\tcalls: detachable.filter(({ toolCall }) => awaiting.has(toolCall.id)),\n\t\tendsOnDetachableTurn: detachable.length > 0,\n\t};\n}\n\n/**\n * Whether the transcript ends on a turn that issued a detachable call and has no answer from the model yet, with or\n * without its results: a session reopened after its process died continues that turn instead of being prompted again.\n */\nexport function hasPendingDetachedTurn(this: AgentSession): boolean {\n\treturn pendingDetachableCalls(this).endsOnDetachableTurn;\n}\n\n/**\n * Whether the transcript ends on a turn still waiting for the result of a call of a detachable tool. Nothing may come\n * between such a call and its result, so input that would land there waits until the turn resumes.\n */\nexport function waitsOnDetachedResults(session: AgentSession): boolean {\n\tif (!states.get(session)?.executes.size) return false;\n\treturn pendingDetachableCalls(session).calls.length > 0;\n}\n\n/**\n * Whether this session must not start a turn of its own: its host set a detachment policy, so it hands back the results\n * of the calls that detached, and its transcript waits on one. A turn that started now would move\n * the transcript past the call; whatever would start it waits, and the turn the hand-back continues takes it up.\n */\nexport function holdsTurnsForDetachedResults(session: AgentSession): boolean {\n\treturn hasToolDetachment(session) && waitsOnDetachedResults(session);\n}\n\n/** Whether the transcript ends on a turn still waiting for the result of a call of a detachable tool. */\nexport function isWaitingOnDetachedResults(this: AgentSession): boolean {\n\treturn waitsOnDetachedResults(this);\n}\n\n/**\n * Mark every call of a detachable tool that the transcript ends on without a result as in flight, not interrupted,\n * until its result is recorded. A workflow stage resumed after its process died starts those calls again, or records\n * the results that process saved, only once its turn resumes; a chat may show the stage's transcript before then, and\n * must not report them interrupted meanwhile (#4022). Says whether any call was pending.\n */\nexport function holdPendingDetachedCalls(session: AgentSession): boolean {\n\tconst pending = pendingDetachableCalls(session).calls;\n\tif (pending.length === 0) return false;\n\tfor (const { toolCall } of pending) session._reissuedToolCallIds.add(toolCall.id);\n\tsession._refreshFinalizedContext();\n\treturn true;\n}\n\n/**\n * Start again every call of a detachable tool that the transcript ends on without a result: the process that ran\n * them is gone. Each runs with its original id and arguments, so a call may run more than once. Hosts see each call\n * start again, and its result is recorded as that call's once it is handed back. The work has the session's tool\n * context only while it starts, up to its first `await`; from then on its context answers only `cwd`, and it reports\n * no progress. A call the session's scheduler queues behind another gets that context when it starts, if the session\n * is still open then.\n */\nexport function redispatchDetachedToolCalls(this: AgentSession): DetachedToolCall[] {\n\tconst pending = pendingDetachableCalls(this).calls;\n\tif (pending.length === 0) return [];\n\tconst state = detachmentState(this);\n\tfor (const { toolCall } of pending) this._reissuedToolCallIds.add(toolCall.id);\n\tthis._refreshFinalizedContext();\n\treturn pending.map(({ toolCall, work }) => {\n\t\tannounceRestartedCall(this, toolCall);\n\t\tconst inline: InlineSession = { onUpdate: undefined, context: undefined };\n\t\tconst facts = detachedCallFacts(this, toolCall.id);\n\t\tconst params = toolCall.arguments as ToolParams;\n\t\tconst permit = takeSchedulerPermit(\n\t\t\tthis._toolExecutionScheduler,\n\t\t\tresolveToolConcurrency(state.concurrency.get(toolCall.name), params as Record<string, unknown>),\n\t\t);\n\t\treturn startOperation(toolCall.name, work.execute, params, inline, facts, holdCall(state.holds, permit), {\n\t\t\tstartingContext: whileOpen(this, work.context),\n\t\t\twhen: permit.grantedLater ?? \"now\",\n\t\t}).call;\n\t});\n}\n\n/** The session's tool context, only while the session is open; a closed session's call has none. */\nfunction whileOpen(session: AgentSession, createContext: DetachableContext): StartingContext {\n\treturn (toolCallId, signal) =>\n\t\tsession._disposed || sessionGenerationClosing.has(session) ? undefined : createContext(toolCallId, signal);\n}\n\n/**\n * Hosts see a call started again start, as they see the agent loop start one. Session listeners hear it at once, so a\n * host that releases the session right after starting its calls again has seen them start; extensions hear it through\n * the session's event queue, in order with its other events.\n */\nfunction announceRestartedCall(session: AgentSession, toolCall: ToolCall): void {\n\tconst event: AgentEvent = {\n\t\ttype: \"tool_execution_start\",\n\t\ttoolCallId: toolCall.id,\n\t\ttoolName: toolCall.name,\n\t\targs: toolCall.arguments,\n\t};\n\tsession._emit(event);\n\tsession._agentEventQueue = Promise.allSettled([session._agentEventQueue]).then(() =>\n\t\tsession._emitExtensionEvent(event),\n\t);\n}\n\nfunction resultMessage(result: DetachedToolResult): ToolResultMessage {\n\treturn {\n\t\trole: \"toolResult\",\n\t\ttoolCallId: result.toolCallId,\n\t\ttoolName: result.toolName,\n\t\tcontent: result.result.content,\n\t\tdetails: result.result.details,\n\t\t...(result.result.usage === undefined ? {} : { usage: result.result.usage }),\n\t\tisError: result.isError,\n\t\ttimestamp: Date.now(),\n\t};\n}\n\n/** A result with what the session's finalization replaced, merged the way the agent loop merges an inline call's. */\nfunction withReplacement(\n\tdetached: DetachedToolResult,\n\treplacement: AfterToolCallResult | undefined,\n): DetachedToolResult {\n\tif (replacement === undefined) return detached;\n\tconst { structuredContent: reported, ...rest } = detached.result;\n\t// Structured content not replaced along with the content may no longer match it.\n\tconst structuredContent = replacement.structuredContent ?? (replacement.content ? undefined : reported);\n\treturn {\n\t\t...detached,\n\t\tresult: {\n\t\t\t...rest,\n\t\t\tcontent: replacement.content ?? rest.content,\n\t\t\tdetails: (replacement.details ?? rest.details) as AgentToolResult[\"details\"],\n\t\t\tusage: replacement.usage ?? rest.usage,\n\t\t\t...(structuredContent === undefined ? {} : { structuredContent }),\n\t\t},\n\t\tisError: replacement.isError ?? detached.isError,\n\t};\n}\n\n/** A detached call's result as it enters history: finalized exactly as the result of an inline call is. */\nasync function finalizedResult(\n\tsession: AgentSession,\n\ttoolCall: ToolCall,\n\treported: DetachedToolResult,\n): Promise<DetachedToolResult> {\n\t// A result handed back across a process boundary may omit its content, as an untyped tool's may.\n\tconst detached = { ...reported, result: { ...reported.result, content: reported.result.content ?? [] } };\n\ttry {\n\t\tconst replacement = await finalizeToolResult(session, {\n\t\t\ttoolCall,\n\t\t\targs: toolCall.arguments,\n\t\t\tresult: detached.result,\n\t\t\tisError: detached.isError,\n\t\t\tparentToolCallId: undefined,\n\t\t\treleasedStage: true,\n\t\t});\n\t\treturn withReplacement(detached, replacement);\n\t} catch (error) {\n\t\t// As the agent loop does when an inline call's finalization throws: the call fails with that error.\n\t\treturn { ...detached, result: errorToolResult(error as Error | string | object), isError: true };\n\t}\n}\n\n/**\n * Wait for the save of a result the session just recorded. A save that failed fails the continuation, which rejects\n * with it; the session's event queue goes on past it, as it does past a failed save inside the agent loop, so the\n * session's later barriers and its disposal do not report the same failure again.\n */\nasync function resultSaved(session: AgentSession): Promise<void> {\n\tconst queue = session._agentEventQueue;\n\ttry {\n\t\tawait queue;\n\t} catch (error) {\n\t\tif (session._agentEventQueue === queue) session._agentEventQueue = queue.catch(() => {});\n\t\tthrow error;\n\t}\n}\n\n/** A new result and the call of the pending turn it answers. */\ninterface Answer {\n\treadonly toolCall: ToolCall;\n\treadonly result: DetachedToolResult;\n}\n\n/** Record each answer as its call's result, in the order given, and refresh the session's context from them. */\nasync function recordAnswers(session: AgentSession, answers: readonly Answer[]): Promise<void> {\n\tfor (const answer of answers) session._reissuedToolCallIds.add(answer.result.toolCallId);\n\ttry {\n\t\tfor (const answer of answers) {\n\t\t\tconst result = await finalizedResult(session, answer.toolCall, answer.result);\n\t\t\tconst message = resultMessage(result);\n\t\t\t// Through the session's event pipeline, as the agent loop records a result: hosts see the call end,\n\t\t\t// and the result is persisted as that call's result.\n\t\t\tsession._handleAgentEvent({\n\t\t\t\ttype: \"tool_execution_end\",\n\t\t\t\ttoolCallId: result.toolCallId,\n\t\t\t\ttoolName: result.toolName,\n\t\t\t\tresult: result.result,\n\t\t\t\tisError: result.isError,\n\t\t\t});\n\t\t\tsession._handleAgentEvent({ type: \"message_start\", message });\n\t\t\tsession._handleAgentEvent({ type: \"message_end\", message });\n\t\t\tawait resultSaved(session);\n\t\t}\n\t} finally {\n\t\tfor (const answer of answers) session._reissuedToolCallIds.delete(answer.result.toolCallId);\n\t\tsession._refreshFinalizedContext();\n\t}\n}\n\n/**\n * Record answers of a turn that still waits on other calls, without continuing it. The session counts as running\n * meanwhile, as it does while a continuation records its results, so a second resume is refused as busy instead of\n * recording beside this one, where neither would see the turn complete and continue it.\n */\nfunction recordWithoutContinuing(session: AgentSession, answers: readonly Answer[]): Promise<void> {\n\treturn trackSessionWork(session, async () => {\n\t\tsession._activePromptCount += 1;\n\t\ttry {\n\t\t\tawait recordAnswers(session, answers);\n\t\t} finally {\n\t\t\tsession._activePromptCount -= 1;\n\t\t}\n\t});\n}\n\n/**\n * Record the results of detached calls the transcript is waiting on, each as its own call's result right after its\n * call, then continue the turn that issued them once every detachable call of that turn has its result. Results may\n * arrive together or across several calls: until the last one arrives, the session records what it is given and\n * resolves without continuing. A result for a call that already has one, repeated in `results`, or issued by a turn\n * the transcript has moved past is ignored (the last one is reported in the debug log); a result for a call no\n * message of the transcript issued throws `unknown-tool-call`. With no new result, a transcript that ends on a\n * detachable turn whose every call has its result continues that turn (its process stopped before the model\n * answered), and a turn still waiting on a call is left as it is. Each result is finalized as an inline call's is:\n * extension `tool_result` handlers, image normalization and the oversized-output spill.\n */\nexport async function resumeDetachedTurn(this: AgentSession, results: readonly DetachedToolResult[]): Promise<void> {\n\tconst sessionId = this.sessionManager.getSessionId();\n\t// A closed session records nothing: the results stay with the caller for the session reopened from the store.\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\tthrow new ToolDetachmentError(\"session-closed\", { sessionId });\n\tif (this.isStreaming || this._activePromptCount > 0) throw new ToolDetachmentError(\"session-busy\", { sessionId });\n\tconst { assistant, calls, endsOnDetachableTurn } = pendingDetachableCalls(this);\n\tconst issued = new Map(\n\t\tassistant?.content.flatMap((block) => (block.type === \"toolCall\" ? [[block.id, block] as const] : [])) ?? [],\n\t);\n\tconst recorded = new Set(\n\t\tthis.sessionManager\n\t\t\t.buildSessionProjection()\n\t\t\t.messages.flatMap((message) => (message.role === \"toolResult\" ? [message.toolCallId] : [])),\n\t);\n\tconst given = results.filter((result) => {\n\t\tif (recorded.has(result.toolCallId)) return false;\n\t\trecorded.add(result.toolCallId);\n\t\treturn true;\n\t});\n\t// A result for a turn the transcript moved past answers nothing: it is dropped, not refused, so a host that\n\t// handed it back late goes on; only a call no message issued is refused.\n\tconst stale = given.filter((result) => !issued.has(result.toolCallId) && wasIssued(this, result.toolCallId));\n\tconst unknown = given.find((result) => !issued.has(result.toolCallId) && !stale.includes(result));\n\tif (unknown !== undefined)\n\t\tthrow new ToolDetachmentError(\"unknown-tool-call\", { sessionId, toolCallId: unknown.toolCallId });\n\tconst detached = states.get(this)?.detached;\n\tfor (const result of stale) {\n\t\tdetached?.delete(result.toolCallId);\n\t\treportStaleDetachedCall(this, result);\n\t}\n\tconst pending = given.filter((result) => !stale.includes(result));\n\tconst answers = pending.map((result) => ({ toolCall: issued.get(result.toolCallId)!, result }));\n\tif (pending.length === 0 && !(endsOnDetachableTurn && [...issued.keys()].every((id) => recorded.has(id)))) return;\n\tfor (const result of pending) detached?.delete(result.toolCallId);\n\t// The turn continues only once every detachable call it issued has a result; until then the results wait for it.\n\tif (calls.some(({ toolCall }) => !recorded.has(toolCall.id))) {\n\t\tawait recordWithoutContinuing(this, answers);\n\t\treturn;\n\t}\n\tawait this._runAgentContinuation(() => recordAnswers(this, answers));\n\tdeliverHeldTaskCompletions(this);\n}\n\nexport const agentSessionDetachedToolMethods = {\n\tsetToolDetachment,\n\thasPendingDetachedTurn,\n\ttakeDetachedToolCalls,\n\tisWaitingOnDetachedResults,\n\tredispatchDetachedToolCalls,\n\tresumeDetachedTurn,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-message-queue.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-message-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAe,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAIlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAO9F,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAMhF,OAAO,EAEN,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAEtB,KAAK,kBAAkB,EAEvB,KAAK,kBAAkB,EAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAA8B,MAAM,eAAe,CAAC;AAK/E,OAAO,EAAE,iCAAiC,EAAE,CAAC;AA0B7C;;;GAGG;AACH,wBAAsB,WAAW,CAChC,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,KAAK,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;GAEG;AACH,wBAAsB,cAAc,CACnC,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,E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;;;;;;;CA0B3C,CAAC"}
1
+ {"version":3,"file":"agent-session-message-queue.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-message-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAe,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAKlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAO9F,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAMhF,OAAO,EAEN,KAAK,YAAY,EACjB,KAAK,iBAAiB,EAEtB,KAAK,kBAAkB,EAEvB,KAAK,kBAAkB,EAGvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,KAAK,EAAE,aAAa,EAA8B,MAAM,eAAe,CAAC;AAK/E,OAAO,EAAE,iCAAiC,EAAE,CAAC;AA0B7C;;;GAGG;AACH,wBAAsB,WAAW,CAChC,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,KAAK,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;GAEG;AACH,wBAAsB,cAAc,CACnC,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,KAAK,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAef;AAED;;GAEG;AAEH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAU/E;AAED;;;;;;;;;;;;;GAaG;AAEH,wBAAsB,i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B,GAC1B,OAAO,CAAC,IAAI,CAAC,CAIf;AAED,wBAAgB,+BAA+B,CAAC,IAAI,EAAE,YAAY,GAAG,kBAAkB,CAYtF;AAED,wBAAgB,wCAAwC,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAejF;AAED,wBAAgB,kBAAkB,CACjC,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,YAAY,EACrB,QAAQ,EAAE,OAAO,GAAG,UAAU,GAAG,WAAW,GAC1C,IAAI,CAyBN;AAED,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,kBAAkB,CAShF;AAED,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,kBAAkB,GAAG,IAAI,CAOhG;AACD;;GAEG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,YAAY,CAyExF;AAED,wEAAwE;AACxE,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,GAAG,SAAS,MAAM,EAAE,CAGzE;AAED,iDAAiD;AACjD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,GAAG,SAAS,MAAM,EAAE,CAGzE;AAMD,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,GAAG,eAAe,GAAG,IAAI,CAGvF;AAED;;;GAGG;AAEH,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,GAAG,eAAe,GAAG,IAAI,CAGvF;AAKD,eAAO,MAAM,+BAA+B;;;;;;;;;;;;;;;;;;;;;;;;;;CA0B3C,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { commitAdmittedCustomMessage, commitAdmittedCustomMessages } from "./agent-session-custom-message-commit.js";
2
2
  import { forwardedMessageOptions, resolveWorkflowStageDeliveryTarget } from "./agent-session-delivery-forwarding.js";
3
+ import { holdsTurnsForDetachedResults } from "./agent-session-detached-tools.js";
3
4
  import { cancelHeldInput, heldInputView } from "./agent-session-held-input.js";
4
5
  import { recordPersistenceFailure } from "./agent-session-persistence-failures.js";
5
6
  import { isProtectedStreamingCustomMessage, restoreProtectedStreamingCustomMessages, } from "./agent-session-persistent-custom-messages.js";
@@ -297,7 +298,7 @@ async function sendInterruptCustomMessageUnlocked(session, message, options) {
297
298
  assertSessionOpen(session);
298
299
  if (lifetime.aborted)
299
300
  throw Object.assign(new Error("Session is closed"), { code: "SessionClosed" });
300
- if (session._queuedMessagesPaused) {
301
+ if (session._queuedMessagesPaused || holdsTurnsForDetachedResults(session)) {
301
302
  session._queueAgentMessage(message, "steer");
302
303
  return;
303
304
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-message-queue.js","sourceRoot":"","sources":["../../src/core/agent-session-message-queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACrH,OAAO,EAAE,uBAAuB,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AACrH,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AACnF,OAAO,EACN,iCAAiC,EACjC,uCAAuC,GACvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACrG,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACN,yBAAyB,EACzB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAIN,4BAA4B,EAE5B,sBAAsB,EAEtB,8BAA8B,EAC9B,kBAAkB,GAClB,MAAM,0BAA0B,CAAC;AAGlC,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cAAc;IACd,wBAAwB;IACxB,iCAAiC;IACjC,2BAA2B;IAC3B,iBAAiB;IACjB,kBAAkB;IAClB,4BAA4B;IAC5B,oBAAoB;IACpB,2BAA2B;IAC3B,8BAA8B;IAC9B,8BAA8B;IAC9B,+BAA+B;IAC/B,wCAAwC;IACxC,mBAAmB;IACnB,oBAAoB;IACpB,kBAAkB;IAClB,yBAAyB;IACzB,2BAA2B;IAC3B,UAAU;IACV,mBAAmB;IACnB,mBAAmB;IACnB,KAAK;IACL,eAAe;IACf,eAAe;CACf,CAAC","sourcesContent":["import type { ImageContent, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { commitAdmittedCustomMessage, commitAdmittedCustomMessages } from \"./agent-session-custom-message-commit.ts\";\nimport { forwardedMessageOptions, resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport { cancelHeldInput, heldInputView } from \"./agent-session-held-input.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { recordPersistenceFailure } from \"./agent-session-persistence-failures.ts\";\nimport {\n\tisProtectedStreamingCustomMessage,\n\trestoreProtectedStreamingCustomMessages,\n} from \"./agent-session-persistent-custom-messages.ts\";\nimport { markQueuedMessageImages, waitForCustomMessagePreparation } from \"./agent-session-prompt.ts\";\nimport { abort, pauseQueuedMessages, resumeQueuedMessages } from \"./agent-session-queue-pause.ts\";\nimport { transferWorkflowStageDeliveriesTo } from \"./agent-session-transfer.ts\";\nimport {\n\tforgetAllTypedQueuedTexts,\n\tforgetTypedQueuedText,\n\trememberTypedQueuedText,\n} from \"./agent-session-typed-queue.ts\";\nimport {\n\ttype AgentQueueAccess,\n\ttype ClearedQueue,\n\ttype ClearQueueOptions,\n\tcustomMessageExcludesContext,\n\ttype DrainedAgentQueues,\n\tdrainAgentMessageQueue,\n\ttype InterruptQueueHold,\n\tnormalizeInterruptAbortMessage,\n\tpriorityHoldCounts,\n} from \"./agent-session-types.js\";\nimport type { SendMessageOptions, SendMessagesOptions } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\nimport { withOwnResourceAdmission } from \"./resource-admission-scope.ts\";\nimport { assertSessionOpen, sessionLifetime, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nexport { transferWorkflowStageDeliveriesTo };\n\nconst interruptMutationQueues = new WeakMap<AgentSession, Promise<void>>();\n\nfunction serializeInterruptMutation(owner: AgentSession, operation: () => Promise<void>): Promise<void> {\n\tconst previous = interruptMutationQueues.get(owner) ?? Promise.resolve();\n\tconst delivery = previous.then(operation);\n\tinterruptMutationQueues.set(\n\t\towner,\n\t\tdelivery.catch(() => undefined),\n\t);\n\treturn delivery;\n}\n\nconst laneImages = new WeakMap<AgentMessage, ImageContent[] | undefined>();\n\nfunction rememberLaneMessage(message: AgentMessage, images: ImageContent[] | undefined): void {\n\tlaneImages.set(message, images?.length ? [...images] : undefined);\n}\n\nfunction queuedTextImages(texts: readonly string[], removed: readonly AgentMessage[]): (ImageContent[] | undefined)[] {\n\tconst images = removed.flatMap((message) => (laneImages.has(message) ? [laneImages.get(message)] : []));\n\tconst firstQueuedIndex = images.length - texts.length;\n\treturn texts.map((_, index) => images[firstQueuedIndex + index]);\n}\n\n/**\n * Queue a steering message (already expanded, no extension command check). `typed` is the text that was submitted,\n * when an `input` hook or an expansion may have changed it; `clearQueue()` gives it back.\n */\nexport async function _queueSteer(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\ttyped?: string,\n): Promise<void> {\n\tassertSessionOpen(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._queueSteer(text, images, typed);\n\tthis._steeringMessages.push(text);\n\trememberTypedQueuedText(this, \"steer\", text, typed);\n\tthis._emitQueueUpdate();\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\tif (images) {\n\t\tcontent.push(...images);\n\t}\n\tconst message: AgentMessage = { role: \"user\", content, timestamp: Date.now() };\n\tif (images?.length) markQueuedMessageImages(message);\n\trememberLaneMessage(message, images);\n\tthis._queueAgentMessage(message, \"steer\");\n}\n\n/**\n * Internal: Queue a follow-up message (already expanded, no extension command check). `typed` is as for `_queueSteer`.\n */\nexport async function _queueFollowUp(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\ttyped?: string,\n): Promise<void> {\n\tassertSessionOpen(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._queueFollowUp(text, images, typed);\n\tthis._followUpMessages.push(text);\n\trememberTypedQueuedText(this, \"followUp\", text, typed);\n\tthis._emitQueueUpdate();\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\tif (images) {\n\t\tcontent.push(...images);\n\t}\n\tconst message: AgentMessage = { role: \"user\", content, timestamp: Date.now() };\n\tif (images?.length) markQueuedMessageImages(message);\n\trememberLaneMessage(message, images);\n\tthis._queueAgentMessage(message, \"followUp\");\n}\n\n/**\n * Throw an error if the text is an extension command.\n */\n\nexport function _throwIfExtensionCommand(this: AgentSession, text: string): void {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst command = this._extensionRunner.getCommand(commandName);\n\n\tif (command) {\n\t\tthrow new Error(\n\t\t\t`Extension command \"/${commandName}\" cannot be queued. Use prompt() or execute the command when not streaming.`,\n\t\t);\n\t}\n}\n\n/**\n * Send a custom message to the session. Creates a CustomMessageEntry.\n *\n * Handles five cases:\n * - Streaming + interrupt trigger: aborts the active run and starts an immediate custom-message turn\n * - Streaming + explicit display-only context exclusion: appends to state/session, no turn and no queue\n * - Streaming otherwise: queues message, processed when loop pulls from queue\n * - Not streaming + triggerTurn: appends to state/session, starts new turn\n * - Not streaming + no trigger: appends to state/session, no turn\n *\n * @param message Custom message with customType, content, display, details\n * @param options.triggerTurn If true and not streaming, triggers a new LLM turn\n * @param options.deliverAs Delivery mode: \"steer\", \"followUp\", \"nextTurn\", or \"interrupt\"\n */\n\nexport async function sendCustomMessage<T = unknown>(\n\tthis: AgentSession,\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst currentOwner = resolveWorkflowStageDeliveryTarget(this);\n\tif (currentOwner !== this) return currentOwner.sendCustomMessage(message, options);\n\tassertSessionOpen(this);\n\treturn deliveredMessageTurn(this, () => admittedCustomMessage.call(this, message, options));\n}\n\n/**\n * A delivered message starts this session's turn, so the turn runs under this session's own resource admission, or\n * none: never under the scope its sender runs in, such as the workflow run whose notice or stage message it is.\n */\nfunction deliveredMessageTurn<T>(session: AgentSession, deliver: () => Promise<T>): Promise<T> {\n\treturn withOwnResourceAdmission(session._resourceAdmission, () => trackSessionWork(session, deliver));\n}\n\nasync function admittedCustomMessage<T>(\n\tthis: AgentSession,\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst appMessage = {\n\t\trole: \"custom\" as const,\n\t\tcustomType: message.customType,\n\t\tcontent: message.content ?? [],\n\t\tdisplay: message.display,\n\t\tdetails: message.details,\n\t\ttimestamp: Date.now(),\n\t\t...(options?.excludeFromContext === true ? { excludeFromContext: true } : {}),\n\t\t...(options?.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: options.stageAdmissionKey }),\n\t} satisfies CustomMessage<T> & { stageAdmissionKey?: string };\n\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\tconst commit = async (): Promise<void> => {\n\t\tif (boundary && options?.stageAdmissionBarrier) await options.stageAdmissionBarrier();\n\t\tassertSessionOpen(this);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tawait commitAdmittedCustomMessage(this, appMessage, options);\n\t};\n\t// Event hooks may await non-triggering writes while protected input awaits the\n\t// event writer. Those local writes must not queue behind that external input.\n\tconst deliver = () =>\n\t\tboundary && options?.triggerTurn === true ? boundary.serializeMessageDelivery(commit) : commit();\n\tif (boundary === undefined) return deliver();\n\tawait boundary.admit(options?.stageAdmissionKey, deliver, () => {\n\t\tif (this._subagentMessageAdmission) throw new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\tconst router = this._orchestrationContext?.lateMessageRouter;\n\t\tif (router === undefined) throw new Error(\"Workflow stage closed without a late-message router\");\n\t\treturn router.routeMessage(message, options);\n\t}).completion;\n}\n\n/** Atomically admits a custom-message batch in array order. */\nexport async function sendCustomMessages<T = unknown>(\n\tthis: AgentSession,\n\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst currentOwner = resolveWorkflowStageDeliveryTarget(this);\n\tif (currentOwner !== this) return currentOwner.sendCustomMessages(messages, options);\n\tassertSessionOpen(this);\n\treturn deliveredMessageTurn(this, () => admittedCustomMessages.call(this, messages, options));\n}\n\nasync function admittedCustomMessages<T>(\n\tthis: AgentSession,\n\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst timestamp = Date.now();\n\tconst appMessages = messages.map(\n\t\t(message) =>\n\t\t\t({\n\t\t\t\trole: \"custom\" as const,\n\t\t\t\tcustomType: message.customType,\n\t\t\t\tcontent: message.content ?? [],\n\t\t\t\tdisplay: message.display,\n\t\t\t\tdetails: message.details,\n\t\t\t\ttimestamp,\n\t\t\t\t...(options?.excludeFromContext === true ? { excludeFromContext: true } : {}),\n\t\t\t\t...(options?.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: options.stageAdmissionKey }),\n\t\t\t}) satisfies CustomMessage<T> & { stageAdmissionKey?: string },\n\t);\n\tif (appMessages.length === 0) return;\n\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\tconst commit = async (): Promise<void> => {\n\t\tif (boundary && options?.stageAdmissionBarrier) await options.stageAdmissionBarrier();\n\t\tassertSessionOpen(this);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tawait commitAdmittedCustomMessages(this, appMessages, options);\n\t};\n\tconst deliver = () =>\n\t\tboundary && options?.triggerTurn === true ? boundary.serializeMessageDelivery(commit) : commit();\n\tif (boundary === undefined) return deliver();\n\tawait boundary.admit(options?.stageAdmissionKey, deliver, () => {\n\t\tif (this._subagentMessageAdmission) throw new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\tconst router = this._orchestrationContext?.lateMessageRouter;\n\t\tif (router === undefined) throw new Error(\"Workflow stage closed without a late-message router\");\n\t\treturn router.routeMessages(messages, options);\n\t}).completion;\n}\n\nexport function sealWorkflowStageGeneration(this: AgentSession): void {\n\tthis._workflowStageAdmission?.seal();\n}\n\nexport async function closeWorkflowStageGeneration(this: AgentSession): Promise<void> {\n\tawait this._workflowStageAdmission?.close();\n\tawait this.agent?.waitForIdle?.();\n\tawait this._agentEventQueue;\n}\n\nexport async function _appendCustomMessage<T>(this: AgentSession, message: CustomMessage<T>): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tawait owner._appendCustomMessage(message);\n\t\treturn;\n\t}\n\tconst stageAdmissionMessage = message as StageAdmittedCustomMessage;\n\tconst entryId = await this.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tstageAdmissionMessage.stageAdmissionKey,\n\t);\n\tthis._entryIdsByMessage.set(message, entryId);\n\tthis._refreshFinalizedContext();\n\tthis._emit({ type: \"message_start\", message });\n\tthis._emit({ type: \"message_end\", message });\n}\n\nconst pendingCustomMessageDrains = new WeakMap<AgentSession, Promise<void>>();\n\n/**\n * Append context-only custom messages once the current turn's tool results are in history. Within a run, a message\n * that cannot be saved stops the run like any other unsaved message (#4254): it is reported once and stays buffered\n * for the next prompt, and the stopped run saves nothing more.\n */\nexport function _flushPendingCustomMessages(this: AgentSession, withinRun = false): Promise<void> {\n\tconst pending = pendingCustomMessageDrains.get(this);\n\tif (pending) return pending;\n\tif (this._pendingCustomMessages.length === 0) return Promise.resolve();\n\tif (withinRun && this._persistenceFailure !== undefined) return Promise.resolve();\n\n\tconst drain = (async () => {\n\t\twhile (this._pendingCustomMessages.length > 0) {\n\t\t\tconst message = this._pendingCustomMessages[0];\n\t\t\ttry {\n\t\t\t\tawait this._appendCustomMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\t// A listener that throws after the message was saved is no save failure; it still fails the turn.\n\t\t\t\tif (!withinRun || this._entryIdsByMessage.has(message)) throw error;\n\t\t\t\trecordPersistenceFailure(this, message, error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._pendingCustomMessages.shift();\n\t\t}\n\t})();\n\tpendingCustomMessageDrains.set(this, drain);\n\tvoid drain.then(\n\t\t() => pendingCustomMessageDrains.delete(this),\n\t\t() => pendingCustomMessageDrains.delete(this),\n\t);\n\treturn drain;\n}\nexport function _enqueueInterruptCustomMessage<T>(\n\tthis: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._enqueueInterruptCustomMessage(message, forwardedMessageOptions(options));\n\tassertSessionOpen(this);\n\tthis._pendingInterruptDeliveries += 1;\n\t// Establish the hold synchronously when the interrupt is enqueued, not when\n\t// the serialized delivery callback later starts. Callers commonly fire and\n\t// forget sendCustomMessage(), then queue additional steer/follow-up messages\n\t// before the promise chain gets a microtask; those messages must be captured\n\t// in the active interrupt hold instead of pi-agent-core's live queues.\n\tthis._ensureActiveInterruptQueueHold();\n\tconst delivery = trackSessionWork(this, () =>\n\t\tthis._interruptDeliveryQueue.then(async () => {\n\t\t\ttry {\n\t\t\t\tawait this._sendInterruptCustomMessageNow(message, options);\n\t\t\t} finally {\n\t\t\t\t// Retirement moves the pending count and hold synchronously. Settle the\n\t\t\t\t// same live owner so its queue cannot remain stranded on the replacement.\n\t\t\t\tconst liveOwner = resolveWorkflowStageDeliveryTarget(this);\n\t\t\t\tliveOwner._pendingInterruptDeliveries -= 1;\n\t\t\t\tif (liveOwner._pendingInterruptDeliveries === 0) {\n\t\t\t\t\tliveOwner._restoreAndClearActiveInterruptQueueHold();\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t);\n\tthis._interruptDeliveryQueue = delivery.catch(() => undefined);\n\treturn delivery;\n}\n\nasync function sendInterruptCustomMessageUnlocked<T>(\n\tsession: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tassertSessionOpen(session);\n\tconst lifetime = sessionLifetime(session);\n\tsession.abortRetry();\n\tsession._ensureActiveInterruptQueueHold();\n\tawait waitForCustomMessagePreparation(session);\n\tif (session.isStreaming || session._isPreparingRun) {\n\t\tconst previousAbortMessage = session._activeInterruptAbortMessage;\n\t\tsession._activeInterruptAbortMessage = normalizeInterruptAbortMessage(options?.interruptAbortMessage);\n\t\ttry {\n\t\t\tsession.agent.abort();\n\t\t\tawait session.agent.waitForIdle();\n\t\t\tawait session._agentEventQueue;\n\t\t} finally {\n\t\t\tsession._activeInterruptAbortMessage = previousAbortMessage;\n\t\t}\n\t}\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return owner._sendInterruptCustomMessageNow(message, forwardedMessageOptions(options));\n\tassertSessionOpen(session);\n\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\tif (session._queuedMessagesPaused) {\n\t\tsession._queueAgentMessage(message, \"steer\");\n\t\treturn;\n\t}\n\tawait session.agent.prompt(message);\n}\n\nexport function _sendInterruptCustomMessageNow<T>(\n\tthis: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._sendInterruptCustomMessageNow(message, forwardedMessageOptions(options));\n\treturn serializeInterruptMutation(this, () => sendInterruptCustomMessageUnlocked(this, message, options));\n}\n\nexport function _ensureActiveInterruptQueueHold(this: AgentSession): InterruptQueueHold {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._ensureActiveInterruptQueueHold();\n\tif (this._activeInterruptQueueHold !== undefined) {\n\t\treturn this._activeInterruptQueueHold;\n\t}\n\tconst drained = this._drainQueuedAgentMessages();\n\tthis._activeInterruptQueueHold = {\n\t\tsteering: [...drained.steering],\n\t\tfollowUp: [...drained.followUp],\n\t};\n\treturn this._activeInterruptQueueHold;\n}\n\nexport function _restoreAndClearActiveInterruptQueueHold(this: AgentSession): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner._restoreAndClearActiveInterruptQueueHold();\n\t\treturn;\n\t}\n\tif (this._queuedMessagesPaused) return;\n\tconst hold = this._activeInterruptQueueHold;\n\tif (hold === undefined) return;\n\tconst currentCoreQueues = this._drainQueuedAgentMessages();\n\tthis._restoreQueuedAgentMessages({\n\t\tsteering: [...hold.steering, ...currentCoreQueues.steering],\n\t\tfollowUp: [...hold.followUp, ...currentCoreQueues.followUp],\n\t});\n\tthis._activeInterruptQueueHold = undefined;\n}\n\nexport function _queueAgentMessage(\n\tthis: AgentSession,\n\tmessage: AgentMessage,\n\tdelivery: \"steer\" | \"followUp\" | \"interrupt\",\n): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner._queueAgentMessage(message, delivery);\n\t\treturn;\n\t}\n\tconst hold = delivery === \"interrupt\" ? this._ensureActiveInterruptQueueHold() : this._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tif (delivery === \"followUp\") {\n\t\t\thold.followUp.push(message);\n\t\t} else if (delivery === \"interrupt\") {\n\t\t\tconst index = priorityHoldCounts.get(hold) ?? 0;\n\t\t\thold.steering.splice(index, 0, message);\n\t\t\tpriorityHoldCounts.set(hold, index + 1);\n\t\t} else {\n\t\t\thold.steering.push(message);\n\t\t}\n\t} else if (delivery === \"followUp\") {\n\t\tthis.agent.followUp(message);\n\t} else {\n\t\tthis.agent.steer(message);\n\t}\n\tconst yieldReason = message.role === \"user\" ? \"input-needed\" : \"intercom-coordination\";\n\tthis._agentTaskHost?.yieldTaskWaits(yieldReason);\n\tthis._childTaskWaits.yieldAll(yieldReason);\n}\n\nexport function _drainQueuedAgentMessages(this: AgentSession): DrainedAgentQueues {\n\t// pi-agent-core exposes public clear methods but no public drain/restore pair.\n\t// Interrupt and pause holds prevent an aborting run from consuming queued raw\n\t// messages while preserving every entry for the existing resume boundary.\n\tconst agentWithQueues = this.agent as unknown as AgentQueueAccess;\n\treturn {\n\t\tsteering: drainAgentMessageQueue(agentWithQueues.steeringQueue),\n\t\tfollowUp: drainAgentMessageQueue(agentWithQueues.followUpQueue),\n\t};\n}\n\nexport function _restoreQueuedAgentMessages(this: AgentSession, queues: DrainedAgentQueues): void {\n\tfor (const message of queues.steering) {\n\t\tthis.agent.steer(message);\n\t}\n\tfor (const message of queues.followUp) {\n\t\tthis.agent.followUp(message);\n\t}\n}\n/**\n * Clear queued text for editor restoration while retaining optional raw custom entries.\n */\nexport function clearQueue(this: AgentSession, options?: ClearQueueOptions): ClearedQueue {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.clearQueue(options);\n\t// Input held while the session compacts goes back to the caller too, and is never sent. It is held as typed.\n\tconst held = cancelHeldInput(this);\n\tconst steering = [...this._steeringMessages, ...held.steering];\n\tconst followUp = [...this._followUpMessages, ...held.followUp];\n\tconst typed = {\n\t\tsteering: [...this._steeringMessages.map((text) => forgetTypedQueuedText(this, \"steer\", text)), ...held.steering],\n\t\tfollowUp: [\n\t\t\t...this._followUpMessages.map((text) => forgetTypedQueuedText(this, \"followUp\", text)),\n\t\t\t...held.followUp,\n\t\t],\n\t};\n\tconst retyped =\n\t\ttyped.steering.some((text, index) => text !== steering[index]) ||\n\t\ttyped.followUp.some((text, index) => text !== followUp[index]);\n\tforgetAllTypedQueuedTexts(this);\n\tconst queuedSteering = this._steeringMessages;\n\tconst queuedFollowUp = this._followUpMessages;\n\tthis._steeringMessages = [];\n\tthis._followUpMessages = [];\n\tconst removed = this._drainQueuedAgentMessages();\n\tconst hold = this._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoved.steering.push(...hold.steering.splice(0));\n\t\tremoved.followUp.push(...hold.followUp.splice(0));\n\t\tpriorityHoldCounts.delete(hold);\n\t}\n\tconst images = {\n\t\tsteering: [...queuedTextImages(queuedSteering, removed.steering), ...held.images.steering],\n\t\tfollowUp: [...queuedTextImages(queuedFollowUp, removed.followUp), ...held.images.followUp],\n\t};\n\tconst withImages = [...images.steering, ...images.followUp].some((entry) => entry !== undefined);\n\trestoreProtectedStreamingCustomMessages(this, removed);\n\tif (options?.preserveUnprotectedCustomMessages && hold !== undefined) {\n\t\tconst restoreUnprotectedCustomMessages = (\n\t\t\tremovedMessages: AgentMessage[],\n\t\t\theldMessages: AgentMessage[],\n\t\t): void => {\n\t\t\tconst currentlyHeld = [...heldMessages];\n\t\t\tconst preserved = removedMessages.filter(\n\t\t\t\t(message): message is Extract<AgentMessage, { role: \"custom\" }> =>\n\t\t\t\t\tmessage.role === \"custom\" && !isProtectedStreamingCustomMessage(this, message),\n\t\t\t);\n\t\t\tif (preserved.length === 0) return;\n\t\t\tconst preservedReferences = new Set<AgentMessage>(preserved);\n\t\t\tconst restoredProtected = new Set(currentlyHeld);\n\t\t\tconst ordered = removedMessages.filter(\n\t\t\t\t(message) => preservedReferences.has(message) || restoredProtected.has(message),\n\t\t\t);\n\t\t\tconst unmatched = currentlyHeld.filter((message) => !ordered.includes(message));\n\t\t\theldMessages.splice(0, heldMessages.length, ...ordered, ...unmatched);\n\t\t};\n\t\trestoreUnprotectedCustomMessages(removed.steering, hold.steering);\n\t\trestoreUnprotectedCustomMessages(removed.followUp, hold.followUp);\n\t}\n\tif (\n\t\t!this._queuedMessagesPaused &&\n\t\tthis._pendingInterruptDeliveries === 0 &&\n\t\thold !== undefined &&\n\t\thold.steering.length === 0 &&\n\t\thold.followUp.length === 0\n\t) {\n\t\tthis._activeInterruptQueueHold = undefined;\n\t}\n\tthis._emitQueueUpdate();\n\treturn {\n\t\tsteering,\n\t\tfollowUp,\n\t\t...(retyped ? { typed } : {}),\n\t\t...(withImages ? { images } : {}),\n\t};\n}\n\n/** Number of pending messages (includes both steering and follow-up) */\nexport function getSteeringMessages(this: AgentSession): readonly string[] {\n\tconst held = heldInputView(this).steering;\n\treturn held.length === 0 ? this._steeringMessages : [...this._steeringMessages, ...held];\n}\n\n/** Get pending follow-up messages (read-only) */\nexport function getFollowUpMessages(this: AgentSession): readonly string[] {\n\tconst held = heldInputView(this).followUp;\n\treturn held.length === 0 ? this._followUpMessages : [...this._followUpMessages, ...held];\n}\n\n// =========================================================================\n// Model Management\n// =========================================================================\n\nexport function setSteeringMode(this: AgentSession, mode: \"all\" | \"one-at-a-time\"): void {\n\tthis.agent.steeringMode = mode;\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setSteeringMode(mode));\n}\n\n/**\n * Set follow-up message mode.\n * Saves to settings.\n */\n\nexport function setFollowUpMode(this: AgentSession, mode: \"all\" | \"one-at-a-time\"): void {\n\tthis.agent.followUpMode = mode;\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setFollowUpMode(mode));\n}\n\n// =========================================================================\n// Queue and delivery settings\n// =========================================================================\nexport const agentSessionMessageQueueMethods = {\n\t_queueSteer,\n\t_queueFollowUp,\n\t_throwIfExtensionCommand,\n\ttransferWorkflowStageDeliveriesTo,\n\tsealWorkflowStageGeneration,\n\tsendCustomMessage,\n\tsendCustomMessages,\n\tcloseWorkflowStageGeneration,\n\t_appendCustomMessage,\n\t_flushPendingCustomMessages,\n\t_enqueueInterruptCustomMessage,\n\t_sendInterruptCustomMessageNow,\n\t_ensureActiveInterruptQueueHold,\n\t_restoreAndClearActiveInterruptQueueHold,\n\tpauseQueuedMessages,\n\tresumeQueuedMessages,\n\t_queueAgentMessage,\n\t_drainQueuedAgentMessages,\n\t_restoreQueuedAgentMessages,\n\tclearQueue,\n\tgetSteeringMessages,\n\tgetFollowUpMessages,\n\tabort,\n\tsetSteeringMode,\n\tsetFollowUpMode,\n};\n"]}
1
+ {"version":3,"file":"agent-session-message-queue.js","sourceRoot":"","sources":["../../src/core/agent-session-message-queue.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,4BAA4B,EAAE,MAAM,0CAA0C,CAAC;AACrH,OAAO,EAAE,uBAAuB,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AACrH,OAAO,EAAE,4BAA4B,EAAE,MAAM,mCAAmC,CAAC;AACjF,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAE/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AACnF,OAAO,EACN,iCAAiC,EACjC,uCAAuC,GACvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,uBAAuB,EAAE,+BAA+B,EAAE,MAAM,2BAA2B,CAAC;AACrG,OAAO,EAAE,KAAK,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EACN,yBAAyB,EACzB,qBAAqB,EACrB,uBAAuB,GACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAIN,4BAA4B,EAE5B,sBAAsB,EAEtB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4E;AAC5E,8BAA8B;AAC9B,4EAA4E;AAC5E,MAAM,CAAC,MAAM,+BAA+B,GAAG;IAC9C,WAAW;IACX,cAAc;IACd,wBAAwB;IACxB,iCAAiC;IACjC,2BAA2B;IAC3B,iBAAiB;IACjB,kBAAkB;IAClB,4BAA4B;IAC5B,oBAAoB;IACpB,2BAA2B;IAC3B,8BAA8B;IAC9B,8BAA8B;IAC9B,+BAA+B;IAC/B,wCAAwC;IACxC,mBAAmB;IACnB,oBAAoB;IACpB,kBAAkB;IAClB,yBAAyB;IACzB,2BAA2B;IAC3B,UAAU;IACV,mBAAmB;IACnB,mBAAmB;IACnB,KAAK;IACL,eAAe;IACf,eAAe;CACf,CAAC","sourcesContent":["import type { ImageContent, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { commitAdmittedCustomMessage, commitAdmittedCustomMessages } from \"./agent-session-custom-message-commit.ts\";\nimport { forwardedMessageOptions, resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport { holdsTurnsForDetachedResults } from \"./agent-session-detached-tools.ts\";\nimport { cancelHeldInput, heldInputView } from \"./agent-session-held-input.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { recordPersistenceFailure } from \"./agent-session-persistence-failures.ts\";\nimport {\n\tisProtectedStreamingCustomMessage,\n\trestoreProtectedStreamingCustomMessages,\n} from \"./agent-session-persistent-custom-messages.ts\";\nimport { markQueuedMessageImages, waitForCustomMessagePreparation } from \"./agent-session-prompt.ts\";\nimport { abort, pauseQueuedMessages, resumeQueuedMessages } from \"./agent-session-queue-pause.ts\";\nimport { transferWorkflowStageDeliveriesTo } from \"./agent-session-transfer.ts\";\nimport {\n\tforgetAllTypedQueuedTexts,\n\tforgetTypedQueuedText,\n\trememberTypedQueuedText,\n} from \"./agent-session-typed-queue.ts\";\nimport {\n\ttype AgentQueueAccess,\n\ttype ClearedQueue,\n\ttype ClearQueueOptions,\n\tcustomMessageExcludesContext,\n\ttype DrainedAgentQueues,\n\tdrainAgentMessageQueue,\n\ttype InterruptQueueHold,\n\tnormalizeInterruptAbortMessage,\n\tpriorityHoldCounts,\n} from \"./agent-session-types.js\";\nimport type { SendMessageOptions, SendMessagesOptions } from \"./extensions/index.js\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\nimport { withOwnResourceAdmission } from \"./resource-admission-scope.ts\";\nimport { assertSessionOpen, sessionLifetime, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nexport { transferWorkflowStageDeliveriesTo };\n\nconst interruptMutationQueues = new WeakMap<AgentSession, Promise<void>>();\n\nfunction serializeInterruptMutation(owner: AgentSession, operation: () => Promise<void>): Promise<void> {\n\tconst previous = interruptMutationQueues.get(owner) ?? Promise.resolve();\n\tconst delivery = previous.then(operation);\n\tinterruptMutationQueues.set(\n\t\towner,\n\t\tdelivery.catch(() => undefined),\n\t);\n\treturn delivery;\n}\n\nconst laneImages = new WeakMap<AgentMessage, ImageContent[] | undefined>();\n\nfunction rememberLaneMessage(message: AgentMessage, images: ImageContent[] | undefined): void {\n\tlaneImages.set(message, images?.length ? [...images] : undefined);\n}\n\nfunction queuedTextImages(texts: readonly string[], removed: readonly AgentMessage[]): (ImageContent[] | undefined)[] {\n\tconst images = removed.flatMap((message) => (laneImages.has(message) ? [laneImages.get(message)] : []));\n\tconst firstQueuedIndex = images.length - texts.length;\n\treturn texts.map((_, index) => images[firstQueuedIndex + index]);\n}\n\n/**\n * Queue a steering message (already expanded, no extension command check). `typed` is the text that was submitted,\n * when an `input` hook or an expansion may have changed it; `clearQueue()` gives it back.\n */\nexport async function _queueSteer(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\ttyped?: string,\n): Promise<void> {\n\tassertSessionOpen(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._queueSteer(text, images, typed);\n\tthis._steeringMessages.push(text);\n\trememberTypedQueuedText(this, \"steer\", text, typed);\n\tthis._emitQueueUpdate();\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\tif (images) {\n\t\tcontent.push(...images);\n\t}\n\tconst message: AgentMessage = { role: \"user\", content, timestamp: Date.now() };\n\tif (images?.length) markQueuedMessageImages(message);\n\trememberLaneMessage(message, images);\n\tthis._queueAgentMessage(message, \"steer\");\n}\n\n/**\n * Internal: Queue a follow-up message (already expanded, no extension command check). `typed` is as for `_queueSteer`.\n */\nexport async function _queueFollowUp(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\ttyped?: string,\n): Promise<void> {\n\tassertSessionOpen(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._queueFollowUp(text, images, typed);\n\tthis._followUpMessages.push(text);\n\trememberTypedQueuedText(this, \"followUp\", text, typed);\n\tthis._emitQueueUpdate();\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text }];\n\tif (images) {\n\t\tcontent.push(...images);\n\t}\n\tconst message: AgentMessage = { role: \"user\", content, timestamp: Date.now() };\n\tif (images?.length) markQueuedMessageImages(message);\n\trememberLaneMessage(message, images);\n\tthis._queueAgentMessage(message, \"followUp\");\n}\n\n/**\n * Throw an error if the text is an extension command.\n */\n\nexport function _throwIfExtensionCommand(this: AgentSession, text: string): void {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst command = this._extensionRunner.getCommand(commandName);\n\n\tif (command) {\n\t\tthrow new Error(\n\t\t\t`Extension command \"/${commandName}\" cannot be queued. Use prompt() or execute the command when not streaming.`,\n\t\t);\n\t}\n}\n\n/**\n * Send a custom message to the session. Creates a CustomMessageEntry.\n *\n * Handles five cases:\n * - Streaming + interrupt trigger: aborts the active run and starts an immediate custom-message turn\n * - Streaming + explicit display-only context exclusion: appends to state/session, no turn and no queue\n * - Streaming otherwise: queues message, processed when loop pulls from queue\n * - Not streaming + triggerTurn: appends to state/session, starts new turn\n * - Not streaming + no trigger: appends to state/session, no turn\n *\n * @param message Custom message with customType, content, display, details\n * @param options.triggerTurn If true and not streaming, triggers a new LLM turn\n * @param options.deliverAs Delivery mode: \"steer\", \"followUp\", \"nextTurn\", or \"interrupt\"\n */\n\nexport async function sendCustomMessage<T = unknown>(\n\tthis: AgentSession,\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst currentOwner = resolveWorkflowStageDeliveryTarget(this);\n\tif (currentOwner !== this) return currentOwner.sendCustomMessage(message, options);\n\tassertSessionOpen(this);\n\treturn deliveredMessageTurn(this, () => admittedCustomMessage.call(this, message, options));\n}\n\n/**\n * A delivered message starts this session's turn, so the turn runs under this session's own resource admission, or\n * none: never under the scope its sender runs in, such as the workflow run whose notice or stage message it is.\n */\nfunction deliveredMessageTurn<T>(session: AgentSession, deliver: () => Promise<T>): Promise<T> {\n\treturn withOwnResourceAdmission(session._resourceAdmission, () => trackSessionWork(session, deliver));\n}\n\nasync function admittedCustomMessage<T>(\n\tthis: AgentSession,\n\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst appMessage = {\n\t\trole: \"custom\" as const,\n\t\tcustomType: message.customType,\n\t\tcontent: message.content ?? [],\n\t\tdisplay: message.display,\n\t\tdetails: message.details,\n\t\ttimestamp: Date.now(),\n\t\t...(options?.excludeFromContext === true ? { excludeFromContext: true } : {}),\n\t\t...(options?.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: options.stageAdmissionKey }),\n\t} satisfies CustomMessage<T> & { stageAdmissionKey?: string };\n\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\tconst commit = async (): Promise<void> => {\n\t\tif (boundary && options?.stageAdmissionBarrier) await options.stageAdmissionBarrier();\n\t\tassertSessionOpen(this);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tawait commitAdmittedCustomMessage(this, appMessage, options);\n\t};\n\t// Event hooks may await non-triggering writes while protected input awaits the\n\t// event writer. Those local writes must not queue behind that external input.\n\tconst deliver = () =>\n\t\tboundary && options?.triggerTurn === true ? boundary.serializeMessageDelivery(commit) : commit();\n\tif (boundary === undefined) return deliver();\n\tawait boundary.admit(options?.stageAdmissionKey, deliver, () => {\n\t\tif (this._subagentMessageAdmission) throw new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\tconst router = this._orchestrationContext?.lateMessageRouter;\n\t\tif (router === undefined) throw new Error(\"Workflow stage closed without a late-message router\");\n\t\treturn router.routeMessage(message, options);\n\t}).completion;\n}\n\n/** Atomically admits a custom-message batch in array order. */\nexport async function sendCustomMessages<T = unknown>(\n\tthis: AgentSession,\n\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst currentOwner = resolveWorkflowStageDeliveryTarget(this);\n\tif (currentOwner !== this) return currentOwner.sendCustomMessages(messages, options);\n\tassertSessionOpen(this);\n\treturn deliveredMessageTurn(this, () => admittedCustomMessages.call(this, messages, options));\n}\n\nasync function admittedCustomMessages<T>(\n\tthis: AgentSession,\n\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\toptions?: SendMessagesOptions,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst timestamp = Date.now();\n\tconst appMessages = messages.map(\n\t\t(message) =>\n\t\t\t({\n\t\t\t\trole: \"custom\" as const,\n\t\t\t\tcustomType: message.customType,\n\t\t\t\tcontent: message.content ?? [],\n\t\t\t\tdisplay: message.display,\n\t\t\t\tdetails: message.details,\n\t\t\t\ttimestamp,\n\t\t\t\t...(options?.excludeFromContext === true ? { excludeFromContext: true } : {}),\n\t\t\t\t...(options?.stageAdmissionKey === undefined ? {} : { stageAdmissionKey: options.stageAdmissionKey }),\n\t\t\t}) satisfies CustomMessage<T> & { stageAdmissionKey?: string },\n\t);\n\tif (appMessages.length === 0) return;\n\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\tconst commit = async (): Promise<void> => {\n\t\tif (boundary && options?.stageAdmissionBarrier) await options.stageAdmissionBarrier();\n\t\tassertSessionOpen(this);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tawait commitAdmittedCustomMessages(this, appMessages, options);\n\t};\n\tconst deliver = () =>\n\t\tboundary && options?.triggerTurn === true ? boundary.serializeMessageDelivery(commit) : commit();\n\tif (boundary === undefined) return deliver();\n\tawait boundary.admit(options?.stageAdmissionKey, deliver, () => {\n\t\tif (this._subagentMessageAdmission) throw new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\tconst router = this._orchestrationContext?.lateMessageRouter;\n\t\tif (router === undefined) throw new Error(\"Workflow stage closed without a late-message router\");\n\t\treturn router.routeMessages(messages, options);\n\t}).completion;\n}\n\nexport function sealWorkflowStageGeneration(this: AgentSession): void {\n\tthis._workflowStageAdmission?.seal();\n}\n\nexport async function closeWorkflowStageGeneration(this: AgentSession): Promise<void> {\n\tawait this._workflowStageAdmission?.close();\n\tawait this.agent?.waitForIdle?.();\n\tawait this._agentEventQueue;\n}\n\nexport async function _appendCustomMessage<T>(this: AgentSession, message: CustomMessage<T>): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tawait owner._appendCustomMessage(message);\n\t\treturn;\n\t}\n\tconst stageAdmissionMessage = message as StageAdmittedCustomMessage;\n\tconst entryId = await this.sessionManager.appendCustomMessageEntry(\n\t\tmessage.customType,\n\t\tmessage.content,\n\t\tmessage.display,\n\t\tmessage.details,\n\t\tcustomMessageExcludesContext(message),\n\t\tundefined,\n\t\tstageAdmissionMessage.stageAdmissionKey,\n\t);\n\tthis._entryIdsByMessage.set(message, entryId);\n\tthis._refreshFinalizedContext();\n\tthis._emit({ type: \"message_start\", message });\n\tthis._emit({ type: \"message_end\", message });\n}\n\nconst pendingCustomMessageDrains = new WeakMap<AgentSession, Promise<void>>();\n\n/**\n * Append context-only custom messages once the current turn's tool results are in history. Within a run, a message\n * that cannot be saved stops the run like any other unsaved message (#4254): it is reported once and stays buffered\n * for the next prompt, and the stopped run saves nothing more.\n */\nexport function _flushPendingCustomMessages(this: AgentSession, withinRun = false): Promise<void> {\n\tconst pending = pendingCustomMessageDrains.get(this);\n\tif (pending) return pending;\n\tif (this._pendingCustomMessages.length === 0) return Promise.resolve();\n\tif (withinRun && this._persistenceFailure !== undefined) return Promise.resolve();\n\n\tconst drain = (async () => {\n\t\twhile (this._pendingCustomMessages.length > 0) {\n\t\t\tconst message = this._pendingCustomMessages[0];\n\t\t\ttry {\n\t\t\t\tawait this._appendCustomMessage(message);\n\t\t\t} catch (error) {\n\t\t\t\t// A listener that throws after the message was saved is no save failure; it still fails the turn.\n\t\t\t\tif (!withinRun || this._entryIdsByMessage.has(message)) throw error;\n\t\t\t\trecordPersistenceFailure(this, message, error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._pendingCustomMessages.shift();\n\t\t}\n\t})();\n\tpendingCustomMessageDrains.set(this, drain);\n\tvoid drain.then(\n\t\t() => pendingCustomMessageDrains.delete(this),\n\t\t() => pendingCustomMessageDrains.delete(this),\n\t);\n\treturn drain;\n}\nexport function _enqueueInterruptCustomMessage<T>(\n\tthis: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._enqueueInterruptCustomMessage(message, forwardedMessageOptions(options));\n\tassertSessionOpen(this);\n\tthis._pendingInterruptDeliveries += 1;\n\t// Establish the hold synchronously when the interrupt is enqueued, not when\n\t// the serialized delivery callback later starts. Callers commonly fire and\n\t// forget sendCustomMessage(), then queue additional steer/follow-up messages\n\t// before the promise chain gets a microtask; those messages must be captured\n\t// in the active interrupt hold instead of pi-agent-core's live queues.\n\tthis._ensureActiveInterruptQueueHold();\n\tconst delivery = trackSessionWork(this, () =>\n\t\tthis._interruptDeliveryQueue.then(async () => {\n\t\t\ttry {\n\t\t\t\tawait this._sendInterruptCustomMessageNow(message, options);\n\t\t\t} finally {\n\t\t\t\t// Retirement moves the pending count and hold synchronously. Settle the\n\t\t\t\t// same live owner so its queue cannot remain stranded on the replacement.\n\t\t\t\tconst liveOwner = resolveWorkflowStageDeliveryTarget(this);\n\t\t\t\tliveOwner._pendingInterruptDeliveries -= 1;\n\t\t\t\tif (liveOwner._pendingInterruptDeliveries === 0) {\n\t\t\t\t\tliveOwner._restoreAndClearActiveInterruptQueueHold();\n\t\t\t\t}\n\t\t\t}\n\t\t}),\n\t);\n\tthis._interruptDeliveryQueue = delivery.catch(() => undefined);\n\treturn delivery;\n}\n\nasync function sendInterruptCustomMessageUnlocked<T>(\n\tsession: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tassertSessionOpen(session);\n\tconst lifetime = sessionLifetime(session);\n\tsession.abortRetry();\n\tsession._ensureActiveInterruptQueueHold();\n\tawait waitForCustomMessagePreparation(session);\n\tif (session.isStreaming || session._isPreparingRun) {\n\t\tconst previousAbortMessage = session._activeInterruptAbortMessage;\n\t\tsession._activeInterruptAbortMessage = normalizeInterruptAbortMessage(options?.interruptAbortMessage);\n\t\ttry {\n\t\t\tsession.agent.abort();\n\t\t\tawait session.agent.waitForIdle();\n\t\t\tawait session._agentEventQueue;\n\t\t} finally {\n\t\t\tsession._activeInterruptAbortMessage = previousAbortMessage;\n\t\t}\n\t}\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return owner._sendInterruptCustomMessageNow(message, forwardedMessageOptions(options));\n\tassertSessionOpen(session);\n\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\tif (session._queuedMessagesPaused || holdsTurnsForDetachedResults(session)) {\n\t\tsession._queueAgentMessage(message, \"steer\");\n\t\treturn;\n\t}\n\tawait session.agent.prompt(message);\n}\n\nexport function _sendInterruptCustomMessageNow<T>(\n\tthis: AgentSession,\n\tmessage: CustomMessage<T>,\n\toptions?: SendMessageOptions,\n): Promise<void> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._sendInterruptCustomMessageNow(message, forwardedMessageOptions(options));\n\treturn serializeInterruptMutation(this, () => sendInterruptCustomMessageUnlocked(this, message, options));\n}\n\nexport function _ensureActiveInterruptQueueHold(this: AgentSession): InterruptQueueHold {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner._ensureActiveInterruptQueueHold();\n\tif (this._activeInterruptQueueHold !== undefined) {\n\t\treturn this._activeInterruptQueueHold;\n\t}\n\tconst drained = this._drainQueuedAgentMessages();\n\tthis._activeInterruptQueueHold = {\n\t\tsteering: [...drained.steering],\n\t\tfollowUp: [...drained.followUp],\n\t};\n\treturn this._activeInterruptQueueHold;\n}\n\nexport function _restoreAndClearActiveInterruptQueueHold(this: AgentSession): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner._restoreAndClearActiveInterruptQueueHold();\n\t\treturn;\n\t}\n\tif (this._queuedMessagesPaused) return;\n\tconst hold = this._activeInterruptQueueHold;\n\tif (hold === undefined) return;\n\tconst currentCoreQueues = this._drainQueuedAgentMessages();\n\tthis._restoreQueuedAgentMessages({\n\t\tsteering: [...hold.steering, ...currentCoreQueues.steering],\n\t\tfollowUp: [...hold.followUp, ...currentCoreQueues.followUp],\n\t});\n\tthis._activeInterruptQueueHold = undefined;\n}\n\nexport function _queueAgentMessage(\n\tthis: AgentSession,\n\tmessage: AgentMessage,\n\tdelivery: \"steer\" | \"followUp\" | \"interrupt\",\n): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner._queueAgentMessage(message, delivery);\n\t\treturn;\n\t}\n\tconst hold = delivery === \"interrupt\" ? this._ensureActiveInterruptQueueHold() : this._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tif (delivery === \"followUp\") {\n\t\t\thold.followUp.push(message);\n\t\t} else if (delivery === \"interrupt\") {\n\t\t\tconst index = priorityHoldCounts.get(hold) ?? 0;\n\t\t\thold.steering.splice(index, 0, message);\n\t\t\tpriorityHoldCounts.set(hold, index + 1);\n\t\t} else {\n\t\t\thold.steering.push(message);\n\t\t}\n\t} else if (delivery === \"followUp\") {\n\t\tthis.agent.followUp(message);\n\t} else {\n\t\tthis.agent.steer(message);\n\t}\n\tconst yieldReason = message.role === \"user\" ? \"input-needed\" : \"intercom-coordination\";\n\tthis._agentTaskHost?.yieldTaskWaits(yieldReason);\n\tthis._childTaskWaits.yieldAll(yieldReason);\n}\n\nexport function _drainQueuedAgentMessages(this: AgentSession): DrainedAgentQueues {\n\t// pi-agent-core exposes public clear methods but no public drain/restore pair.\n\t// Interrupt and pause holds prevent an aborting run from consuming queued raw\n\t// messages while preserving every entry for the existing resume boundary.\n\tconst agentWithQueues = this.agent as unknown as AgentQueueAccess;\n\treturn {\n\t\tsteering: drainAgentMessageQueue(agentWithQueues.steeringQueue),\n\t\tfollowUp: drainAgentMessageQueue(agentWithQueues.followUpQueue),\n\t};\n}\n\nexport function _restoreQueuedAgentMessages(this: AgentSession, queues: DrainedAgentQueues): void {\n\tfor (const message of queues.steering) {\n\t\tthis.agent.steer(message);\n\t}\n\tfor (const message of queues.followUp) {\n\t\tthis.agent.followUp(message);\n\t}\n}\n/**\n * Clear queued text for editor restoration while retaining optional raw custom entries.\n */\nexport function clearQueue(this: AgentSession, options?: ClearQueueOptions): ClearedQueue {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.clearQueue(options);\n\t// Input held while the session compacts goes back to the caller too, and is never sent. It is held as typed.\n\tconst held = cancelHeldInput(this);\n\tconst steering = [...this._steeringMessages, ...held.steering];\n\tconst followUp = [...this._followUpMessages, ...held.followUp];\n\tconst typed = {\n\t\tsteering: [...this._steeringMessages.map((text) => forgetTypedQueuedText(this, \"steer\", text)), ...held.steering],\n\t\tfollowUp: [\n\t\t\t...this._followUpMessages.map((text) => forgetTypedQueuedText(this, \"followUp\", text)),\n\t\t\t...held.followUp,\n\t\t],\n\t};\n\tconst retyped =\n\t\ttyped.steering.some((text, index) => text !== steering[index]) ||\n\t\ttyped.followUp.some((text, index) => text !== followUp[index]);\n\tforgetAllTypedQueuedTexts(this);\n\tconst queuedSteering = this._steeringMessages;\n\tconst queuedFollowUp = this._followUpMessages;\n\tthis._steeringMessages = [];\n\tthis._followUpMessages = [];\n\tconst removed = this._drainQueuedAgentMessages();\n\tconst hold = this._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoved.steering.push(...hold.steering.splice(0));\n\t\tremoved.followUp.push(...hold.followUp.splice(0));\n\t\tpriorityHoldCounts.delete(hold);\n\t}\n\tconst images = {\n\t\tsteering: [...queuedTextImages(queuedSteering, removed.steering), ...held.images.steering],\n\t\tfollowUp: [...queuedTextImages(queuedFollowUp, removed.followUp), ...held.images.followUp],\n\t};\n\tconst withImages = [...images.steering, ...images.followUp].some((entry) => entry !== undefined);\n\trestoreProtectedStreamingCustomMessages(this, removed);\n\tif (options?.preserveUnprotectedCustomMessages && hold !== undefined) {\n\t\tconst restoreUnprotectedCustomMessages = (\n\t\t\tremovedMessages: AgentMessage[],\n\t\t\theldMessages: AgentMessage[],\n\t\t): void => {\n\t\t\tconst currentlyHeld = [...heldMessages];\n\t\t\tconst preserved = removedMessages.filter(\n\t\t\t\t(message): message is Extract<AgentMessage, { role: \"custom\" }> =>\n\t\t\t\t\tmessage.role === \"custom\" && !isProtectedStreamingCustomMessage(this, message),\n\t\t\t);\n\t\t\tif (preserved.length === 0) return;\n\t\t\tconst preservedReferences = new Set<AgentMessage>(preserved);\n\t\t\tconst restoredProtected = new Set(currentlyHeld);\n\t\t\tconst ordered = removedMessages.filter(\n\t\t\t\t(message) => preservedReferences.has(message) || restoredProtected.has(message),\n\t\t\t);\n\t\t\tconst unmatched = currentlyHeld.filter((message) => !ordered.includes(message));\n\t\t\theldMessages.splice(0, heldMessages.length, ...ordered, ...unmatched);\n\t\t};\n\t\trestoreUnprotectedCustomMessages(removed.steering, hold.steering);\n\t\trestoreUnprotectedCustomMessages(removed.followUp, hold.followUp);\n\t}\n\tif (\n\t\t!this._queuedMessagesPaused &&\n\t\tthis._pendingInterruptDeliveries === 0 &&\n\t\thold !== undefined &&\n\t\thold.steering.length === 0 &&\n\t\thold.followUp.length === 0\n\t) {\n\t\tthis._activeInterruptQueueHold = undefined;\n\t}\n\tthis._emitQueueUpdate();\n\treturn {\n\t\tsteering,\n\t\tfollowUp,\n\t\t...(retyped ? { typed } : {}),\n\t\t...(withImages ? { images } : {}),\n\t};\n}\n\n/** Number of pending messages (includes both steering and follow-up) */\nexport function getSteeringMessages(this: AgentSession): readonly string[] {\n\tconst held = heldInputView(this).steering;\n\treturn held.length === 0 ? this._steeringMessages : [...this._steeringMessages, ...held];\n}\n\n/** Get pending follow-up messages (read-only) */\nexport function getFollowUpMessages(this: AgentSession): readonly string[] {\n\tconst held = heldInputView(this).followUp;\n\treturn held.length === 0 ? this._followUpMessages : [...this._followUpMessages, ...held];\n}\n\n// =========================================================================\n// Model Management\n// =========================================================================\n\nexport function setSteeringMode(this: AgentSession, mode: \"all\" | \"one-at-a-time\"): void {\n\tthis.agent.steeringMode = mode;\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setSteeringMode(mode));\n}\n\n/**\n * Set follow-up message mode.\n * Saves to settings.\n */\n\nexport function setFollowUpMode(this: AgentSession, mode: \"all\" | \"one-at-a-time\"): void {\n\tthis.agent.followUpMode = mode;\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setFollowUpMode(mode));\n}\n\n// =========================================================================\n// Queue and delivery settings\n// =========================================================================\nexport const agentSessionMessageQueueMethods = {\n\t_queueSteer,\n\t_queueFollowUp,\n\t_throwIfExtensionCommand,\n\ttransferWorkflowStageDeliveriesTo,\n\tsealWorkflowStageGeneration,\n\tsendCustomMessage,\n\tsendCustomMessages,\n\tcloseWorkflowStageGeneration,\n\t_appendCustomMessage,\n\t_flushPendingCustomMessages,\n\t_enqueueInterruptCustomMessage,\n\t_sendInterruptCustomMessageNow,\n\t_ensureActiveInterruptQueueHold,\n\t_restoreAndClearActiveInterruptQueueHold,\n\tpauseQueuedMessages,\n\tresumeQueuedMessages,\n\t_queueAgentMessage,\n\t_drainQueuedAgentMessages,\n\t_restoreQueuedAgentMessages,\n\tclearQueue,\n\tgetSteeringMessages,\n\tgetFollowUpMessages,\n\tabort,\n\tsetSteeringMode,\n\tsetFollowUpMode,\n};\n"]}