@bastani/atomic 0.9.11-alpha.10 → 0.9.11-alpha.12

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 (224) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/intercom/subagent-relay.ts +8 -5
  5. package/dist/builtin/mcp/package.json +1 -1
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/subagents/src/extension/notification-content.ts +14 -9
  8. package/dist/builtin/subagents/src/runs/background/notify.ts +20 -4
  9. package/dist/builtin/web-access/CHANGELOG.md +13 -0
  10. package/dist/builtin/web-access/content-tools.ts +1 -0
  11. package/dist/builtin/web-access/flat-string.ts +37 -0
  12. package/dist/builtin/web-access/github-api.ts +2 -1
  13. package/dist/builtin/web-access/github-extract.ts +3 -2
  14. package/dist/builtin/web-access/package.json +2 -2
  15. package/dist/builtin/workflows/CHANGELOG.md +10 -0
  16. package/dist/builtin/workflows/builtin/goal-ledger.ts +6 -4
  17. package/dist/builtin/workflows/builtin/goal-runner.ts +2 -1
  18. package/dist/builtin/workflows/builtin/goal.ts +1 -1
  19. package/dist/builtin/workflows/builtin/ralph-core.ts +8 -9
  20. package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +2 -4
  21. package/dist/builtin/workflows/builtin/ralph-runner.ts +5 -8
  22. package/dist/builtin/workflows/builtin/ralph.ts +2 -1
  23. package/dist/builtin/workflows/package.json +1 -1
  24. package/dist/builtin/workflows/src/durable/completed-catalog.ts +14 -8
  25. package/dist/builtin/workflows/src/durable/completed-inspection.ts +10 -11
  26. package/dist/builtin/workflows/src/durable/resume-catalog.ts +1 -1
  27. package/dist/builtin/workflows/src/durable/resume-eligibility.ts +42 -0
  28. package/dist/builtin/workflows/src/durable/resume-runtime.ts +36 -37
  29. package/dist/builtin/workflows/src/durable/tool-primitive.ts +10 -2
  30. package/dist/builtin/workflows/src/engine/run.ts +1 -0
  31. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +12 -8
  32. package/dist/builtin/workflows/src/extension/hil-answer-notifications.ts +5 -2
  33. package/dist/builtin/workflows/src/extension/index.bundle.mjs +1962 -876
  34. package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +6 -3
  35. package/dist/builtin/workflows/src/extension/postmortem-deps.ts +3 -2
  36. package/dist/builtin/workflows/src/extension/render-result.ts +4 -11
  37. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +17 -20
  38. package/dist/builtin/workflows/src/extension/runtime.ts +3 -3
  39. package/dist/builtin/workflows/src/extension/workflow-command-completions.ts +1 -1
  40. package/dist/builtin/workflows/src/extension/workflow-command-registration.ts +3 -7
  41. package/dist/builtin/workflows/src/extension/workflow-durable-resume-command.ts +21 -24
  42. package/dist/builtin/workflows/src/extension/workflow-resume-picker-rows.ts +38 -26
  43. package/dist/builtin/workflows/src/extension/workflow-resume-shadow.ts +2 -1
  44. package/dist/builtin/workflows/src/extension/workflow-run-control-command.ts +56 -64
  45. package/dist/builtin/workflows/src/extension/workflow-schema.ts +2 -2
  46. package/dist/builtin/workflows/src/extension/workflow-status-summary.ts +0 -5
  47. package/dist/builtin/workflows/src/extension/workflow-targets.ts +17 -20
  48. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -1
  49. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +24 -51
  50. package/dist/builtin/workflows/src/extension/workflow-tool-inspection.ts +7 -29
  51. package/dist/builtin/workflows/src/extension/workflow-tool-send.ts +5 -13
  52. package/dist/builtin/workflows/src/extension/workflow-tool.ts +4 -13
  53. package/dist/builtin/workflows/src/runs/background/quit.ts +4 -3
  54. package/dist/builtin/workflows/src/runs/background/run-inspect.ts +8 -8
  55. package/dist/builtin/workflows/src/runs/background/status.ts +2 -1
  56. package/dist/builtin/workflows/src/runs/background/workflow-lifecycle-aggregate.ts +2 -1
  57. package/dist/builtin/workflows/src/runs/foreground/executor-direct-helpers.ts +5 -5
  58. package/dist/builtin/workflows/src/runs/foreground/executor-lifecycle.ts +4 -0
  59. package/dist/builtin/workflows/src/runs/foreground/executor-scheduler.ts +2 -0
  60. package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +23 -8
  61. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +6 -2
  62. package/dist/builtin/workflows/src/runs/foreground/executor-task-prompts.ts +5 -0
  63. package/dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts +56 -10
  64. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +6 -0
  65. package/dist/builtin/workflows/src/runs/foreground/stage-runner-output.ts +137 -6
  66. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +2 -0
  67. package/dist/builtin/workflows/src/shared/authoring-contract-ui.ts +2 -0
  68. package/dist/builtin/workflows/src/shared/expanded-workflow-graph.ts +159 -10
  69. package/dist/builtin/workflows/src/shared/flat-string.ts +33 -0
  70. package/dist/builtin/workflows/src/shared/graph-store-snapshot.ts +144 -0
  71. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +2 -3
  72. package/dist/builtin/workflows/src/shared/run-id.ts +36 -0
  73. package/dist/builtin/workflows/src/shared/store-internal.ts +32 -3
  74. package/dist/builtin/workflows/src/shared/store-observation.ts +10 -0
  75. package/dist/builtin/workflows/src/shared/store-public-types.ts +8 -0
  76. package/dist/builtin/workflows/src/shared/store-run-methods.ts +14 -0
  77. package/dist/builtin/workflows/src/shared/store-types.ts +4 -0
  78. package/dist/builtin/workflows/src/shared/types.ts +2 -0
  79. package/dist/builtin/workflows/src/shared/workflow-artifacts.ts +261 -0
  80. package/dist/builtin/workflows/src/tui/dispatch-confirm.ts +39 -23
  81. package/dist/builtin/workflows/src/tui/graph-canvas.ts +26 -9
  82. package/dist/builtin/workflows/src/tui/graph-view-constants.ts +3 -0
  83. package/dist/builtin/workflows/src/tui/graph-view-graph-render.ts +95 -98
  84. package/dist/builtin/workflows/src/tui/graph-view-render.ts +7 -20
  85. package/dist/builtin/workflows/src/tui/graph-view-state.ts +160 -13
  86. package/dist/builtin/workflows/src/tui/layout.ts +8 -2
  87. package/dist/builtin/workflows/src/tui/node-card.ts +57 -45
  88. package/dist/builtin/workflows/src/tui/overlay-adapter.ts +4 -2
  89. package/dist/builtin/workflows/src/tui/prompt-card-render.ts +291 -21
  90. package/dist/builtin/workflows/src/tui/prompt-card.ts +1 -1
  91. package/dist/builtin/workflows/src/tui/renderers.ts +0 -1
  92. package/dist/builtin/workflows/src/tui/run-detail.ts +52 -35
  93. package/dist/builtin/workflows/src/tui/run-identity-rows.ts +97 -0
  94. package/dist/builtin/workflows/src/tui/session-overlays.ts +24 -3
  95. package/dist/builtin/workflows/src/tui/session-picker.ts +94 -41
  96. package/dist/builtin/workflows/src/tui/stage-chat-view-archive-history.ts +190 -26
  97. package/dist/builtin/workflows/src/tui/stage-chat-view-footer-status.ts +52 -18
  98. package/dist/builtin/workflows/src/tui/stage-chat-view-input.ts +9 -5
  99. package/dist/builtin/workflows/src/tui/stage-chat-view-state.ts +44 -4
  100. package/dist/builtin/workflows/src/tui/stage-chat-view-types.ts +3 -1
  101. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +3 -2
  102. package/dist/builtin/workflows/src/tui/status-list.ts +67 -45
  103. package/dist/builtin/workflows/src/tui/store-widget-installer.ts +7 -6
  104. package/dist/builtin/workflows/src/tui/widget.ts +49 -40
  105. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +15 -10
  106. package/dist/builtin/workflows/src/tui/workflow-resume-selector.ts +21 -8
  107. package/dist/core/agent-session-accessors.d.ts.map +1 -1
  108. package/dist/core/agent-session-accessors.js +5 -0
  109. package/dist/core/agent-session-accessors.js.map +1 -1
  110. package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
  111. package/dist/core/agent-session-auto-compaction.js +5 -0
  112. package/dist/core/agent-session-auto-compaction.js.map +1 -1
  113. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  114. package/dist/core/agent-session-compaction.js +3 -0
  115. package/dist/core/agent-session-compaction.js.map +1 -1
  116. package/dist/core/agent-session-events.d.ts.map +1 -1
  117. package/dist/core/agent-session-events.js +2 -1
  118. package/dist/core/agent-session-events.js.map +1 -1
  119. package/dist/core/agent-session-message-queue.d.ts +3 -7
  120. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  121. package/dist/core/agent-session-message-queue.js +27 -13
  122. package/dist/core/agent-session-message-queue.js.map +1 -1
  123. package/dist/core/agent-session-methods.d.ts +5 -3
  124. package/dist/core/agent-session-methods.d.ts.map +1 -1
  125. package/dist/core/agent-session-methods.js.map +1 -1
  126. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  127. package/dist/core/agent-session-persistent-custom-messages.js +6 -3
  128. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  129. package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
  130. package/dist/core/agent-session-post-tool-compaction.js +11 -2
  131. package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
  132. package/dist/core/agent-session-tree.d.ts.map +1 -1
  133. package/dist/core/agent-session-tree.js +4 -0
  134. package/dist/core/agent-session-tree.js.map +1 -1
  135. package/dist/core/agent-session-types.d.ts +4 -0
  136. package/dist/core/agent-session-types.d.ts.map +1 -1
  137. package/dist/core/agent-session-types.js.map +1 -1
  138. package/dist/core/agent-session.d.ts +2 -1
  139. package/dist/core/agent-session.d.ts.map +1 -1
  140. package/dist/core/agent-session.js +1 -0
  141. package/dist/core/agent-session.js.map +1 -1
  142. package/dist/core/bounded-model-refresh.d.ts +14 -0
  143. package/dist/core/bounded-model-refresh.d.ts.map +1 -0
  144. package/dist/core/bounded-model-refresh.js +38 -0
  145. package/dist/core/bounded-model-refresh.js.map +1 -0
  146. package/dist/core/messages.d.ts +5 -1
  147. package/dist/core/messages.d.ts.map +1 -1
  148. package/dist/core/messages.js +2 -1
  149. package/dist/core/messages.js.map +1 -1
  150. package/dist/core/session-manager-core.d.ts +1 -1
  151. package/dist/core/session-manager-core.d.ts.map +1 -1
  152. package/dist/core/session-manager-core.js +2 -2
  153. package/dist/core/session-manager-core.js.map +1 -1
  154. package/dist/core/session-manager-entries.d.ts +1 -1
  155. package/dist/core/session-manager-entries.d.ts.map +1 -1
  156. package/dist/core/session-manager-entries.js +2 -1
  157. package/dist/core/session-manager-entries.js.map +1 -1
  158. package/dist/core/session-manager-history.d.ts.map +1 -1
  159. package/dist/core/session-manager-history.js +2 -2
  160. package/dist/core/session-manager-history.js.map +1 -1
  161. package/dist/core/session-manager-types.d.ts +3 -0
  162. package/dist/core/session-manager-types.d.ts.map +1 -1
  163. package/dist/core/session-manager-types.js.map +1 -1
  164. package/dist/index.d.ts +1 -1
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js.map +1 -1
  167. package/dist/modes/interactive/components/chat-session-host-actions.d.ts +7 -2
  168. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  169. package/dist/modes/interactive/components/chat-session-host-actions.js +13 -4
  170. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  171. package/dist/modes/interactive/components/chat-session-host-editor.d.ts +3 -1
  172. package/dist/modes/interactive/components/chat-session-host-editor.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/chat-session-host-editor.js +2 -2
  174. package/dist/modes/interactive/components/chat-session-host-editor.js.map +1 -1
  175. package/dist/modes/interactive/components/chat-session-host-events.d.ts +3 -0
  176. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  177. package/dist/modes/interactive/components/chat-session-host-events.js +5 -4
  178. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  179. package/dist/modes/interactive/components/chat-session-host.d.ts +16 -2
  180. package/dist/modes/interactive/components/chat-session-host.d.ts.map +1 -1
  181. package/dist/modes/interactive/components/chat-session-host.js +31 -4
  182. package/dist/modes/interactive/components/chat-session-host.js.map +1 -1
  183. package/dist/modes/interactive/components/index.d.ts +1 -0
  184. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  185. package/dist/modes/interactive/components/index.js.map +1 -1
  186. package/dist/modes/interactive/components/model-selector.d.ts +0 -1
  187. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  188. package/dist/modes/interactive/components/model-selector.js +23 -45
  189. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  190. package/dist/modes/interactive/interactive-editor-actions.js +2 -1
  191. package/dist/modes/interactive/interactive-editor-actions.js.map +1 -1
  192. package/dist/modes/interactive/interactive-input-handling.js +1 -1
  193. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  194. package/dist/modes/interactive/interactive-mode-surface.d.ts +4 -1
  195. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  196. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  197. package/dist/modes/interactive/interactive-model-routing.js +4 -1
  198. package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
  199. package/dist/modes/interactive/interactive-pause.d.ts +3 -1
  200. package/dist/modes/interactive/interactive-pause.d.ts.map +1 -1
  201. package/dist/modes/interactive/interactive-pause.js +5 -1
  202. package/dist/modes/interactive/interactive-pause.js.map +1 -1
  203. package/dist/modes/interactive/interactive-queueing.js +3 -3
  204. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  205. package/dist/modes/interactive-engine/isolated-runtime.d.ts +1 -0
  206. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  207. package/dist/modes/interactive-engine/isolated-runtime.js +5 -0
  208. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  209. package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
  210. package/dist/modes/rpc/rpc-command-handler.js +1 -0
  211. package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
  212. package/dist/modes/rpc/rpc-types.d.ts +2 -1
  213. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  214. package/dist/modes/rpc/rpc-types.js.map +1 -1
  215. package/docs/index.md +10 -0
  216. package/docs/keybindings.md +1 -1
  217. package/docs/models.md +1 -1
  218. package/docs/quickstart.md +7 -1
  219. package/docs/termux.md +3 -1
  220. package/docs/usage.md +3 -2
  221. package/docs/workflows.md +82 -46
  222. package/npm-shrinkwrap.json +59 -27
  223. package/package.json +3 -3
  224. package/dist/builtin/workflows/src/tui/toast.ts +0 -107
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\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.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\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.js\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\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/** 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\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}\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.ts\").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 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\t_reconnectToAgent(): void;\n\tdispose(): 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_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\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_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(): { 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>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(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\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(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\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(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\n\t_isRetryableError(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\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): Promise<string>;\n\texportToJsonl(outputPath?: string): 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| \"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| \"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| \"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| \"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\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_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: 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_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | 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_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\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_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_asyncJobManager: AsyncJobManager;\n\t_asyncJobManagerSessionId: symbol;\n\t_workflowStageAdmission: 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 {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\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\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\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.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\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.js\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\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/** 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\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}\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.ts\").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\t_reconnectToAgent(): void;\n\tdispose(): 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_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\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_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>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(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\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(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\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(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\n\t_isRetryableError(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\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): Promise<string>;\n\texportToJsonl(outputPath?: string): 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| \"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| \"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| \"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\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_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: 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_compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | 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_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\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_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_asyncJobManager: AsyncJobManager;\n\t_asyncJobManagerSessionId: symbol;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
@@ -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,C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D,CACnE,OAAO,EAAE,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,CAe7G;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,CAmB9F;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,E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AG,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"}
@@ -7,9 +7,10 @@ function protectedMessages(session) {
7
7
  }
8
8
  function appendDurableDisplayCard(session, message, delivery) {
9
9
  const card = { ...message, excludeFromContext: true };
10
+ const admitted = message;
10
11
  // The card and recovery marker share one append, so either both survive a
11
12
  // process exit or neither does.
12
- const intentEntryId = session.sessionManager.appendCustomMessageEntry(card.customType, card.content, card.display, card.details, true, { delivery });
13
+ const intentEntryId = session.sessionManager.appendCustomMessageEntry(card.customType, card.content, card.display, card.details, true, { delivery }, admitted.stageAdmissionKey);
13
14
  session.agent.state.messages.push(card);
14
15
  return { card, intentEntryId };
15
16
  }
@@ -168,9 +169,10 @@ export function persistProtectedStreamingCustomMessage(session, message) {
168
169
  if (index === -1)
169
170
  return false;
170
171
  const entry = pending[index];
172
+ const admitted = message;
171
173
  if (entry.phase !== "consumed-unpersisted" && entry.phase !== "persistence-failed")
172
174
  return true;
173
- session.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details, customMessageExcludesContext(message));
175
+ session.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details, customMessageExcludesContext(message), undefined, admitted.stageAdmissionKey);
174
176
  pending.splice(index, 1);
175
177
  return true;
176
178
  }
@@ -235,7 +237,8 @@ export function prepareProtectedStreamingCustomMessagesForDisposal(session) {
235
237
  throw new Error("Cannot dispose a session with a queued protected reconciliation");
236
238
  }
237
239
  for (const entry of queued) {
238
- session.sessionManager.appendCustomMessageEntry(entry.message.customType, entry.message.content, entry.message.display, entry.message.details, customMessageExcludesContext(entry.message));
240
+ const admitted = entry.message;
241
+ session.sessionManager.appendCustomMessageEntry(entry.message.customType, entry.message.content, entry.message.display, entry.message.details, customMessageExcludesContext(entry.message), undefined, admitted.stageAdmissionKey);
239
242
  removeQueuedProtectedReference(session, entry.message);
240
243
  const index = pending.indexOf(entry);
241
244
  if (index >= 0)
@@ -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,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,CACZ,CAAC;IACF,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC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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 } 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\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);\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\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);\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\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);\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;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;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AC7C,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// 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\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 +1 @@
1
- {"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,EAAwC,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAY5G,oFAAoF;AACpF,wBAAsB,yBAAyB,CAC9C,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,YAAY,EAAE,CAAC,CAyFzB;AAED,mFAAmF;AACnF,wBAAgB,kCAAkC,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CA+B/G;AAED,MAAM,WAAW,8BAA8B;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,wBAAwB,CAAC;CACjC;AAED,eAAO,MAAM,qCAAqC;;;CAGjD,CAAC"}
1
+ {"version":3,"file":"agent-session-post-tool-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,EAAwC,KAAK,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAY5G,oFAAoF;AACpF,wBAAsB,yBAAyB,CAC9C,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,YAAY,EAAE,EACxB,MAAM,CAAC,EAAE,WAAW,GAClB,OAAO,CAAC,YAAY,EAAE,CAAC,CAiGzB;AAED,mFAAmF;AACnF,wBAAgB,kCAAkC,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,YAAY,EAAE,GAAG,YAAY,EAAE,CA+B/G;AAED,MAAM,WAAW,8BAA8B;IAC9C,cAAc,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,wBAAwB,CAAC;CACjC;AAED,eAAO,MAAM,qCAAqC;;;CAGjD,CAAC"}
@@ -34,9 +34,16 @@ export async function _preflightPostToolContext(messages, signal) {
34
34
  signal?.addEventListener("abort", relayAbort, { once: true });
35
35
  if (signal?.aborted)
36
36
  abortController.abort();
37
- this._autoCompactionAbortController = abortController;
38
- this._emit({ type: "compaction_start", reason: "threshold", midTurn: true });
37
+ // Ownership publication and the synchronous `compaction_start` emission live
38
+ // inside the cleanup scope: `_emit` runs subscribers synchronously, so a
39
+ // throwing listener would otherwise leave `_autoCompactionAbortController`
40
+ // and `_compactionReason` set with no `finally` to clear them. The next
41
+ // threshold compaction would then be rejected as already active, and
42
+ // attached clients would keep painting a compaction that never runs.
39
43
  try {
44
+ this._autoCompactionAbortController = abortController;
45
+ this._compactionReason = "threshold";
46
+ this._emit({ type: "compaction_start", reason: "threshold", midTurn: true });
40
47
  const result = await this._applyVerbatimCompaction({
41
48
  resolvePlannerAuth: async (candidate) => {
42
49
  const auth = await this._getRequiredRequestAuth(candidate);
@@ -95,6 +102,8 @@ export async function _preflightPostToolContext(messages, signal) {
95
102
  finally {
96
103
  signal?.removeEventListener("abort", relayAbort);
97
104
  this._autoCompactionAbortController = undefined;
105
+ if (this._compactionReason === "threshold")
106
+ this._compactionReason = undefined;
98
107
  }
99
108
  }
100
109
  /** Gate the transformed message context immediately before provider conversion. */
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-post-tool-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-post-tool-compaction.ts"],"names":[],"mappings":"AAEA,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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,IAAI,CAAC,cAAc,CAAC,SAAS,EAAE,CAAC,CAAC;IAC1G,MAAM,eAAe,GAAG,qBAAqB,CAAC,qBAAqB,CAAC,CAAC,MAAM,CAAC;IAC5E,IAAI,eAAe,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC;QAC9C,MAAM,YAAY,GAAG,gBAAgB,CAAC,eAAe,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;QAC/E,IAAI,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;SACZ,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;KACb,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 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\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 relayAbort = () => abortController.abort();\n\tsignal?.addEventListener(\"abort\", relayAbort, { once: true });\n\tif (signal?.aborted) abortController.abort();\n\tthis._autoCompactionAbortController = abortController;\n\tthis._emit({ type: \"compaction_start\", reason: \"threshold\", midTurn: true });\n\n\ttry {\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\t// Mid-turn: a compaction failure here kills the active turn.\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});\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, the\n\t\t// getter hands back the live internal array. Returning it directly would make the\n\t\t// agent loop's `currentContext.messages` an alias of `agent.state.messages`, and\n\t\t// from the next turn on both writers (`runLoop` and the `message_end` reducer)\n\t\t// would append every message twice — duplicate `tool_result` blocks for one\n\t\t// `tool_use` id, which the provider rejects with an unrecoverable 400.\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...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tthis._autoCompactionAbortController = 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});\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});\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":"AAEA,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;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AAG;IACpD,yBAAyB;IACzB,kCAAkC;CAClC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\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\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 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 `_autoCompactionAbortController`\n\t// and `_compactionReason` set with no `finally` to clear them. The next\n\t// threshold compaction would then be rejected as already active, and\n\t// attached clients would keep painting a compaction that never runs.\n\ttry {\n\t\tthis._autoCompactionAbortController = abortController;\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\t// Mid-turn: a compaction failure here kills the active turn.\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});\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, the\n\t\t// getter hands back the live internal array. Returning it directly would make the\n\t\t// agent loop's `currentContext.messages` an alias of `agent.state.messages`, and\n\t\t// from the next turn on both writers (`runLoop` and the `message_end` reducer)\n\t\t// would append every message twice — duplicate `tool_result` blocks for one\n\t\t// `tool_use` id, which the provider rejects with an unrecoverable 400.\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...(aborted ? {} : { errorMessage }),\n\t\t});\n\t\tthrow new Error(errorMessage, { cause: error });\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", relayAbort);\n\t\tthis._autoCompactionAbortController = 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});\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});\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-tree.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAG9F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAG/D,wBAAgB,cAAc,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAKrE;AAMD;;;;;;;;;;GAUG;AAEH,wBAAsB,YAAY,CACjC,IAAI,EAAE,YAAY,EAClB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;IAAE,SAAS,CAAC,EAAE,OAAO,CAAC;IAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAO,GAC/G,OAAO,CAAC;IAAE,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,YAAY,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAC,CAmM5G;AAED;;GAEG;AAEH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAetG;AAED,wBAAgB,uBAAuB,CACtC,IAAI,EAAE,YA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I,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACtD,MAAM,CASR;AAED;;GAEG;AAEH,eAAO,MAAM,uBAAuB;;;;;CAKnC,CAAC"}
@@ -57,6 +57,8 @@ export async function navigateTree(targetId, options = {}) {
57
57
  };
