@bastani/atomic 0.9.19-alpha.2 → 0.9.19-alpha.4

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 (197) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +15 -0
  3. package/dist/builtin/intercom/broker/broker.ts +8 -0
  4. package/dist/builtin/intercom/broker/client.ts +18 -0
  5. package/dist/builtin/intercom/broker/send-handler.ts +9 -0
  6. package/dist/builtin/intercom/index.bundle.mjs +161 -30
  7. package/dist/builtin/intercom/package.json +1 -1
  8. package/dist/builtin/intercom/types.ts +2 -1
  9. package/dist/builtin/mcp/package.json +1 -1
  10. package/dist/builtin/subagents/CHANGELOG.md +18 -0
  11. package/dist/builtin/subagents/README.md +14 -14
  12. package/dist/builtin/subagents/package.json +1 -1
  13. package/dist/builtin/subagents/skills/subagent/SKILL.md +14 -14
  14. package/dist/builtin/subagents/src/extension/index.bundle.mjs +142 -60
  15. package/dist/builtin/web-access/package.json +1 -1
  16. package/dist/builtin/workflows/CHANGELOG.md +33 -0
  17. package/dist/builtin/workflows/README.md +14 -15
  18. package/dist/builtin/workflows/builtin/{chunk-mygmtz6e.js → chunk-9k3ywfgd.js} +1 -1
  19. package/dist/builtin/workflows/builtin/{chunk-r9qq7xfj.js → chunk-ahbntmx2.js} +1 -1
  20. package/dist/builtin/workflows/builtin/{chunk-zggjyg5z.js → chunk-n8zysf1t.js} +1 -1
  21. package/dist/builtin/workflows/builtin/goal.js +2 -2
  22. package/dist/builtin/workflows/builtin/index.js +3 -3
  23. package/dist/builtin/workflows/builtin/ralph.js +2 -2
  24. package/dist/builtin/workflows/package.json +5 -5
  25. package/dist/builtin/workflows/src/extension/index.bundle.mjs +171 -207
  26. package/dist/builtin/workflows/src/index.js +33 -6
  27. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +2 -1
  28. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +1 -1
  29. package/dist/core/agent-session-auto-compaction.js +1 -1
  30. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  31. package/dist/core/agent-session-compaction.js +1 -1
  32. package/dist/core/agent-session-compaction.js.map +1 -1
  33. package/dist/core/agent-session-custom-message-commit.d.ts.map +1 -1
  34. package/dist/core/agent-session-custom-message-commit.js +33 -2
  35. package/dist/core/agent-session-custom-message-commit.js.map +1 -1
  36. package/dist/core/agent-session-message-queue.d.ts +1 -1
  37. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  38. package/dist/core/agent-session-message-queue.js +22 -8
  39. package/dist/core/agent-session-message-queue.js.map +1 -1
  40. package/dist/core/agent-session-methods.d.ts +7 -1
  41. package/dist/core/agent-session-methods.d.ts.map +1 -1
  42. package/dist/core/agent-session-methods.js.map +1 -1
  43. package/dist/core/agent-session-persistent-custom-messages.d.ts +1 -1
  44. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  45. package/dist/core/agent-session-persistent-custom-messages.js +13 -3
  46. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  47. package/dist/core/agent-session-post-tool-compaction.js +1 -1
  48. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  49. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  50. package/dist/core/agent-session-prompt.js +83 -0
  51. package/dist/core/agent-session-prompt.js.map +1 -1
  52. package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
  53. package/dist/core/agent-session-queue-pause.js +11 -0
  54. package/dist/core/agent-session-queue-pause.js.map +1 -1
  55. package/dist/core/agent-session-tasks.d.ts +5 -0
  56. package/dist/core/agent-session-tasks.d.ts.map +1 -1
  57. package/dist/core/agent-session-tasks.js +8 -1
  58. package/dist/core/agent-session-tasks.js.map +1 -1
  59. package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
  60. package/dist/core/agent-session-tool-hooks.js +2 -0
  61. package/dist/core/agent-session-tool-hooks.js.map +1 -1
  62. package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
  63. package/dist/core/agent-session-tool-registry.js +12 -0
  64. package/dist/core/agent-session-tool-registry.js.map +1 -1
  65. package/dist/core/agent-session-transfer.d.ts.map +1 -1
  66. package/dist/core/agent-session-transfer.js +7 -0
  67. package/dist/core/agent-session-transfer.js.map +1 -1
  68. package/dist/core/agent-session-types.d.ts +2 -0
  69. package/dist/core/agent-session-types.d.ts.map +1 -1
  70. package/dist/core/agent-session-types.js +2 -0
  71. package/dist/core/agent-session-types.js.map +1 -1
  72. package/dist/core/agent-session.d.ts +4 -0
  73. package/dist/core/agent-session.d.ts.map +1 -1
  74. package/dist/core/agent-session.js +22 -0
  75. package/dist/core/agent-session.js.map +1 -1
  76. package/dist/core/extensions/context-types.d.ts +6 -0
  77. package/dist/core/extensions/context-types.d.ts.map +1 -1
  78. package/dist/core/extensions/context-types.js.map +1 -1
  79. package/dist/core/extensions/loader-api.d.ts.map +1 -1
  80. package/dist/core/extensions/loader-api.js +3 -0
  81. package/dist/core/extensions/loader-api.js.map +1 -1
  82. package/dist/core/extensions/loader-host-modules.d.ts +1 -1
  83. package/dist/core/extensions/loader-host-modules.d.ts.map +1 -1
  84. package/dist/core/extensions/loader-host-modules.js +2 -1
  85. package/dist/core/extensions/loader-host-modules.js.map +1 -1
  86. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  87. package/dist/core/extensions/loader-virtual-modules.js +4 -1
  88. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  89. package/dist/core/extensions/runner-context.d.ts +1 -1
  90. package/dist/core/extensions/runner-context.d.ts.map +1 -1
  91. package/dist/core/extensions/runner-context.js +9 -3
  92. package/dist/core/extensions/runner-context.js.map +1 -1
  93. package/dist/core/extensions/runner.js +1 -1
  94. package/dist/core/extensions/runner.js.map +1 -1
  95. package/dist/core/extensions/workflow-events.d.ts +1 -1
  96. package/dist/core/extensions/workflow-events.d.ts.map +1 -1
  97. package/dist/core/extensions/workflow-events.js.map +1 -1
  98. package/dist/core/retry-policy.d.ts +1 -0
  99. package/dist/core/retry-policy.d.ts.map +1 -1
  100. package/dist/core/retry-policy.js +2 -1
  101. package/dist/core/retry-policy.js.map +1 -1
  102. package/dist/core/sdk-exports.d.ts +1 -1
  103. package/dist/core/sdk-exports.d.ts.map +1 -1
  104. package/dist/core/sdk-exports.js +1 -1
  105. package/dist/core/sdk-exports.js.map +1 -1
  106. package/dist/core/settings-manager-basic-accessors.d.ts +6 -3
  107. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  108. package/dist/core/settings-manager-basic-accessors.js +25 -8
  109. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  110. package/dist/core/settings-manager.d.ts +1 -1
  111. package/dist/core/settings-manager.d.ts.map +1 -1
  112. package/dist/core/settings-manager.js.map +1 -1
  113. package/dist/core/settings-types.d.ts +6 -0
  114. package/dist/core/settings-types.d.ts.map +1 -1
  115. package/dist/core/settings-types.js.map +1 -1
  116. package/dist/core/slash-commands.d.ts.map +1 -1
  117. package/dist/core/slash-commands.js +4 -5
  118. package/dist/core/slash-commands.js.map +1 -1
  119. package/dist/core/tasks/agent-adapter.d.ts +14 -2
  120. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  121. package/dist/core/tasks/agent-adapter.js +45 -4
  122. package/dist/core/tasks/agent-adapter.js.map +1 -1
  123. package/dist/core/tasks/completion.d.ts.map +1 -1
  124. package/dist/core/tasks/completion.js +5 -1
  125. package/dist/core/tasks/completion.js.map +1 -1
  126. package/dist/core/tasks/pause.d.ts +4 -0
  127. package/dist/core/tasks/pause.d.ts.map +1 -0
  128. package/dist/core/tasks/pause.js +49 -0
  129. package/dist/core/tasks/pause.js.map +1 -0
  130. package/dist/core/tasks/supervisor.d.ts +3 -1
  131. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  132. package/dist/core/tasks/supervisor.js +48 -22
  133. package/dist/core/tasks/supervisor.js.map +1 -1
  134. package/dist/core/tools/bash-pty-native.d.ts +16 -2
  135. package/dist/core/tools/bash-pty-native.d.ts.map +1 -1
  136. package/dist/core/tools/bash-pty-native.js +82 -0
  137. package/dist/core/tools/bash-pty-native.js.map +1 -1
  138. package/dist/core/tools/bash.d.ts +15 -2
  139. package/dist/core/tools/bash.d.ts.map +1 -1
  140. package/dist/core/tools/bash.js +49 -4
  141. package/dist/core/tools/bash.js.map +1 -1
  142. package/dist/core/tools/index.d.ts +4 -1
  143. package/dist/core/tools/index.d.ts.map +1 -1
  144. package/dist/core/tools/index.js +12 -0
  145. package/dist/core/tools/index.js.map +1 -1
  146. package/dist/core/tools/kill.d.ts +17 -0
  147. package/dist/core/tools/kill.d.ts.map +1 -0
  148. package/dist/core/tools/kill.js +49 -0
  149. package/dist/core/tools/kill.js.map +1 -0
  150. package/dist/core/tools/powershell.d.ts +84 -28
  151. package/dist/core/tools/powershell.d.ts.map +1 -1
  152. package/dist/core/tools/powershell.js +11 -3
  153. package/dist/core/tools/powershell.js.map +1 -1
  154. package/dist/core/tools/resource-selectors.d.ts +1 -1
  155. package/dist/core/tools/resource-selectors.d.ts.map +1 -1
  156. package/dist/core/tools/resource-selectors.js +7 -4
  157. package/dist/core/tools/resource-selectors.js.map +1 -1
  158. package/dist/core/workflow-stage-admission.d.ts +14 -0
  159. package/dist/core/workflow-stage-admission.d.ts.map +1 -1
  160. package/dist/core/workflow-stage-admission.js +63 -3
  161. package/dist/core/workflow-stage-admission.js.map +1 -1
  162. package/dist/index.d.ts +2 -2
  163. package/dist/index.d.ts.map +1 -1
  164. package/dist/index.js +1 -1
  165. package/dist/index.js.map +1 -1
  166. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  167. package/dist/modes/interactive/components/chat-session-host.js +3 -2
  168. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  169. package/dist/modes/interactive/components/task-row.d.ts.map +1 -1
  170. package/dist/modes/interactive/components/task-row.js +8 -1
  171. package/dist/modes/interactive/components/task-row.js.map +1 -1
  172. package/docs/background-tasks.md +31 -2
  173. package/docs/compaction.md +20 -0
  174. package/docs/computer-use.md +390 -0
  175. package/docs/development.md +23 -74
  176. package/docs/docs.json +1 -0
  177. package/docs/extensions.md +15 -1
  178. package/docs/herdr.md +26 -77
  179. package/docs/index.md +1 -0
  180. package/docs/intercom.md +14 -2
  181. package/docs/models/evals.md +2 -0
  182. package/docs/models/model-selection.md +10 -7
  183. package/docs/quickstart.md +1 -1
  184. package/docs/sdk.md +11 -1
  185. package/docs/settings.md +24 -0
  186. package/docs/subagents.md +10 -6
  187. package/docs/tmux.md +2 -0
  188. package/docs/tools.md +11 -1
  189. package/docs/usage.md +1 -1
  190. package/docs/workflows/api-reference.md +5 -4
  191. package/docs/workflows/authoring.md +3 -3
  192. package/docs/workflows/operations.md +44 -33
  193. package/docs/workflows/reliable-design.md +3 -3
  194. package/docs/workflows/verification.md +99 -40
  195. package/docs/workflows.md +4 -2
  196. package/npm-shrinkwrap.json +59 -59
  197. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tModelMutationOptions,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ExtensionProviderTransaction, ModelRuntime } from \"./model-runtime.js\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.js\";\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Reports when a session_before_compact override becomes the active compaction source. */\n\tonCompactionSource?: (fromExtension: boolean) => void;\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Outcome of an automatic compaction admission and persistence attempt. */\nexport type AutoCompactionRunOutcome = \"compacted\" | \"not_compactable\" | \"deferred\" | \"failed\";\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n\tpreserveRunner?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.js\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.ts\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\tdispose(): void;\n\tgetAgentTaskHost(): import(\"./tasks/agent-adapter.js\").AgentTaskHost;\n\tcloseSessionTasks(): Promise<void>;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[], promptStarted?: () => void): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[], options?: Pick<PromptOptions, \"source\">): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[], options?: Pick<PromptOptions, \"source\">): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_flushPendingCustomMessages(): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>, options?: ModelMutationOptions): Promise<void>;\n\tcycleModel(\n\t\tdirection?: \"forward\" | \"backward\",\n\t\toptions?: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel, options?: ModelMutationOptions): void;\n\tcycleThinkingLevel(options?: ModelMutationOptions): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(targetModel?: Model<Api>, explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: Partial<VerbatimCompactionParameters>): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\tabortSessionSummary(): void;\n\t_maybeGenerateSessionSummary(): Promise<void>;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(\n\t\treason: \"overflow\" | \"threshold\",\n\t\twillRetry: boolean,\n\t\turgency?: CompactionUrgency,\n\t): Promise<AutoCompactionRunOutcome>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(\n\t\trunner: ExtensionRunner,\n\t\tpublication?: {\n\t\t\tresourceLoader: ResourceLoader;\n\t\t\tproviderTransaction: ExtensionProviderTransaction;\n\t\t\tproviderIds: Set<string>;\n\t\t\tdefer(effect: () => void | Promise<void>): void;\n\t\t},\n\t): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\tcompleteStartupResources(resourceLoader: ResourceLoader): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isFallbackableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\t_beginFallbackModelScope(): void;\n\t_clearFallbackModelScope(): void;\n\t_settleFallbackModelScope(): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string, options?: { themeName?: string }): Promise<string>;\n\texportToJsonl(outputPath?: string, options?: { includeShareContext?: boolean }): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"getAgentTaskHost\"\n\t\t| \"closeSessionTasks\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"abortSessionSummary\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"completeStartupResources\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_fallbackAttemptedKeys: Set<string>;\n\t_fallbackBlockedModels: Array<Model<Api>>;\n\t_fallbackOriginModel: Model<Api> | undefined;\n\t_fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\t_fallbackScopeGeneration: number;\n\t_fallbackOriginGeneration: number | undefined;\n\t_fallbackRestoreError: string | undefined;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_stopAfterTurnBlockedContinuation: boolean;\n\t_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_admittedQueuedMessageAwaitingReply: string | undefined;\n\t_admittedRecoveryTurn: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_pendingCustomMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_autoCompactionCompletion: Promise<void> | undefined;\n\t_compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_recoverableLengthRecoveryAttempted: boolean;\n\t_contextOverflowUnresolved: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_branchSummaryCompletion: Promise<void> | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, AbortController>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_subagentPolicy?: import(\"./extensions/index.js\").SubagentChildPolicy;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_disposed: boolean;\n\t_sessionSummaryAbortController: AbortController | undefined;\n\t_sessionSummaryToken: number;\n\t_sessionSummaryRun: import(\"./agent-session-summary.ts\").SessionSummaryRun | undefined;\n\t_lastSummarizedMessageId: string | undefined;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_extensionProviderIds: Set<string>;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_systemPromptTransform?: (prompt: string) => string;\n\t_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_tempStorageLease: import(\"./tools/session-temp-dir.ts\").ProtectedPathLease | undefined;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n\t_agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\t_taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\t_taskAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