58
58
  // Set up abort controller for summarization
59
59
  this._branchSummaryAbortController = new AbortController();
60
+ if (this._compactionReason === undefined)
61
+ this._compactionReason = "branchSummary";
60
62
  try {
61
63
  let extensionSummary;
62
64
  let fromExtension = false;
@@ -187,6 +189,8 @@ export async function navigateTree(targetId, options = {}) {
187
189
  }
188
190
  finally {
189
191
  this._branchSummaryAbortController = undefined;
192
+ if (this._compactionReason === "branchSummary")
193
+ this._compactionReason = undefined;
190
194
  }
191
195
  }
192
196
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-tree.js","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG9F,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,MAAM,UAAU,cAAc,CAAqB,IAAY;IAC9D,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,sBAAsB,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,cAAc,EAAE,EAAW,CAAC;IACpG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAClB,KAAK,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC;AAED,4EAA4E;AAC5E,kBAAkB;AAClB,4EAA4E;AAE5E;;;;;;;;;;GAUG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY,CAEjC,QAAgB,EAChB,OAAO,GAAwG,EAAE;IAEjH,+EAA+E;IAC/E,4DAA4D;IAC5D,IAAI,IAAI,CAA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AAK,SAAS;YAAE,SAAS;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QAE5C,MAAM,IAAI,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACjE,IAAI,IAAI,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,uBAAuB,CAEtC,OAAwD;IAExD,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC;IAChD,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,OAAO;aACZ,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,cAAc;IACd,YAAY;IACZ,yBAAyB;IACzB,uBAAuB;CACvB,CAAC","sourcesContent":["import type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { collectEntriesForBranchSummary, generateBranchSummary } from \"./compaction/index.ts\";\nimport type { SessionBeforeTreeResult, TreePreparation } from \"./extensions/index.ts\";\nimport type { BranchSummaryEntry } from \"./session-manager.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nexport function setSessionName(this: AgentSession, name: string): void {\n\tthis.sessionManager.appendSessionInfo(name);\n\tconst event = { type: \"session_info_changed\", name: this.sessionManager.getSessionName() } as const;\n\tthis._emit(event);\n\tvoid this._extensionRunner.emit(event);\n}\n\n// =========================================================================\n// Tree Navigation\n// =========================================================================\n\n/**\n * Navigate to a different node in the session tree.\n * Unlike fork() which creates a new session file, this stays in the same file.\n *\n * @param targetId The entry ID to navigate to\n * @param options.summarize Whether user wants to summarize abandoned branch\n * @param options.customInstructions Custom instructions for summarizer\n * @param options.replaceInstructions If true, customInstructions replaces the default prompt\n * @param options.label Label to attach to the branch summary entry\n * @returns Result with editorText (if user message) and cancelled status\n */\n\nexport async function navigateTree(\n\tthis: AgentSession,\n\ttargetId: string,\n\toptions: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},\n): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {\n\t// Navigating away mid-response would strand the in-flight turn's tool calls on\n\t// the abandoned branch. Callers abort first, then navigate.\n\tif (this.isStreaming) {\n\t\tthrow new Error(\"Wait for the current response to finish before navigating the session tree.\");\n\t}\n\n\tconst oldLeafId = this.sessionManager.getLeafId();\n\n\t// No-op if already at target\n\tif (targetId === oldLeafId) {\n\t\treturn { cancelled: false };\n\t}\n\n\t// Model required for summarization\n\tif (options.summarize && !this.model) {\n\t\tthrow new Error(\"No model available for summarization\");\n\t}\n\n\tconst targetEntry = this.sessionManager.getEntry(targetId);\n\tif (!targetEntry) {\n\t\tthrow new Error(`Entry ${targetId} not found`);\n\t}\n\n\t// Collect entries to summarize (from old leaf to common ancestor)\n\tconst { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(\n\t\tthis.sessionManager,\n\t\toldLeafId,\n\t\ttargetId,\n\t);\n\n\t// Prepare event data - mutable so extensions can override\n\tlet customInstructions = options.customInstructions;\n\tlet replaceInstructions = options.replaceInstructions;\n\tlet label = options.label;\n\n\tconst preparation: TreePreparation = {\n\t\ttargetId,\n\t\toldLeafId,\n\t\tcommonAncestorId,\n\t\tentriesToSummarize,\n\t\tuserWantsSummary: options.summarize ?? false,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\tlabel,\n\t};\n\n\t// Set up abort controller for summarization\n\tthis._branchSummaryAbortController = new AbortController();\n\n\ttry {\n\t\tlet extensionSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromExtension = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._extensionRunner.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_tree\",\n\t\t\t\tpreparation,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t})) as SessionBeforeTreeResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { cancelled: true };\n\t\t\t}\n\n\t\t\tif (result?.summary && options.summarize) {\n\t\t\t\textensionSummary = result.summary;\n\t\t\t\tfromExtension = true;\n\t\t\t}\n\n\t\t\t// Allow extensions to override instructions and label\n\t\t\tif (result?.customInstructions !== undefined) {\n\t\t\t\tcustomInstructions = result.customInstructions;\n\t\t\t}\n\t\t\tif (result?.replaceInstructions !== undefined) {\n\t\t\t\treplaceInstructions = result.replaceInstructions;\n\t\t\t}\n\t\t\tif (result?.label !== undefined) {\n\t\t\t\tlabel = result.label;\n\t\t\t}\n\t\t}\n\n\t\t// Run default summarizer if needed\n\t\tlet summaryText: string | undefined;\n\t\tlet summaryDetails: unknown;\n\t\tlet summaryUsage: import(\"@earendil-works/pi-ai/compat\").Usage | undefined;\n\t\tif (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {\n\t\t\tconst model = this.model!;\n\t\t\tconst { apiKey, headers, baseUrl } = await this._getRequiredRequestAuth(model);\n\t\t\tconst branchSummarySettings = this.settingsManager.getBranchSummarySettings();\n\t\t\tconst result = await generateBranchSummary(entriesToSummarize, {\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tbaseUrl,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t\tcustomInstructions,\n\t\t\t\treplaceInstructions,\n\t\t\t\treserveTokens: branchSummarySettings.reserveTokens,\n\t\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\t\tstreamFn: this.agent.streamFunction,\n\t\t\t\tretry: this.settingsManager.getRetrySettings(),\n\t\t\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"branchSummary\" }),\n\t\t\t});\n\t\t\tif (result.aborted) {\n\t\t\t\treturn { cancelled: true, aborted: true };\n\t\t\t}\n\t\t\tif (result.error) {\n\t\t\t\tthrow new Error(result.error);\n\t\t\t}\n\t\t\tsummaryText = result.summary;\n\t\t\tsummaryUsage = result.usage;\n\t\t\tsummaryDetails = {\n\t\t\t\treadFiles: result.readFiles || [],\n\t\t\t\tmodifiedFiles: result.modifiedFiles || [],\n\t\t\t};\n\t\t} else if (extensionSummary) {\n\t\t\tsummaryText = extensionSummary.summary;\n\t\t\tsummaryDetails = extensionSummary.details;\n\t\t}\n\n\t\t// Determine the new leaf position based on target type\n\t\tlet newLeafId: string | null;\n\t\tlet editorText: string | undefined;\n\n\t\tif (targetEntry.type === \"message\" && targetEntry.message.role === \"user\") {\n\t\t\t// User message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText = this._extractUserMessageText(targetEntry.message.content);\n\t\t} else if (targetEntry.type === \"custom_message\") {\n\t\t\t// Custom message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText =\n\t\t\t\ttypeof targetEntry.content === \"string\"\n\t\t\t\t\t? targetEntry.content\n\t\t\t\t\t: targetEntry.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t} else {\n\t\t\t// Non-user message: leaf = selected node\n\t\t\tnewLeafId = targetId;\n\t\t}\n\n\t\t// Switch leaf (with or without summary)\n\t\t// Summary is attached at the navigation target position (newLeafId), not the old branch\n\t\tlet summaryEntry: BranchSummaryEntry | undefined;\n\t\tif (summaryText) {\n\t\t\t// Create summary at target position (can be null for root)\n\t\t\tconst summaryId = this.sessionManager.branchWithSummary(\n\t\t\t\tnewLeafId,\n\t\t\t\tsummaryText,\n\t\t\t\tsummaryDetails,\n\t\t\t\tfromExtension,\n\t\t\t\tsummaryUsage,\n\t\t\t);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\n\n\t\t\t// Attach label to the summary entry\n\t\t\tif (label) {\n\t\t\t\tthis.sessionManager.appendLabelChange(summaryId, label);\n\t\t\t}\n\t\t} else if (newLeafId === null) {\n\t\t\t// No summary, navigating to root - reset leaf\n\t\t\tthis.sessionManager.resetLeaf();\n\t\t} else {\n\t\t\t// No summary, navigating to non-root\n\t\t\tthis.sessionManager.branch(newLeafId);\n\t\t}\n\n\t\t// Attach label to target entry when not summarizing (no summary entry to label)\n\t\tif (label && !summaryText) {\n\t\t\tthis.sessionManager.appendLabelChange(targetId, label);\n\t\t}\n\n\t\t// Update agent state\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.state.messages = sessionContext.messages;\n\n\t\t// Emit session_tree event\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_tree\",\n\t\t\tnewLeafId: this.sessionManager.getLeafId(),\n\t\t\toldLeafId,\n\t\t\tsummaryEntry,\n\t\t\tfromExtension: summaryText ? fromExtension : undefined,\n\t\t});\n\n\t\t// Emit to custom tools\n\n\t\treturn { editorText, cancelled: false, summaryEntry };\n\t} finally {\n\t\tthis._branchSummaryAbortController = undefined;\n\t}\n}\n\n/**\n * Get all user messages from session for fork selector.\n */\n\nexport function getUserMessagesForForking(this: AgentSession): Array<{ entryId: string; text: string }> {\n\tconst entries = this.sessionManager.getEntries();\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\n\t\tconst text = this._extractUserMessageText(entry.message.content);\n\t\tif (text) {\n\t\t\tresult.push({ entryId: entry.id, text });\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport function _extractUserMessageText(\n\tthis: AgentSession,\n\tcontent: string | Array<{ type: string; text?: string }>,\n): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * Get session statistics.\n */\n\nexport const agentSessionTreeMethods = {\n\tsetSessionName,\n\tnavigateTree,\n\tgetUserMessagesForForking,\n\t_extractUserMessageText,\n};\n"]}
1
+ {"version":3,"file":"agent-session-tree.js","sourceRoot":"","sources":["../../src/core/agent-session-tree.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,8BAA8B,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAG9F,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAE7E,MAAM,UAAU,cAAc,CAAqB,IAAY;IAC9D,IAAI,CAAC,cAAc,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,sBAAsB,EAAE,IAAI,EAAE,IAAI,CAAC,cAAc,CAAC,cAAc,EAAE,EAAW,CAAC;IACpG,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IAClB,KAAK,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACxC,CAAC;AAED,4EAA4E;AAC5E,kBAAkB;AAClB,4EAA4E;AAE5E;;;;;;;;;;GAUG;AAEH,MAAM,CAAC,KAAK,UAAU,YAAY,CAEjC,QAAgB,EAChB,OAAO,GAAwG,EAAE;IAEjH,+EAA+E;IAC/E,4DAA4D;IAC5D,IAAI,IAAI,CAAC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MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,UAAU,EAAE,CAAC;IACjD,MAAM,MAAM,GAA6C,EAAE,CAAC;IAE5D,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS;YAAE,SAAS;QACvC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,MAAM;YAAE,SAAS;QAE5C,MAAM,IAAI,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QACjE,IAAI,IAAI,EAAE,CAAC;YACV,MAAM,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC;IACF,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,uBAAuB,CAEtC,OAAwD;IAExD,IAAI,OAAO,OAAO,KAAK,QAAQ;QAAE,OAAO,OAAO,CAAC;IAChD,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5B,OAAO,OAAO;aACZ,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;aACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;aAClB,IAAI,CAAC,EAAE,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,EAAE,CAAC;AACX,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,cAAc;IACd,YAAY;IACZ,yBAAyB;IACzB,uBAAuB;CACvB,CAAC","sourcesContent":["import type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { collectEntriesForBranchSummary, generateBranchSummary } from \"./compaction/index.ts\";\nimport type { SessionBeforeTreeResult, TreePreparation } from \"./extensions/index.ts\";\nimport type { BranchSummaryEntry } from \"./session-manager.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nexport function setSessionName(this: AgentSession, name: string): void {\n\tthis.sessionManager.appendSessionInfo(name);\n\tconst event = { type: \"session_info_changed\", name: this.sessionManager.getSessionName() } as const;\n\tthis._emit(event);\n\tvoid this._extensionRunner.emit(event);\n}\n\n// =========================================================================\n// Tree Navigation\n// =========================================================================\n\n/**\n * Navigate to a different node in the session tree.\n * Unlike fork() which creates a new session file, this stays in the same file.\n *\n * @param targetId The entry ID to navigate to\n * @param options.summarize Whether user wants to summarize abandoned branch\n * @param options.customInstructions Custom instructions for summarizer\n * @param options.replaceInstructions If true, customInstructions replaces the default prompt\n * @param options.label Label to attach to the branch summary entry\n * @returns Result with editorText (if user message) and cancelled status\n */\n\nexport async function navigateTree(\n\tthis: AgentSession,\n\ttargetId: string,\n\toptions: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},\n): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {\n\t// Navigating away mid-response would strand the in-flight turn's tool calls on\n\t// the abandoned branch. Callers abort first, then navigate.\n\tif (this.isStreaming) {\n\t\tthrow new Error(\"Wait for the current response to finish before navigating the session tree.\");\n\t}\n\n\tconst oldLeafId = this.sessionManager.getLeafId();\n\n\t// No-op if already at target\n\tif (targetId === oldLeafId) {\n\t\treturn { cancelled: false };\n\t}\n\n\t// Model required for summarization\n\tif (options.summarize && !this.model) {\n\t\tthrow new Error(\"No model available for summarization\");\n\t}\n\n\tconst targetEntry = this.sessionManager.getEntry(targetId);\n\tif (!targetEntry) {\n\t\tthrow new Error(`Entry ${targetId} not found`);\n\t}\n\n\t// Collect entries to summarize (from old leaf to common ancestor)\n\tconst { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(\n\t\tthis.sessionManager,\n\t\toldLeafId,\n\t\ttargetId,\n\t);\n\n\t// Prepare event data - mutable so extensions can override\n\tlet customInstructions = options.customInstructions;\n\tlet replaceInstructions = options.replaceInstructions;\n\tlet label = options.label;\n\n\tconst preparation: TreePreparation = {\n\t\ttargetId,\n\t\toldLeafId,\n\t\tcommonAncestorId,\n\t\tentriesToSummarize,\n\t\tuserWantsSummary: options.summarize ?? false,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\tlabel,\n\t};\n\n\t// Set up abort controller for summarization\n\tthis._branchSummaryAbortController = new AbortController();\n\tif (this._compactionReason === undefined) this._compactionReason = \"branchSummary\";\n\n\ttry {\n\t\tlet extensionSummary: { summary: string; details?: unknown } | undefined;\n\t\tlet fromExtension = false;\n\n\t\t// Emit session_before_tree event\n\t\tif (this._extensionRunner.hasHandlers(\"session_before_tree\")) {\n\t\t\tconst result = (await this._extensionRunner.emit({\n\t\t\t\ttype: \"session_before_tree\",\n\t\t\t\tpreparation,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t})) as SessionBeforeTreeResult | undefined;\n\n\t\t\tif (result?.cancel) {\n\t\t\t\treturn { cancelled: true };\n\t\t\t}\n\n\t\t\tif (result?.summary && options.summarize) {\n\t\t\t\textensionSummary = result.summary;\n\t\t\t\tfromExtension = true;\n\t\t\t}\n\n\t\t\t// Allow extensions to override instructions and label\n\t\t\tif (result?.customInstructions !== undefined) {\n\t\t\t\tcustomInstructions = result.customInstructions;\n\t\t\t}\n\t\t\tif (result?.replaceInstructions !== undefined) {\n\t\t\t\treplaceInstructions = result.replaceInstructions;\n\t\t\t}\n\t\t\tif (result?.label !== undefined) {\n\t\t\t\tlabel = result.label;\n\t\t\t}\n\t\t}\n\n\t\t// Run default summarizer if needed\n\t\tlet summaryText: string | undefined;\n\t\tlet summaryDetails: unknown;\n\t\tlet summaryUsage: import(\"@earendil-works/pi-ai/compat\").Usage | undefined;\n\t\tif (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {\n\t\t\tconst model = this.model!;\n\t\t\tconst { apiKey, headers, baseUrl } = await this._getRequiredRequestAuth(model);\n\t\t\tconst branchSummarySettings = this.settingsManager.getBranchSummarySettings();\n\t\t\tconst result = await generateBranchSummary(entriesToSummarize, {\n\t\t\t\tmodel,\n\t\t\t\tapiKey,\n\t\t\t\theaders,\n\t\t\t\tbaseUrl,\n\t\t\t\tsignal: this._branchSummaryAbortController.signal,\n\t\t\t\tcustomInstructions,\n\t\t\t\treplaceInstructions,\n\t\t\t\treserveTokens: branchSummarySettings.reserveTokens,\n\t\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\t\tstreamFn: this.agent.streamFunction,\n\t\t\t\tretry: this.settingsManager.getRetrySettings(),\n\t\t\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"branchSummary\" }),\n\t\t\t});\n\t\t\tif (result.aborted) {\n\t\t\t\treturn { cancelled: true, aborted: true };\n\t\t\t}\n\t\t\tif (result.error) {\n\t\t\t\tthrow new Error(result.error);\n\t\t\t}\n\t\t\tsummaryText = result.summary;\n\t\t\tsummaryUsage = result.usage;\n\t\t\tsummaryDetails = {\n\t\t\t\treadFiles: result.readFiles || [],\n\t\t\t\tmodifiedFiles: result.modifiedFiles || [],\n\t\t\t};\n\t\t} else if (extensionSummary) {\n\t\t\tsummaryText = extensionSummary.summary;\n\t\t\tsummaryDetails = extensionSummary.details;\n\t\t}\n\n\t\t// Determine the new leaf position based on target type\n\t\tlet newLeafId: string | null;\n\t\tlet editorText: string | undefined;\n\n\t\tif (targetEntry.type === \"message\" && targetEntry.message.role === \"user\") {\n\t\t\t// User message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText = this._extractUserMessageText(targetEntry.message.content);\n\t\t} else if (targetEntry.type === \"custom_message\") {\n\t\t\t// Custom message: leaf = parent (null if root), text goes to editor\n\t\t\tnewLeafId = targetEntry.parentId;\n\t\t\teditorText =\n\t\t\t\ttypeof targetEntry.content === \"string\"\n\t\t\t\t\t? targetEntry.content\n\t\t\t\t\t: targetEntry.content\n\t\t\t\t\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t\t\t\t\t.map((c) => c.text)\n\t\t\t\t\t\t\t.join(\"\");\n\t\t} else {\n\t\t\t// Non-user message: leaf = selected node\n\t\t\tnewLeafId = targetId;\n\t\t}\n\n\t\t// Switch leaf (with or without summary)\n\t\t// Summary is attached at the navigation target position (newLeafId), not the old branch\n\t\tlet summaryEntry: BranchSummaryEntry | undefined;\n\t\tif (summaryText) {\n\t\t\t// Create summary at target position (can be null for root)\n\t\t\tconst summaryId = this.sessionManager.branchWithSummary(\n\t\t\t\tnewLeafId,\n\t\t\t\tsummaryText,\n\t\t\t\tsummaryDetails,\n\t\t\t\tfromExtension,\n\t\t\t\tsummaryUsage,\n\t\t\t);\n\t\t\tsummaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;\n\n\t\t\t// Attach label to the summary entry\n\t\t\tif (label) {\n\t\t\t\tthis.sessionManager.appendLabelChange(summaryId, label);\n\t\t\t}\n\t\t} else if (newLeafId === null) {\n\t\t\t// No summary, navigating to root - reset leaf\n\t\t\tthis.sessionManager.resetLeaf();\n\t\t} else {\n\t\t\t// No summary, navigating to non-root\n\t\t\tthis.sessionManager.branch(newLeafId);\n\t\t}\n\n\t\t// Attach label to target entry when not summarizing (no summary entry to label)\n\t\tif (label && !summaryText) {\n\t\t\tthis.sessionManager.appendLabelChange(targetId, label);\n\t\t}\n\n\t\t// Update agent state\n\t\tconst sessionContext = this.sessionManager.buildSessionContext();\n\t\tthis.agent.state.messages = sessionContext.messages;\n\n\t\t// Emit session_tree event\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_tree\",\n\t\t\tnewLeafId: this.sessionManager.getLeafId(),\n\t\t\toldLeafId,\n\t\t\tsummaryEntry,\n\t\t\tfromExtension: summaryText ? fromExtension : undefined,\n\t\t});\n\n\t\t// Emit to custom tools\n\n\t\treturn { editorText, cancelled: false, summaryEntry };\n\t} finally {\n\t\tthis._branchSummaryAbortController = undefined;\n\t\tif (this._compactionReason === \"branchSummary\") this._compactionReason = undefined;\n\t}\n}\n\n/**\n * Get all user messages from session for fork selector.\n */\n\nexport function getUserMessagesForForking(this: AgentSession): Array<{ entryId: string; text: string }> {\n\tconst entries = this.sessionManager.getEntries();\n\tconst result: Array<{ entryId: string; text: string }> = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"message\") continue;\n\t\tif (entry.message.role !== \"user\") continue;\n\n\t\tconst text = this._extractUserMessageText(entry.message.content);\n\t\tif (text) {\n\t\t\tresult.push({ entryId: entry.id, text });\n\t\t}\n\t}\n\n\treturn result;\n}\n\nexport function _extractUserMessageText(\n\tthis: AgentSession,\n\tcontent: string | Array<{ type: string; text?: string }>,\n): string {\n\tif (typeof content === \"string\") return content;\n\tif (Array.isArray(content)) {\n\t\treturn content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\t}\n\treturn \"\";\n}\n\n/**\n * Get session statistics.\n */\n\nexport const agentSessionTreeMethods = {\n\tsetSessionName,\n\tnavigateTree,\n\tgetUserMessagesForForking,\n\t_extractUserMessageText,\n};\n"]}
@@ -8,6 +8,7 @@ import type { ResourceLoader } from "./resource-loader.ts";
8
8
  import type { SessionManager } from "./session-manager.ts";
9
9
  import type { SettingsManager } from "./settings-manager.ts";
10
10
  import type { SourceInfo } from "./source-info.ts";
11
+ export type CompactionReason = "manual" | "threshold" | "overflow" | "branchSummary";
11
12
  export type AgentSessionEvent = AgentEvent | {
12
13
  type: "agent_settled";
13
14
  } | {
@@ -106,6 +107,9 @@ export interface InterruptQueueHold {
106
107
  readonly steering: AgentMessage[];
107
108
  readonly followUp: AgentMessage[];
108
109
  }
110
+ export interface ClearQueueOptions {
111
+ preserveUnprotectedCustomMessages?: boolean;
112
+ }
109
113
  export declare function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[];
110
114
  export declare function normalizeInterruptAbortMessage(value: string | undefined): string | undefined;
111
115
  export declare function isGenericAbortText(value: string): boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-types.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC/G,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,KAAK,EACX,YAAY,EACZ,8BAA8B,EAC9B,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD,MAAM,MAAM,iBAAiB,GAC1B,UAAU,GACV;IAAE,IAAI,EAAE,eAAe,CAAA;CAAE,GACzB;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,KAAK,EAAE,OAAO,sBAAsB,EAAE,YAAY,CAAA;CAAE,GAC9E;IACA,IAAI,EAAE,cAAc,CAAC;IACrB,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,QAAQ,EAAE,SAAS,MAAM,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AAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE;QACP,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,SAAS,EAAE,MAAM,CAAC;QAClB,UAAU,EAAE,MAAM,CAAC;QACnB,KAAK,EAAE,MAAM,CAAC;KACd,CAAC;IACF,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B;AAED,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,cAAc,CAAC;IAC3B,UAAU,EAAE,UAAU,CAAC;CACvB;AAED,eAAO,MAAM,eAAe,EAAE,aAAa,EAAgE,CAAC;AAE5G,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAE5E;AAED,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,CAAC"}
1
+ {"version":3,"file":"agent-session-types.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC/G,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AACtE,OAAO,KAAK,EACX,YAAY,EACZ,8BAA8B,EAC9B,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OA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,CAAC,CAAC,CAAwB,CAAC,IAAI,KAAK,QAAQ;QAC3D,kBAAkB,CAAE,OAAO,CAAC,CAAC,CAAsB,CAAC,IAAI,CAAC,CACzD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,IAAY;IACnD,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;AACjC,CAAC;AAyED,MAAM,CAAC,MAAM,eAAe,GAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAE5G,MAAM,UAAU,4BAA4B,CAAC,OAAsB;IAClE,OAAQ,OAA4D,CAAC,kBAAkB,KAAK,IAAI,CAAC;AAClG,CAAC","sourcesContent":["import type { Agent, AgentEvent, AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| { type: \"agent_settled\" }\n\t| { type: \"entry_appended\"; entry: import(\"./session-manager.ts\").SessionEntry }\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\"; midTurn?: boolean }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: VerbatimCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\tunresolvedOverflow?: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tmidTurn?: boolean;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t| {\n\t\t\ttype: \"summarization_retry_scheduled\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\tdelayMs: number;\n\t\t\terrorMessage: string;\n\t }\n\t| { type: \"summarization_retry_attempt_start\"; source: \"branchSummary\" }\n\t| {\n\t\t\ttype: \"summarization_retry_attempt_start\";\n\t\t\tsource: \"compaction\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t }\n\t| { type: \"summarization_retry_finished\" }\n\t| { type: \"bash_execution_update\"; id?: string; channel: \"stdout\" | \"stderr\"; delta: string }\n\t| { type: \"model_fallback_start\"; from: string; to: string; reason: string; attempt: number }\n\t| { type: \"model_fallback_end\"; success: boolean; from?: string; to?: string; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tfallbackModels?: string[];\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRuntime: ModelRuntime;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface AgentSessionReloadOptions {\n\treason?: \"startup\" | \"reload\";\n\t/** Runs after resources and the extension runtime are rebuilt, immediately before session_start. */\n\tbeforeSessionStart?: () => void | Promise<void>;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}
1
+ {"version":3,"file":"agent-session-types.js","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAiGA,MAAM,UAAU,sBAAsB,CAAC,KAA2C;IACjF,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,MAAM,OAAO,GAAmB,EAAE,CAAC;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,8BAA8B,CAAC,KAAyB;IACvE,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IAC9B,OAAO,OAAO,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC5D,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAa;IAC/C,MAAM,UAAU,GAAG,KAAK;SACtB,IAAI,EAAE;SACN,WAAW,EAAE;SACb,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;IACxB,OAAO,CACN,UAAU,KAAK,mBAAmB;QAClC,UAAU,KAAK,2BAA2B;QAC1C,UAAU,KAAK,qBAAqB;QACpC,UAAU,KAAK,4BAA4B;QAC3C,UAAU,KAAK,6BAA6B,CAC5C,CAAC;AACH,CAAC;AAED,MAAM,UAAU,+BAA+B,CAAC,OAAgB;IAC/D,OAAO,CACN,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;QACtB,OAAO,CAAC,MAAM,KAAK,CAAC;QACpB,OAAO,OAAO,CAAC,CAAC,CAAC,KAAK,QAAQ;QAC9B,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI;QAClB,OAAO,CAAC,CAAC,CAAwB,CAAC,IAAI,KAAK,MAAM;QAClD,OAAQ,OAAO,CAAC,CAAC,CAAwB,CAAC,IAAI,KAAK,QAAQ;QAC3D,kBAAkB,CAAE,OAAO,CAAC,CAAC,CAAsB,CAAC,IAAI,CAAC,CACzD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,IAAY;IACnD,OAAO,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;AACjC,CAAC;AAyED,MAAM,CAAC,MAAM,eAAe,GAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAE5G,MAAM,UAAU,4BAA4B,CAAC,OAAsB;IAClE,OAAQ,OAA4D,CAAC,kBAAkB,KAAK,IAAI,CAAC;AAClG,CAAC","sourcesContent":["import type { Agent, AgentEvent, AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nexport type CompactionReason = \"manual\" | \"threshold\" | \"overflow\" | \"branchSummary\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| { type: \"agent_settled\" }\n\t| { type: \"entry_appended\"; entry: import(\"./session-manager.ts\").SessionEntry }\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\"; midTurn?: boolean }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: VerbatimCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\tunresolvedOverflow?: boolean;\n\t\t\terrorMessage?: string;\n\t\t\tmidTurn?: boolean;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string }\n\t| {\n\t\t\ttype: \"summarization_retry_scheduled\";\n\t\t\tattempt: number;\n\t\t\tmaxAttempts: number;\n\t\t\tdelayMs: number;\n\t\t\terrorMessage: string;\n\t }\n\t| { type: \"summarization_retry_attempt_start\"; source: \"branchSummary\" }\n\t| {\n\t\t\ttype: \"summarization_retry_attempt_start\";\n\t\t\tsource: \"compaction\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t }\n\t| { type: \"summarization_retry_finished\" }\n\t| { type: \"bash_execution_update\"; id?: string; channel: \"stdout\" | \"stderr\"; delta: string }\n\t| { type: \"model_fallback_start\"; from: string; to: string; reason: string; attempt: number }\n\t| { type: \"model_fallback_end\"; success: boolean; from?: string; to?: string; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\nexport interface ClearQueueOptions {\n\tpreserveUnprotectedCustomMessages?: boolean;\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value\n\t\t.trim()\n\t\t.toLowerCase()\n\t\t.replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tfallbackModels?: string[];\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRuntime: ModelRuntime;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface AgentSessionReloadOptions {\n\treason?: \"startup\" | \"reload\";\n\t/** Runs after resources and the extension runtime are rebuilt, immediately before session_start. */\n\tbeforeSessionStart?: () => void | Promise<void>;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}