1
+ {"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tModelMutationOptions,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ExtensionProviderTransaction, ModelRuntime } from \"./model-runtime.js\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.js\";\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Reports when a session_before_compact override becomes the active compaction source. */\n\tonCompactionSource?: (fromExtension: boolean) => void;\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Outcome of an automatic compaction admission and persistence attempt. */\nexport type AutoCompactionRunOutcome = \"compacted\" | \"not_compactable\" | \"deferred\" | \"failed\";\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n\tpreserveRunner?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.js\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.ts\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\tdispose(): void;\n\tgetAgentTaskHost(): import(\"./tasks/agent-adapter.js\").AgentTaskHost;\n\tcloseSessionTasks(): Promise<void>;\n\t/** Internal workflow pause: cancel owned execution without closing message admission. */\n\tpauseTasks(): Promise<void>;\n\tresumeTasks(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[], promptStarted?: () => void): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[], options?: Pick<PromptOptions, \"source\">): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[], options?: Pick<PromptOptions, \"source\">): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_flushPendingCustomMessages(): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\" | \"interrupt\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>, options?: ModelMutationOptions): Promise<void>;\n\tcycleModel(\n\t\tdirection?: \"forward\" | \"backward\",\n\t\toptions?: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel, options?: ModelMutationOptions): void;\n\tcycleThinkingLevel(options?: ModelMutationOptions): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(targetModel?: Model<Api>, explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: Partial<VerbatimCompactionParameters>): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\tabortSessionSummary(): void;\n\t_maybeGenerateSessionSummary(): Promise<void>;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(\n\t\treason: \"overflow\" | \"threshold\",\n\t\twillRetry: boolean,\n\t\turgency?: CompactionUrgency,\n\t): Promise<AutoCompactionRunOutcome>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(\n\t\trunner: ExtensionRunner,\n\t\tpublication?: {\n\t\t\tresourceLoader: ResourceLoader;\n\t\t\tproviderTransaction: ExtensionProviderTransaction;\n\t\t\tproviderIds: Set<string>;\n\t\t\tdefer(effect: () => void | Promise<void>): void;\n\t\t},\n\t): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\tcompleteStartupResources(resourceLoader: ResourceLoader): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isFallbackableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\t_beginFallbackModelScope(): void;\n\t_clearFallbackModelScope(): void;\n\t_settleFallbackModelScope(): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string, options?: { themeName?: string }): Promise<string>;\n\texportToJsonl(outputPath?: string, options?: { includeShareContext?: boolean }): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"getAgentTaskHost\"\n\t\t| \"closeSessionTasks\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"abortSessionSummary\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"completeStartupResources\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_fallbackAttemptedKeys: Set<string>;\n\t_fallbackBlockedModels: Array<Model<Api>>;\n\t_fallbackOriginModel: Model<Api> | undefined;\n\t_fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\t_fallbackScopeGeneration: number;\n\t_fallbackOriginGeneration: number | undefined;\n\t_fallbackRestoreError: string | undefined;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_stopAfterTurnBlockedContinuation: boolean;\n\t_pendingInterruptDeliveries: number;\n\t_priorityInterruptPending: boolean;\n\t_activePromptCount: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_admittedQueuedMessageAwaitingReply: string | undefined;\n\t_admittedRecoveryTurn: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_pendingCustomMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_autoCompactionCompletion: Promise<void> | undefined;\n\t_compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_recoverableLengthRecoveryAttempted: boolean;\n\t_contextOverflowUnresolved: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_branchSummaryCompletion: Promise<void> | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, AbortController>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_subagentPolicy?: import(\"./extensions/index.js\").SubagentChildPolicy;\n\t_subagentMessageAdmission?: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_disposed: boolean;\n\t_sessionSummaryAbortController: AbortController | undefined;\n\t_sessionSummaryToken: number;\n\t_sessionSummaryRun: import(\"./agent-session-summary.ts\").SessionSummaryRun | undefined;\n\t_lastSummarizedMessageId: string | undefined;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_extensionProviderIds: Set<string>;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_systemPromptTransform?: (prompt: string) => string;\n\t_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_tempStorageLease: import(\"./tools/session-temp-dir.ts\").ProtectedPathLease | undefined;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n\t_agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\t_taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\t_taskAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
@@ -14,7 +14,7 @@ export declare function recoverProtectedStreamingCustomMessages(session: AgentSe
14
14
  /** Persist one visible card and register its hidden model-facing turn. */
15
15
  export declare function admitProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage, delivery: ProtectedDelivery): Promise<CustomMessage>;
16
16
  /** Queue one hidden turn before public listeners can transfer its ownership. */
17
- export declare function queueProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage, delivery: ProtectedDelivery): Promise<void>;
17
+ export declare function queueProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage, delivery: ProtectedDelivery, priority?: boolean): Promise<void>;
18
18
  /** Queue a whole hidden batch before public listeners can transfer ownership. */
19
19
  export declare function queueProtectedStreamingCustomMessages(session: AgentSession, messages: CustomMessage[], delivery: ProtectedDelivery): Promise<void>;
20
20
  /** Start or queue an idle protected batch before exposing its display cards. */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-persistent-custom-messages.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KA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YAAY,EACrB,OAAO,EAAE,aAAa,GACpB,IAAI,CAGN;AAED,wBAAgB,iCAAiC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAExG;AAED;;;;GAIG;AACH,wBAAgB,sCAAsC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAkB7G;AAED,+EAA+E;AAC/E,wBAAgB,6CAA6C,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAUzF;AAED,4EAA4E;AAC5E,wBAAgB,6CAA6C,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAOzF;AAgCD;;;;GAIG;AACH,wBAAgB,kDAAkD,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAsB9F;AAED,kFAAkF;AAClF,wBAAgB,uCAAuC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAOhH;AAED,oFAAoF;AACpF,wBAAgB,wCAAwC,CACvD,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,YAAY,EACpB,WAAW,EAAE,kBAAkB,GAC7B,IAAI,CAUN"}
1
+ {"version":3,"file":"agent-session-persistent-custom-messages.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,aAAa,EAA8B,MAAM,eAAe,CAAC;AAE/E,KAAK,iBAAiB,GAAG,OAAO,GAAG,UAAU,CAAC;AAC9C,KAAK,cAAc,GAAG,QAAQ,GAAG,sBAAsB,GAAG,oBAAoB,CAAC;AAE/E,eAAO,MAAM,oCAAoC,8CAA8C,CAAC;AAMhG,MAAM,WAAW,+BAA+B;IAC/C,OAAO,EAAE,aAAa,CAAC;IAC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GAAG,IAAI,CAUzF;AAED,4EAA4E;AAC5E,wBAAgB,6CAA6C,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAOzF;AAgCD;;;;GAIG;AACH,wBAAgB,kDAAkD,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAsB9F;AAED,kFAAkF;AAClF,wBAAgB,uCAAuC,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,EAAE,kBAAkB,GAAG,IAAI,CAOhH;AAED,oFAAoF;AACpF,wBAAgB,wCAAwC,CACvD,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,YAAY,EACpB,WAAW,EAAE,kBAAkB,GAC7B,IAAI,CAUN"}
@@ -8,9 +8,19 @@ function protectedMessages(session) {
8
8
  function appendDurableDisplayCard(session, message, delivery) {
9
9
  const card = { ...message, excludeFromContext: true };
10
10
  const admitted = message;
11
+ // A retry after a failed flush must complete the already-appended occurrence
12
+ // rather than append a second visible card for the same stable key.
13
+ const partial = admitted.stageAdmissionKey === undefined
14
+ ? undefined
15
+ : session.sessionManager
16
+ .getBranch()
17
+ .find((entry) => entry.type === "custom_message" &&
18
+ entry.stageAdmissionKey === admitted.stageAdmissionKey &&
19
+ protectedDelivery(entry.protectedReconciliation) !== undefined);
11
20
  // The card and recovery marker share one append, so either both survive a
12
21
  // process exit or neither does.
13
- const intentEntryId = session.sessionManager.appendCustomMessageEntry(card.customType, card.content, card.display, card.details, true, { delivery }, admitted.stageAdmissionKey);
22
+ const intentEntryId = partial?.id ??
23
+ session.sessionManager.appendCustomMessageEntry(card.customType, card.content, card.display, card.details, true, { delivery }, admitted.stageAdmissionKey);
14
24
  if (admitted.stageAdmissionKey !== undefined)
15
25
  session.sessionManager.flush();
16
26
  session.agent.state.messages.push(card);
@@ -116,9 +126,9 @@ export async function admitProtectedStreamingCustomMessage(session, message, del
116
126
  return admission.reconciliations[0];
117
127
  }
118
128
  /** Queue one hidden turn before public listeners can transfer its ownership. */
119
- export async function queueProtectedStreamingCustomMessage(session, message, delivery) {
129
+ export async function queueProtectedStreamingCustomMessage(session, message, delivery, priority = false) {
120
130
  const admission = await prepareProtectedAdmission(session, [message], delivery);
121
- admission.owner._queueAgentMessage(admission.reconciliations[0], delivery);
131
+ admission.owner._queueAgentMessage(admission.reconciliations[0], priority ? "interrupt" : delivery);
122
132
  emitProtectedAdmission(admission);
123
133
  }
124
134
  /** Queue a whole hidden batch before public listeners can transfer ownership. */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAMxE,MAAM,CAAC,MAAM,oCAAoC,GAAG,2CAA2C,CAAC;AAYhG,SAAS,iBAAiB,CAAC,OAAqB;IAC/C,OAAO,CAAC,iCAAiC,KAAK,EAAE,CAAC;IACjD,OAAO,OAAO,CAAC,iCAAiC,CAAC;AAClD,CAAC;AAED,SAAS,wBAAwB,CAChC,OAAqB,EACrB,OAAsB,EACtB,QAA2B;IAE3B,MAAM,IAAI,GAAG,EAAE,GAAG,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAyD,CAAC;IAC7G,MAAM,QAAQ,GAAG,OAAqC,CAAC;IACvD,0EAA0E;IAC1E,gCAAgC;IAChC,MAAM,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,wBAAwB,CACpE,IAAI,CAAC,UAAU,EACf,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,OAAO,EACZ,IAAI,EACJ,EAAE,QAAQ,EAAE,EACZ,QAAQ,CAAC,iBAAiB,CAC1B,CAAC;IACF,IAAI,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QAAE,OAAO,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;IAC7E,OAAO,CAAC,KAAK,CAAC,K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kflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.ts\";\nimport { customMessageExcludesContext } from \"./agent-session-types.ts\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nfunction appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): { readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string } {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId = session.sessionManager.appendCustomMessageEntry(\n\t\tcard.customType,\n\t\tcard.content,\n\t\tcard.display,\n\t\tcard.details,\n\t\ttrue,\n\t\t{ delivery },\n\t\tadmitted.stageAdmissionKey,\n\t);\n\tif (admitted.stageAdmissionKey !== undefined) session.sessionManager.flush();\n\tsession.agent.state.messages.push(card);\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Requeue each durable card intent that has no persisted hidden completion. */\nexport function recoverProtectedStreamingCustomMessages(session: AgentSession): number {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tlet recovered = 0;\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst card: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: entry.display,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tconst reconciliation = createProtectedReconciliation(card, entry.id);\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, delivery);\n\t\trecovered += 1;\n\t}\n\treturn recovered;\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = messages.map((message) => {\n\t\tconst { card, intentEntryId } = appendDurableDisplayCard(owner, message, delivery);\n\t\treturn { card, reconciliation: createProtectedReconciliation(message, intentEntryId) };\n\t});\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport function persistProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tsession.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\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): void {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tpersistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): void {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tpersistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): void {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tsession.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tflushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
1
+ {"version":3,"file":"agent-session-persistent-custom-messages.js","sourceRoot":"","sources":["../../src/core/agent-session-persistent-custom-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAMxE,MAAM,CAAC,MAAM,oCAAoC,GAAG,2CAA2C,CAAC;AAYhG,SAAS,iBAAiB,CAAC,OAAqB;IA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AiB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,QAAQ,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC9E,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,OAAO,CAAC,EAAE,CAAC;QAChD,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE,CAAC;YACtE,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;QAC3D,CAAC;IACF,CAAC;AACF,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,wCAAwC,CACvD,MAAoB,EACpB,MAAoB,EACpB,WAA+B;IAE/B,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,QAAQ,EAAE,GAAG,WAAW,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC1F,MAAM,QAAQ,GAAsC,EAAE,CAAC;IACvD,MAAM,KAAK,GAAsC,EAAE,CAAC;IACpD,KAAK,MAAM,KAAK,IAAI,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;QAC/C,IAAI,KAAK,CAAC,KAAK,KAAK,QAAQ,IAAI,qBAAqB,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC;YAAE,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YACvF,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3B,CAAC;IACD,MAAM,CAAC,iCAAiC,GAAG,QAAQ,CAAC;IACpD,iBAAiB,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { DrainedAgentQueues } from \"./agent-session-types.ts\";\nimport { customMessageExcludesContext } from \"./agent-session-types.ts\";\nimport type { CustomMessage, StageAdmittedCustomMessage } from \"./messages.ts\";\n\ntype ProtectedDelivery = \"steer\" | \"followUp\";\ntype ProtectedPhase = \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\nexport const PROTECTED_RECONCILIATION_CUSTOM_TYPE = \"atomic:protected-streaming-reconciliation\";\n\ninterface ProtectedReconciliationDetails {\n\tprotectedReconciliationOf: string;\n}\n\nexport interface ProtectedStreamingCustomMessage {\n\tmessage: CustomMessage;\n\tdelivery: ProtectedDelivery;\n\tphase: ProtectedPhase;\n}\n\nfunction protectedMessages(session: AgentSession): ProtectedStreamingCustomMessage[] {\n\tsession._protectedStreamingCustomMessages ??= [];\n\treturn session._protectedStreamingCustomMessages;\n}\n\nfunction appendDurableDisplayCard(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): { readonly card: CustomMessage & { excludeFromContext: true }; readonly intentEntryId: string } {\n\tconst card = { ...message, excludeFromContext: true } satisfies CustomMessage & { excludeFromContext: true };\n\tconst admitted = message as StageAdmittedCustomMessage;\n\t// A retry after a failed flush must complete the already-appended occurrence\n\t// rather than append a second visible card for the same stable key.\n\tconst partial =\n\t\tadmitted.stageAdmissionKey === undefined\n\t\t\t? undefined\n\t\t\t: session.sessionManager\n\t\t\t\t\t.getBranch()\n\t\t\t\t\t.find(\n\t\t\t\t\t\t(entry) =>\n\t\t\t\t\t\t\tentry.type === \"custom_message\" &&\n\t\t\t\t\t\t\tentry.stageAdmissionKey === admitted.stageAdmissionKey &&\n\t\t\t\t\t\t\tprotectedDelivery(entry.protectedReconciliation) !== undefined,\n\t\t\t\t\t);\n\t// The card and recovery marker share one append, so either both survive a\n\t// process exit or neither does.\n\tconst intentEntryId =\n\t\tpartial?.id ??\n\t\tsession.sessionManager.appendCustomMessageEntry(\n\t\t\tcard.customType,\n\t\t\tcard.content,\n\t\t\tcard.display,\n\t\t\tcard.details,\n\t\t\ttrue,\n\t\t\t{ delivery },\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\tif (admitted.stageAdmissionKey !== undefined) session.sessionManager.flush();\n\tsession.agent.state.messages.push(card);\n\treturn { card, intentEntryId };\n}\n\nfunction emitDurableDisplayCard(session: AgentSession, card: CustomMessage): void {\n\t// The card is already live and file-backed, and its protected reconciliation\n\t// is registered. Public listeners remain fallible, but their errors cannot\n\t// revoke admission or make the producer retry this committed occurrence.\n\ttry {\n\t\tsession._emit({ type: \"message_start\", message: card });\n\t} catch {}\n\ttry {\n\t\tsession._emit({ type: \"message_end\", message: card });\n\t} catch {}\n}\n\nfunction createProtectedReconciliation(message: CustomMessage, intentEntryId: string): CustomMessage {\n\treturn {\n\t\trole: \"custom\",\n\t\tcustomType: PROTECTED_RECONCILIATION_CUSTOM_TYPE,\n\t\tcontent: message.content,\n\t\tdisplay: false,\n\t\tdetails: { protectedReconciliationOf: intentEntryId } satisfies ProtectedReconciliationDetails,\n\t\ttimestamp: message.timestamp,\n\t};\n}\n\nfunction completedReconciliationIntent(details: unknown): string | undefined {\n\tif (details === null || typeof details !== \"object\") return undefined;\n\tconst intent = (details as { protectedReconciliationOf?: unknown }).protectedReconciliationOf;\n\treturn typeof intent === \"string\" ? intent : undefined;\n}\n\nfunction protectedDelivery(marker: unknown): ProtectedDelivery | undefined {\n\tif (marker === null || typeof marker !== \"object\") return undefined;\n\tconst delivery = (marker as { delivery?: unknown }).delivery;\n\treturn delivery === \"steer\" || delivery === \"followUp\" ? delivery : undefined;\n}\n\n/** Requeue each durable card intent that has no persisted hidden completion. */\nexport function recoverProtectedStreamingCustomMessages(session: AgentSession): number {\n\tconst branch = session.sessionManager.getBranch();\n\tconst completed = new Set(\n\t\tbranch.flatMap((entry) =>\n\t\t\tentry.type === \"custom_message\" && entry.customType === PROTECTED_RECONCILIATION_CUSTOM_TYPE\n\t\t\t\t? [completedReconciliationIntent(entry.details)].filter((intent): intent is string => intent !== undefined)\n\t\t\t\t: [],\n\t\t),\n\t);\n\tconst scheduled = new Set(\n\t\tprotectedMessages(session).flatMap((entry) => {\n\t\t\tconst intent = completedReconciliationIntent(entry.message.details);\n\t\t\treturn intent === undefined ? [] : [intent];\n\t\t}),\n\t);\n\tlet recovered = 0;\n\tfor (const entry of branch) {\n\t\tif (entry.type !== \"custom_message\") continue;\n\t\tconst delivery = protectedDelivery(entry.protectedReconciliation);\n\t\tif (delivery === undefined || completed.has(entry.id) || scheduled.has(entry.id)) continue;\n\t\tconst parsedTimestamp = Date.parse(entry.timestamp);\n\t\tconst card: CustomMessage = {\n\t\t\trole: \"custom\",\n\t\t\tcustomType: entry.customType,\n\t\t\tcontent: entry.content,\n\t\t\tdisplay: entry.display,\n\t\t\tdetails: entry.details,\n\t\t\ttimestamp: Number.isFinite(parsedTimestamp) ? parsedTimestamp : Date.now(),\n\t\t};\n\t\tconst reconciliation = createProtectedReconciliation(card, entry.id);\n\t\tprotectedMessages(session).push({ message: reconciliation, delivery, phase: \"queued\" });\n\t\tsession._queueAgentMessage(reconciliation, delivery);\n\t\trecovered += 1;\n\t}\n\treturn recovered;\n}\n\ninterface ProtectedAdmission {\n\towner: AgentSession;\n\tcards: CustomMessage[];\n\treconciliations: CustomMessage[];\n}\n\nasync function prepareProtectedAdmission(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<ProtectedAdmission> {\n\t// While the initiating workflow tool is still executing, its assistant call\n\t// may be ahead of SessionManager's async event writer. Wait only in that\n\t// protocol-sensitive phase; at ordinary turn boundaries the hidden steer must\n\t// be queued synchronously so agent-core's next native poll observes it.\n\tif (session.agent.state.pendingToolCalls.size > 0) await session._agentEventQueue;\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tconst prepared = messages.map((message) => {\n\t\tconst { card, intentEntryId } = appendDurableDisplayCard(owner, message, delivery);\n\t\treturn { card, reconciliation: createProtectedReconciliation(message, intentEntryId) };\n\t});\n\tconst cards = prepared.map((entry) => entry.card);\n\tconst reconciliations = prepared.map((entry) => entry.reconciliation);\n\tprotectedMessages(owner).push(\n\t\t...reconciliations.map((message) => ({ message, delivery, phase: \"queued\" as const })),\n\t);\n\treturn { owner, cards, reconciliations };\n}\n\nfunction emitProtectedAdmission(admission: ProtectedAdmission): AgentSession {\n\tlet owner = admission.owner;\n\tfor (const card of admission.cards) {\n\t\towner = resolveWorkflowStageDeliveryTarget(owner);\n\t\temitDurableDisplayCard(owner, card);\n\t}\n\treturn resolveWorkflowStageDeliveryTarget(owner);\n}\n\n/** Persist one visible card and register its hidden model-facing turn. */\nexport async function admitProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n): Promise<CustomMessage> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\temitProtectedAdmission(admission);\n\treturn admission.reconciliations[0]!;\n}\n\n/** Queue one hidden turn before public listeners can transfer its ownership. */\nexport async function queueProtectedStreamingCustomMessage(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n\tdelivery: ProtectedDelivery,\n\tpriority = false,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, [message], delivery);\n\tadmission.owner._queueAgentMessage(admission.reconciliations[0]!, priority ? \"interrupt\" : delivery);\n\temitProtectedAdmission(admission);\n}\n\n/** Queue a whole hidden batch before public listeners can transfer ownership. */\nexport async function queueProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\temitProtectedAdmission(admission);\n}\n\n/** Start or queue an idle protected batch before exposing its display cards. */\nexport async function triggerProtectedStreamingCustomMessages(\n\tsession: AgentSession,\n\tmessages: CustomMessage[],\n\tdelivery: ProtectedDelivery,\n): Promise<void> {\n\tconst admission = await prepareProtectedAdmission(session, messages, delivery);\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tadmission.owner._queueAgentMessage(reconciliation, delivery);\n\t}\n\tconst owner = emitProtectedAdmission(admission);\n\tif (owner.isStreaming || owner._queuedMessagesPaused) return;\n\tfor (const reconciliation of admission.reconciliations) {\n\t\tremoveQueuedProtectedReference(owner, reconciliation);\n\t}\n\tconst turn = owner._runAgentPrompt(admission.reconciliations);\n\tvoid turn.catch(() => {});\n}\n\n/** Record that agent-core drained and consumed the hidden reconciliation. */\nexport function markProtectedStreamingCustomMessageConsumed(session: AgentSession, message: CustomMessage): boolean {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (!entry) return false;\n\tentry.phase = \"consumed-unpersisted\";\n\treturn true;\n}\n\nexport function markProtectedStreamingCustomMessagePersistenceFailed(\n\tsession: AgentSession,\n\tmessage: CustomMessage,\n): void {\n\tconst entry = protectedMessages(session).find((candidate) => candidate.message === message);\n\tif (entry?.phase === \"consumed-unpersisted\") entry.phase = \"persistence-failed\";\n}\n\nexport function isProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\treturn protectedMessages(session).some((entry) => entry.message === message);\n}\n\n/**\n * Persist a consumed hidden reconciliation exactly once. Its visible card was\n * already committed at admission, so a transient failure never re-adds a card\n * or re-injects another provider message.\n */\nexport function persistProtectedStreamingCustomMessage(session: AgentSession, message: CustomMessage): boolean {\n\tconst pending = protectedMessages(session);\n\tconst index = pending.findIndex((entry) => entry.message === message);\n\tif (index === -1) return false;\n\tconst entry = pending[index];\n\tconst admitted = message as StageAdmittedCustomMessage;\n\tif (entry.phase !== \"consumed-unpersisted\" && entry.phase !== \"persistence-failed\") return true;\n\tsession.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\tadmitted.stageAdmissionKey,\n\t);\n\tpending.splice(index, 1);\n\treturn true;\n}\n\n/** Retry only hidden reconciliation persistence; never queue another alias. */\nexport function retryConsumedProtectedStreamingCustomMessages(session: AgentSession): void {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase !== \"persistence-failed\") continue;\n\t\ttry {\n\t\t\tpersistProtectedStreamingCustomMessage(session, entry.message);\n\t\t} catch {\n\t\t\t// The visible lifecycle card is already durable. Keep this consumed phase\n\t\t\t// for a later event rather than duplicating either the card or model turn.\n\t\t}\n\t}\n}\n\n/** Flush consumed reconciliations before session state can be discarded. */\nexport function flushConsumedProtectedStreamingCustomMessages(session: AgentSession): void {\n\tfor (const entry of [...protectedMessages(session)]) {\n\t\tif (entry.phase === \"queued\") continue;\n\t\t// Do not swallow the final write failure: callers must keep this session\n\t\t// alive rather than discard the only remaining recovery state.\n\t\tpersistProtectedStreamingCustomMessage(session, entry.message);\n\t}\n}\n\nfunction removeReference<T>(items: T[], message: T): void {\n\tlet index = items.indexOf(message);\n\twhile (index >= 0) {\n\t\titems.splice(index, 1);\n\t\tindex = items.indexOf(message);\n\t}\n}\n\nfunction removeQueuedProtectedReference(session: AgentSession, message: CustomMessage): void {\n\tconst hold = session._activeInterruptQueueHold;\n\tif (hold !== undefined) {\n\t\tremoveReference(hold.steering, message);\n\t\tremoveReference(hold.followUp, message);\n\t}\n\tconst queues = session._drainQueuedAgentMessages();\n\tsession._restoreQueuedAgentMessages({\n\t\tsteering: queues.steering.filter((candidate) => candidate !== message),\n\t\tfollowUp: queues.followUp.filter((candidate) => candidate !== message),\n\t});\n}\n\nfunction isPausedHeldProtectedReference(session: AgentSession, message: CustomMessage): boolean {\n\tconst hold = session._activeInterruptQueueHold;\n\treturn (\n\t\tsession._queuedMessagesPaused &&\n\t\thold !== undefined &&\n\t\t(hold.steering.includes(message) || hold.followUp.includes(message))\n\t);\n}\n\n/**\n * Persist only reconciliation input already sealed inside an accepted pause\n * hold. Other queued input can still race an active protocol turn and must keep\n * the historical fail-closed disposal behavior.\n */\nexport function prepareProtectedStreamingCustomMessagesForDisposal(session: AgentSession): void {\n\tconst pending = protectedMessages(session);\n\tconst queued = pending.filter((entry) => entry.phase === \"queued\");\n\tif (queued.some((entry) => !isPausedHeldProtectedReference(session, entry.message))) {\n\t\tthrow new Error(\"Cannot dispose a session with a queued protected reconciliation\");\n\t}\n\tfor (const entry of queued) {\n\t\tconst admitted = entry.message as StageAdmittedCustomMessage;\n\t\tsession.sessionManager.appendCustomMessageEntry(\n\t\t\tentry.message.customType,\n\t\t\tentry.message.content,\n\t\t\tentry.message.display,\n\t\t\tentry.message.details,\n\t\t\tcustomMessageExcludesContext(entry.message),\n\t\t\tundefined,\n\t\t\tadmitted.stageAdmissionKey,\n\t\t);\n\t\tremoveQueuedProtectedReference(session, entry.message);\n\t\tconst index = pending.indexOf(entry);\n\t\tif (index >= 0) pending.splice(index, 1);\n\t}\n\tflushConsumedProtectedStreamingCustomMessages(session);\n}\n\n/** Restore only protected references actually removed from native queues/hold. */\nexport function restoreProtectedStreamingCustomMessages(session: AgentSession, removed: DrainedAgentQueues): void {\n\tconst removedReferences = new Set([...removed.steering, ...removed.followUp]);\n\tfor (const entry of protectedMessages(session)) {\n\t\tif (entry.phase === \"queued\" && removedReferences.has(entry.message)) {\n\t\t\tsession._queueAgentMessage(entry.message, entry.delivery);\n\t\t}\n\t}\n}\n\n/** Move protection only for message references that transfer with native queues. */\nexport function transferProtectedStreamingCustomMessages(\n\tsource: AgentSession,\n\ttarget: AgentSession,\n\ttransferred: DrainedAgentQueues,\n): void {\n\tconst transferredReferences = new Set([...transferred.steering, ...transferred.followUp]);\n\tconst retained: ProtectedStreamingCustomMessage[] = [];\n\tconst moved: ProtectedStreamingCustomMessage[] = [];\n\tfor (const entry of protectedMessages(source)) {\n\t\tif (entry.phase === \"queued\" && transferredReferences.has(entry.message)) moved.push(entry);\n\t\telse retained.push(entry);\n\t}\n\tsource._protectedStreamingCustomMessages = retained;\n\tprotectedMessages(target).unshift(...moved);\n}\n"]}
@@ -12,7 +12,7 @@ function hardLimitMessage(projectedTokens, hardInputLimit) {
12
12
  /** Compact tool-expanded context without scheduling a second Agent continuation. */
13
13
  export async function _preflightPostToolContext(messages, signal) {
14
14
  const model = this.model;
15
- const settings = this.settingsManager.getCompactionSettings();
15
+ const settings = this.settingsManager.getCompactionSettings(model);
16
16
  if (!model || !settings.enabled)
17
17
  return messages;
18
18
  const hardInputLimit = model.contextWindow;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAE/E,SAAS,sBAAsB,CAAC,KAAc;IAC7C,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,OAAO,yEAAyE,MAAM,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,gBAAgB,CAAC,eAAuB,EAAE,cAAsB;IACxE,OAAO,kFAAkF,eAAe,MAAM,cAAc,mDAAmD,CAAC;AACjL,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAE9C,QAAwB,EACxB,MAAoB;IAEpB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;IACzB,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,qBAAqB,EAAE,CAAC;IAC9D,IAAI,CAAC,KAAK,IAAI,CAAC,QAAQ,CAAC,OAAO;QAAE,OAAO,QA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AAI,CAAC,iCAAiC,GAAG,YAAY,CAAC;QACtD,IAAI,CAAC,KAAK,CAAC;YACV,IAAI,EAAE,gBAAgB;YACtB,MAAM,EAAE,WAAW;YACnB,MAAM,EAAE,OAAO,CAAC,MAAM;YACtB,OAAO,EAAE,KAAK;YACd,SAAS,EAAE,KAAK;YAChB,OAAO,EAAE,IAAI;YACb,YAAY;YACZ,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACzF,CAAC,CAAC;QACH,MAAM,IAAI,KAAK,CAAC,YAAY,CAAC,CAAC;IAC/B,CAAC;IAED,IAAI,CAAC,KAAK,CAAC;QACV,IAAI,EAAE,gBAAgB;QACtB,MAAM,EAAE,WAAW;QACnB,MAAM,EAAE,OAAO,CAAC,MAAM;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,KAAK;QAChB,OAAO,EAAE,IAAI;QACb,GAAG,CAAC,kCAAkC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,qBAAqB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACzF,CAAC,CAAC;IACH,OAAO,qBAAqB,CAAC;AAC9B,CAAC;AAOD,MAAM,CAAC,MAAM,qCAAqC,GAAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { createAutoCompactionCompletion, hasPendingManualCompactionTakeover } from \"./agent-session-auto-compaction.ts\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue;\n\t// Manual compaction owns the next boundary and aborts the active run before\n\t// planning. Do not append a competing mid-turn boundary in that brief gap.\n\tif (this._compactionAbortController !== undefined || this._manualCompactionPromise !== undefined) {\n\t\treturn messages;\n\t}\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tlet fromExtension = false;\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\t// Ownership publication and the synchronous `compaction_start` emission live\n\t// inside the cleanup scope: `_emit` runs subscribers synchronously, so a\n\t// throwing listener would otherwise leave ownership set with no `finally` to\n\t// clear it. A manual takeover also awaits this settlement before it writes.\n\ttry {\n\t\tthis._autoCompactionAbortController = abortController;\n\t\tthis._autoCompactionCompletion = completion.promise;\n\t\tthis._compactionReason = \"threshold\";\n\t\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst auth = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn auth.apiKey || auth.headers ? auth : undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// A mid-turn planner failure must reach the fresh rung so the active\n\t\t\t// turn can continue. `_applyVerbatimCompaction` still treats a fitting\n\t\t\t// no-preparation threshold crossing as a safe no-op.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies,\n\t\t// while the getter returns the live internal array. Return a separate array\n\t\t// so the loop and reducer cannot append the next message twice.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason: \"threshold\",\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tif (this._autoCompactionAbortController === abortController) this._autoCompactionAbortController = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tif (this._compactionReason === \"threshold\") this._compactionReason = undefined;\n\t}\n}\n\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(this: AgentSession, messages: AgentMessage[]): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\tconst projectedTokens = estimateContextTokens(providerBoundMessages).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
1
+ {"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AACxH,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAiC,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAE/E,SAAS,sBAAsB,CAAC,KAAc;IAC7C,MAAM,MAAM,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACtE,OAAO,yEAAyE,MAAM,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,gBAAgB,CAAC,eAAuB,EAAE,cAAsB;IACxE,OAAO,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C,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { createAutoCompactionCompletion, hasPendingManualCompactionTakeover } from \"./agent-session-auto-compaction.ts\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { estimateContextTokens, shouldCompact, type VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport { scrubPreCompactionAssistantUsage } from \"./provider-context-usage.ts\";\n\nfunction postToolFailureMessage(error: unknown): string {\n\tconst detail = error instanceof Error ? error.message : String(error);\n\treturn `Post-tool context compaction failed before the next provider request: ${detail}`;\n}\n\nfunction hardLimitMessage(projectedTokens: number, hardInputLimit: number): string {\n\treturn `Post-tool context remains over the provider hard input limit after compaction (${projectedTokens} > ${hardInputLimit} tokens); the next provider request was not sent.`;\n}\n\n/** Compact tool-expanded context without scheduling a second Agent continuation. */\nexport async function _preflightPostToolContext(\n\tthis: AgentSession,\n\tmessages: AgentMessage[],\n\tsignal?: AbortSignal,\n): Promise<AgentMessage[]> {\n\tconst model = this.model;\n\tconst settings = this.settingsManager.getCompactionSettings(model);\n\tif (!model || !settings.enabled) return messages;\n\n\tconst hardInputLimit = model.contextWindow;\n\tconst projectedTokens = estimateContextTokens(messages).tokens;\n\tif (!shouldCompact(projectedTokens, hardInputLimit, settings)) return messages;\n\t// Only a context that genuinely will not fit may clear a sub-minimum region.\n\t// The threshold sits at `contextWindow - reserveTokens`, well below the hard\n\t// limit, so a crossing alone is no reason to destroy context.\n\tconst overHardLimit = hardInputLimit > 0 && projectedTokens > hardInputLimit;\n\n\t// Tool-result persistence is ordered on AgentSession's event queue, while Pi\n\t// may reach its next-turn hook as soon as its own listener barrier settles.\n\tawait this._agentEventQueue;\n\t// Manual compaction owns the next boundary and aborts the active run before\n\t// planning. Do not append a competing mid-turn boundary in that brief gap.\n\tif (this._compactionAbortController !== undefined || this._manualCompactionPromise !== undefined) {\n\t\treturn messages;\n\t}\n\tif (this._autoCompactionAbortController) {\n\t\tconst message = postToolFailureMessage(\"another automatic compaction is already active\");\n\t\tthis._postToolCompactionPreflightError = message;\n\t\tthrow new Error(message);\n\t}\n\n\tconst abortController = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tlet fromExtension = false;\n\tconst relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\t// Ownership publication and the synchronous `compaction_start` emission live\n\t// inside the cleanup scope: `_emit` runs subscribers synchronously, so a\n\t// throwing listener would otherwise leave ownership set with no `finally` to\n\t// clear it. A manual takeover also awaits this settlement before it writes.\n\ttry {\n\t\tthis._autoCompactionAbortController = abortController;\n\t\tthis._autoCompactionCompletion = completion.promise;\n\t\tthis._compactionReason = \"threshold\";\n\t\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst auth = await this._getRequiredRequestAuth(candidate);\n\t\t\t\treturn auth.apiKey || auth.headers ? auth : undefined;\n\t\t\t},\n\t\t\tabortController,\n\t\t\tbackupLabel: \"auto-compact\",\n\t\t\treason: \"threshold\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// A mid-turn planner failure must reach the fresh rung so the active\n\t\t\t// turn can continue. `_applyVerbatimCompaction` still treats a fitting\n\t\t\t// no-preparation threshold crossing as a safe no-op.\n\t\t\turgency: \"load_bearing\",\n\t\t\t...(overHardLimit ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\t// Nothing was compactable and the projected context still fits, so the\n\t\t\t// follow-up request can be sent unchanged. That is a successful no-op,\n\t\t\t// not a failure: raising here is what killed the active turn.\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"threshold\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tmidTurn: true,\n\t\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\treturn messages;\n\t\t}\n\n\t\tthis._pendingPostToolCompactionGuard = { hardInputLimit, result };\n\t\t// `AgentState.messages` has an asymmetric accessor pair: the setter copies,\n\t\t// while the getter returns the live internal array. Return a separate array\n\t\t// so the loop and reducer cannot append the next message twice.\n\t\treturn this.agent.state.messages.slice();\n\t} catch (error) {\n\t\tconst detail = error instanceof Error ? error.message : String(error);\n\t\tconst aborted =\n\t\t\tabortController.signal.aborted ||\n\t\t\tdetail === \"Compaction cancelled\" ||\n\t\t\t(error instanceof Error && error.name === \"AbortError\");\n\t\tconst errorMessage = aborted\n\t\t\t? \"Post-tool context compaction was cancelled before the next provider request.\"\n\t\t\t: postToolFailureMessage(error);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason: \"threshold\",\n\t\t\t...(aborted ? {} : { errorMessage }),\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tif (this._autoCompactionAbortController === abortController) this._autoCompactionAbortController = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tif (this._compactionReason === \"threshold\") this._compactionReason = undefined;\n\t}\n}\n\n/** Gate the transformed message context immediately before provider conversion. */\nexport function _finishPostToolCompactionPreflight(this: AgentSession, messages: AgentMessage[]): AgentMessage[] {\n\tconst pending = this._pendingPostToolCompactionGuard;\n\tif (!pending) return messages;\n\tthis._pendingPostToolCompactionGuard = undefined;\n\n\tconst providerBoundMessages = scrubPreCompactionAssistantUsage(messages, this.sessionManager.getBranch());\n\tconst projectedTokens = estimateContextTokens(providerBoundMessages).tokens;\n\tif (projectedTokens > pending.hardInputLimit) {\n\t\tconst errorMessage = hardLimitMessage(projectedTokens, pending.hardInputLimit);\n\t\tthis._postToolCompactionPreflightError = errorMessage;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult: pending.result,\n\t\t\taborted: false,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\terrorMessage,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tthrow new Error(errorMessage);\n\t}\n\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"threshold\",\n\t\tresult: pending.result,\n\t\taborted: false,\n\t\twillRetry: false,\n\t\tmidTurn: true,\n\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t});\n\treturn providerBoundMessages;\n}\n\nexport interface PendingPostToolCompactionGuard {\n\thardInputLimit: number;\n\tresult: VerbatimCompactionResult;\n}\n\nexport const agentSessionPostToolCompactionMethods = {\n\t_preflightPostToolContext,\n\t_finishPostToolCompactionPreflight,\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-prompt.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,E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AC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAiC5E;AA4BD;;;;;;;GAOG;AAEH,wBAAsB,KAAK,CAC1B,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,GACrC,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;;;;;GAMG;AAEH,wBAAsB,QAAQ,CAC7B,IAAI,EAAE,YAAY,EAClB,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,YAAY,EAAE,EACvB,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,QAAQ,CAAC,GACrC,OAAO,CAAC,IAAI,CAAC,CAEf;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,eAAe,CACpC,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;IACT,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;IACjC,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,kBAAkB,CAAC,EAAE,iCAAiC,CAAC,oBAAoB,CAAC,CAAC;CAC7E,GACC,OAAO,CAAC,IAAI,CAAC,CAgCf;AAED;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB;;;;;;;;;;CAUrC,CAAC"}
@@ -12,6 +12,27 @@ export async function tryExecuteSessionSlashCommand(session, text) {
12
12
  return session._tryExecuteExtensionCommand(text);
13
13
  }
14
14
  export async function prompt(text, options) {
15
+ this._activePromptCount += 1;
16
+ try {
17
+ await promptInternal.call(this, text, options);
18
+ const boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;
19
+ if (this._activePromptCount === 1 &&
20
+ !this.isStreaming &&
21
+ !this._queuedMessagesPaused &&
22
+ (this._priorityInterruptPending || boundary?.hasMessageDeliveries())) {
23
+ // A command/input hook may consume the original prompt during preflight.
24
+ // Its owner still owes independently admitted priority input a reply; drain
25
+ // that input without replaying preflight or starting another task prompt.
26
+ await this._continueQueuedAgentMessages();
27
+ if (this._subagentMessageAdmission)
28
+ await settleSubagentMessages(this);
29
+ }
30
+ }
31
+ finally {
32
+ this._activePromptCount -= 1;
33
+ }
34
+ }
35
+ async function promptInternal(text, options) {
15
36
  const owner = resolveWorkflowStageDeliveryTarget(this);
16
37
  if (owner !== this)
17
38
  return owner.prompt(text, options);
@@ -187,7 +208,24 @@ export async function _runAgentPrompt(messages, promptStarted) {
187
208
  }
188
209
  return owner._runAgentPrompt(messages, promptStarted);
189
210
  }
211
+ this._activePromptCount += 1;
190
212
  try {
213
+ if (this._subagentMessageAdmission) {
214
+ await this._subagentMessageAdmission.waitForPendingDeliveries();
215
+ if (!this._subagentMessageAdmission.isOpen())
216
+ return;
217
+ }
218
+ const pendingPriority = preparePriorityContinuation(this);
219
+ if (pendingPriority)
220
+ await pendingPriority;
221
+ // An explicit stop may win during input preflight or priority preparation.
222
+ // Preserve the prepared input without opening a native turn past that gate.
223
+ if (this._queuedMessagesPaused) {
224
+ const items = Array.isArray(messages) ? messages : [messages];
225
+ for (const message of items)
226
+ this._queueAgentMessage(message, "steer");
227
+ return;
228
+ }
191
229
  const turn = this.agent.prompt(messages);
192
230
  if (this.isStreaming)
193
231
  promptStarted?.();
@@ -204,19 +242,64 @@ export async function _runAgentPrompt(messages, promptStarted) {
204
242
  await this._extensionRunner.emit({ type: "agent_settled" });
205
243
  }
206
244
  this._emit?.({ type: "agent_settled" });
245
+ if (this._subagentMessageAdmission)
246
+ await settleSubagentMessages(this);
247
+ this._activePromptCount -= 1;
207
248
  }
208
249
  }
250
+ async function settleSubagentMessages(session) {
251
+ const admission = session._subagentMessageAdmission;
252
+ // A host-requested stop is terminal for a child, like cancellation. Retain
253
+ // protected input for persistence without restarting work or spinning on it.
254
+ if (session._stopAfterTurnBlockedContinuation)
255
+ session.pauseQueuedMessages();
256
+ // Keep receiving while admitted input is answered. Seal synchronously only
257
+ // after both producer commits and native continuations have drained.
258
+ do {
259
+ await admission.waitForPendingDeliveries();
260
+ await session._continueQueuedAgentMessages();
261
+ if (session._stopAfterTurnBlockedContinuation)
262
+ session.pauseQueuedMessages();
263
+ } while (admission.hasPendingDeliveries() || (!session._queuedMessagesPaused && session.agent.hasQueuedMessages()));
264
+ admission.seal();
265
+ }
209
266
  export async function _runAgentContinue() {
210
267
  await this.agent.continue();
211
268
  await this.waitForRetry();
212
269
  await this._continueQueuedAgentMessages();
213
270
  }
271
+ /** Restore priority input the moment the native loop can poll it again. */
272
+ function preparePriorityContinuation(session) {
273
+ const boundary = session._subagentMessageAdmission ?? session._workflowStageAdmission;
274
+ // Explicit SDK interrupts own a native turn and the shared hold. An admitted
275
+ // receiver's task must join that owner before checking its priority input;
276
+ // otherwise it can settle before the interrupt finalizer restores the queue.
277
+ if (boundary && session._pendingInterruptDeliveries > 0) {
278
+ return session._interruptDeliveryQueue.then(() => preparePriorityContinuation(session));
279
+ }
280
+ const restore = () => {
281
+ if (!session._priorityInterruptPending)
282
+ return;
283
+ session._priorityInterruptPending = false;
284
+ session._restoreAndClearActiveInterruptQueueHold();
285
+ };
286
+ // Keep the idle prompt start synchronous unless a producer commit is still in flight.
287
+ if (!boundary?.hasMessageDeliveries()) {
288
+ restore();
289
+ return undefined;
290
+ }
291
+ // A producer can enqueue an explicit SDK interrupt while this await yields.
292
+ // Recheck its ownership before restoring the shared hold.
293
+ return boundary.waitForMessageDeliveries().then(() => preparePriorityContinuation(session));
294
+ }
214
295
  export async function _continueQueuedAgentMessages() {
215
296
  await this._agentEventQueue;
297
+ await preparePriorityContinuation(this);
216
298
  while (!this._stopAfterTurnBlockedContinuation && !this._queuedMessagesPaused && this.agent.hasQueuedMessages()) {
217
299
  await this.agent.continue();
218
300
  await this.waitForRetry();
219
301
  await this._agentEventQueue;
302
+ await preparePriorityContinuation(this);
220
303
  }
221
304
  if (this._stopAfterTurnBlockedContinuation)
222
305
  return;