@bastani/atomic 0.9.38-alpha.9 → 0.9.38

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 (48) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/CHANGELOG.md +10 -0
  6. package/dist/builtin/subagents/package.json +1 -1
  7. package/dist/builtin/web-access/CHANGELOG.md +7 -0
  8. package/dist/builtin/web-access/package.json +1 -1
  9. package/dist/builtin/workflows/CHANGELOG.md +60 -0
  10. package/dist/builtin/workflows/package.json +1 -1
  11. package/dist/builtin/workflows/src/extension/index.bundle.mjs +5 -0
  12. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  13. package/dist/core/agent-session-prompt.js +57 -15
  14. package/dist/core/agent-session-prompt.js.map +1 -1
  15. package/dist/core/queued-input-admission.d.ts +20 -0
  16. package/dist/core/queued-input-admission.d.ts.map +1 -0
  17. package/dist/core/queued-input-admission.js +55 -0
  18. package/dist/core/queued-input-admission.js.map +1 -0
  19. package/dist/extensions/mcp/client/transports/streamable-http.js +9 -8
  20. package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
  21. package/dist/modes/interactive/components/chat-session-host-actions.d.ts +4 -0
  22. package/dist/modes/interactive/components/chat-session-host-actions.d.ts.map +1 -1
  23. package/dist/modes/interactive/components/chat-session-host-actions.js +104 -30
  24. package/dist/modes/interactive/components/chat-session-host-actions.js.map +1 -1
  25. package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
  26. package/dist/modes/interactive/components/chat-session-host-events.js +1 -0
  27. package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
  28. package/dist/modes/interactive/components/chat-session-host-state.d.ts +4 -0
  29. package/dist/modes/interactive/components/chat-session-host-state.d.ts.map +1 -1
  30. package/dist/modes/interactive/components/chat-session-host-state.js +4 -0
  31. package/dist/modes/interactive/components/chat-session-host-state.js.map +1 -1
  32. package/dist/modes/interactive/components/session-selector.js +4 -3
  33. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  34. package/dist/modes/interactive/interactive-input-handling.js +8 -2
  35. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  36. package/dist/modes/interactive/interactive-mode-base.d.ts +4 -0
  37. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  38. package/dist/modes/interactive/interactive-mode-base.js +4 -0
  39. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  40. package/dist/modes/interactive/interactive-process-lifecycle.js +8 -2
  41. package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
  42. package/dist/modes/interactive/interactive-queueing.js +94 -73
  43. package/dist/modes/interactive/interactive-queueing.js.map +1 -1
  44. package/dist/modes/interactive/interactive-session-runtime.js +1 -0
  45. package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
  46. package/docs/usage.md +2 -0
  47. package/npm-shrinkwrap.json +32 -32
  48. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session-prompt.js","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EACN,0BAA0B,EAC1B,4BAA4B,EAC5B,4BAA4B,GAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EACN,iBAAiB,EACjB,wBAAwB,EACxB,eAAe,EACf,iBAAiB,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2B;IAC3B,mBAAmB;IACnB,KAAK;IACL,QAAQ;IACR,eAAe;CACf,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { ImageContent, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptDisposition, PromptOptions, QueuedInputDisposition } from \"./agent-session-types.js\";\nimport {\n\tformatNoApiKeyFoundMessage,\n\tformatNoModelSelectedMessage,\n\tformatUnresolvedModelMessage,\n} from \"./auth-guidance.ts\";\nimport { runCallback } from \"./callback-activity.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport {\n\tassertSessionOpen,\n\tsessionGenerationClosing,\n\tsessionLifetime,\n\tsessionQuitSignal,\n\ttrackSessionWork,\n} from \"./session-lifecycle-work.ts\";\nimport { getSkillCatalog } from \"./skill-catalog.ts\";\n\nconst customPreparations = new WeakMap<AgentSession, Promise<void>>();\n\nexport async function waitForCustomMessagePreparation(session: AgentSession): Promise<void> {\n\tawait customPreparations.get(session);\n}\n\ntype UserMessageDeliveryAction = \"prompt\" | \"steer\" | \"followUp\" | \"handled\";\n\nfunction assistantHasRecoverableOutput(message: AgentMessage): boolean {\n\tif (message.role !== \"assistant\") return false;\n\treturn message.content.some((block) => {\n\t\tif (block.type === \"text\") return block.text.length > 0;\n\t\tif (block.type === \"thinking\") return block.thinking.length > 0;\n\t\treturn true;\n\t});\n}\n\ntype PromptOptionsWithWorkflowDelivery = PromptOptions & {\n\treadonly __workflowDelivery?: {\n\t\treadonly beforeDelivery?: () => void;\n\t\t/** Called only after an idle prompt has synchronously entered the agent turn. */\n\t\treadonly promptStarted?: () => void;\n\t\treadonly delivered?: (action: UserMessageDeliveryAction) => void;\n\t};\n};\n\n/** Dispatch registered extension slash commands without changing the raw queue pause gate. */\nexport async function tryExecuteSessionSlashCommand(\n\tsession: Pick<AgentSession, \"_tryExecuteExtensionCommand\">,\n\ttext: string,\n): Promise<boolean> {\n\tif (!text.startsWith(\"/\")) return false;\n\treturn session._tryExecuteExtensionCommand(text);\n}\n\nasync function _normalizePromptImages(\n\tthis: AgentSession,\n\timages: ImageContent[] | undefined,\n): Promise<{ images: ImageContent[]; hints: string[] }> {\n\tif (!images) return { images: [], hints: [] };\n\n\tconst normalizedImages: ImageContent[] = [];\n\tconst hints: string[] = [];\n\tfor (const image of images) {\n\t\tconst processed = await processImage(Buffer.from(image.data, \"base64\"), image.mimeType, {\n\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\tresizeOptions: this.model?.inputLimits?.images?.resize,\n\t\t});\n\t\tif (!processed.ok) {\n\t\t\thints.push(processed.message);\n\t\t\tcontinue;\n\t\t}\n\t\tnormalizedImages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\thints.push(...processed.hints);\n\t}\n\treturn { images: normalizedImages, hints };\n}\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tif (this._isEmittingAgentSettled) {\n\t\t// A run started by an agent_settled handler waits until every settled handler completes.\n\t\tthis._deferredSettledActions.push(async () => await this.prompt(text, options));\n\t\treturn;\n\t}\n\treturn trackSessionWork(this, () => admittedPrompt.call(this, text, options));\n}\n\nasync function admittedPrompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tif (this._activePromptCount === 0 && !this.isStreaming) this._agentRunAbortRequested = false;\n\tthis._activePromptCount += 1;\n\ttry {\n\t\tawait promptInternal.call(this, text, options);\n\t\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\t\tif (\n\t\t\t!this._disposed &&\n\t\t\t!sessionGenerationClosing.has(this) &&\n\t\t\tthis._activePromptCount === 1 &&\n\t\t\t!this.isStreaming &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\t(this._priorityInterruptPending || boundary?.hasMessageDeliveries())\n\t\t) {\n\t\t\t// A command/input hook may consume the original prompt during preflight.\n\t\t\t// Its owner still owes independently admitted priority input a reply; drain\n\t\t\t// that input without replaying preflight or starting another task prompt.\n\t\t\tawait this._continueQueuedAgentMessages();\n\t\t\tif (this._subagentMessageAdmission) await settleSubagentMessages(this);\n\t\t}\n\t} finally {\n\t\tthis._activePromptCount -= 1;\n\t}\n}\n\nasync function promptInternal(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst assertCurrent = () => {\n\t\tif (this._disposed || lifetime.aborted || sessionGenerationClosing.has(this))\n\t\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t};\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tconst workflowDelivery = (options as PromptOptionsWithWorkflowDelivery | undefined)?.__workflowDelivery;\n\tlet messages: AgentMessage[] | undefined;\n\tlet preparingRun = false;\n\n\ttry {\n\t\t// Authorize workflow delivery before commands or input extensions can perform side effects.\n\t\t// A later terminal transition cannot retroactively reject input accepted at this boundary.\n\t\tworkflowDelivery?.beforeDelivery?.();\n\t\t// Registered slash commands execute without releasing ordinary queued work.\n\t\t// Unknown slash input continues through the normal paused admission path.\n\t\tif (expandPromptTemplates && (await tryExecuteSessionSlashCommand(this, text))) {\n\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\tpreflightResult?.(true, \"handled\");\n\t\t\treturn;\n\t\t}\n\t\tassertCurrent();\n\t\t// Real user input is on its way in, so a summary describing the previous turn is about\n\t\t// to be stale; stop paying for it. Deliberately after the authorization boundary and\n\t\t// the slash-command path, both of which must observe an untouched session. The\n\t\t// generation discards itself via its token/anchor checks either way.\n\t\tthis.abortSessionSummary();\n\t\t// A controlled pause is an admission gate, including the idle gap after\n\t\t// abort settles. Preserve the raw user payload without running input hooks,\n\t\t// compaction, or a provider turn; explicit resume makes it eligible again.\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst delivery = options?.streamingBehavior === \"followUp\" ? \"followUp\" : \"steer\";\n\t\t\tif (delivery === \"followUp\") await this._queueFollowUp(text, options?.images);\n\t\t\telse await this._queueSteer(text, options?.images);\n\t\t\tworkflowDelivery?.delivered?.(delivery);\n\t\t\tpreflightResult?.(true, \"queued\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tassertCurrent();\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\t\tpreflightResult?.(true, \"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option. The run is still\n\t\t// open while agent_before_settle handlers decide on its continuation, so input sent\n\t\t// from that boundary queues for the continuation instead of starting a second run.\n\t\tif (this.isStreaming || this._isPreparingRun || this._isBeforeSettle) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tworkflowDelivery?.delivered?.(options.streamingBehavior);\n\t\t\tpreflightResult?.(true, \"queued\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Close the completed fallback lifecycle before validating credentials for\n\t\t// the next idle prompt. The selected fallback remains the session model.\n\t\tif (typeof this._settleFallbackModelScope === \"function\") await this._settleFallbackModelScope();\n\t\tassertCurrent();\n\t\t// Flush context-only messages deferred until the previous turn's tool results were appended.\n\t\tawait this._flushPendingBashMessages();\n\t\tawait this._flushPendingCustomMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRuntime.hasConfiguredAuth(this.model.provider)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\tthis._isPreparingRun = \"user\";\n\t\tpreparingRun = true;\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t\tassertCurrent();\n\t\t}\n\n\t\t// Emit before_agent_start before normalizing images so extension-driven model\n\t\t// selection determines the resize profile used for the request and history.\n\t\tconst selectedToolsBefore = this._baseSystemPromptOptions.selectedTools ?? [];\n\t\tconst emitted = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\tconst result = emitted ?? { systemPromptOptions: this._baseSystemPromptOptions };\n\t\tassertCurrent();\n\t\tconst nextTools = result.systemPromptOptions.selectedTools ?? selectedToolsBefore;\n\t\tconst handlerEditedTools =\n\t\t\tnextTools.length !== selectedToolsBefore.length ||\n\t\t\tnextTools.some((name, index) => name !== selectedToolsBefore[index]);\n\t\tif (!handlerEditedTools && typeof this.getActiveToolNames === \"function\") {\n\t\t\tresult.systemPromptOptions.selectedTools = this.getActiveToolNames();\n\t\t}\n\n\t\tconst normalized = await _normalizePromptImages.call(this, currentImages);\n\t\tassertCurrent();\n\t\tconst userText = normalized.hints.length > 0 ? `${expandedText}\\n\\n${normalized.hints.join(\"\\n\")}` : expandedText;\n\n\t\t// Build messages only after hooks and image normalization have completed.\n\t\tmessages = [];\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: userText }];\n\t\tuserContent.push(...normalized.images);\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content ?? [],\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);\n\t\tthis._runSystemPromptOptions = result.systemPromptOptions;\n\t\tif (updateMessage) messages.unshift(updateMessage);\n\t} catch (error) {\n\t\tif (preparingRun) this._isPreparingRun = false;\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tassertCurrent();\n\tlet dispatched = false;\n\tconst reportDispatch = (disposition: PromptDisposition) => {\n\t\tif (dispatched) return;\n\t\tdispatched = true;\n\t\tpreflightResult?.(true, disposition);\n\t};\n\tconst turn = this._runAgentPrompt(messages, workflowDelivery?.promptStarted, reportDispatch, true);\n\tworkflowDelivery?.delivered?.(\"prompt\");\n\ttry {\n\t\tawait turn;\n\t} catch (error) {\n\t\tif (!dispatched) {\n\t\t\tdispatched = true;\n\t\t\tpreflightResult?.(false);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function _runAgentPrompt(\n\tthis: AgentSession,\n\tmessages: AgentMessage | AgentMessage[],\n\tpromptStarted?: () => void,\n\treportDispatch?: (disposition: PromptDisposition) => void,\n\tprepared = false,\n\tcustomStarter?: CustomMessage,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tif (owner._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) owner._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\treturn owner._runAgentPrompt(messages, promptStarted, reportDispatch, prepared, customStarter);\n\t}\n\tif (this._isEmittingAgentSettled) {\n\t\tthis._deferredSettledActions.push(\n\t\t\tasync () => await this._runAgentPrompt(messages, promptStarted, reportDispatch, prepared, customStarter),\n\t\t);\n\t\treturn;\n\t}\n\tif (this._activePromptCount === 0 && !this.isStreaming) this._agentRunAbortRequested = false;\n\tconst startingMessages = Array.isArray(messages) ? messages : [messages];\n\tconst customMessage = !prepared\n\t\t? (customStarter ?? startingMessages.find((message) => message.role === \"custom\"))\n\t\t: undefined;\n\tconst ownsPreparation = prepared || customMessage !== undefined;\n\tconst preparation = customMessage ? Promise.withResolvers<void>() : undefined;\n\tif (preparation) {\n\t\tcustomPreparations.set(this, preparation.promise);\n\t\tthis._isPreparingRun = \"custom\";\n\t}\n\tconst releasePreparation = () => {\n\t\tif (preparation && customPreparations.get(this) === preparation.promise) {\n\t\t\tcustomPreparations.delete(this);\n\t\t\tthis._isPreparingRun = false;\n\t\t\tpreparation.resolve();\n\t\t}\n\t};\n\tthis._activePromptCount += 1;\n\ttry {\n\t\tif (this._subagentMessageAdmission) {\n\t\t\tawait this._subagentMessageAdmission.waitForPendingDeliveries();\n\t\t\tif (!this._subagentMessageAdmission.isOpen()) {\n\t\t\t\treportDispatch?.(\"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst pendingPriority = preparePriorityContinuation(this);\n\t\tif (pendingPriority) await pendingPriority;\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tif (this.agent.state.isStreaming || this._queuedMessagesPaused) {\n\t\t\t\treportDispatch?.(\"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this._isPreparingRun) this._agentRunAbortRequested = false;\n\t\t}\n\t\t// An explicit stop may win during input preflight or priority preparation.\n\t\t// Preserve the prepared input without opening a native turn past that gate.\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) this._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\tif (customMessage?.role === \"custom\") {\n\t\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\t\tif (lastAssistant) await this._checkCompaction(lastAssistant, false);\n\t\t\tconst selectedToolsBefore = this._baseSystemPromptOptions.selectedTools ?? [];\n\t\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\t\t\"\",\n\t\t\t\tundefined,\n\t\t\t\tthis._baseSystemPromptOptions,\n\t\t\t\tcustomMessage,\n\t\t\t);\n\t\t\tconst nextTools = result.systemPromptOptions.selectedTools;\n\t\t\tconst handlerEditedTools =\n\t\t\t\tnextTools.length !== selectedToolsBefore.length ||\n\t\t\t\tnextTools.some((name, index) => name !== selectedToolsBefore[index]);\n\t\t\tif (!handlerEditedTools) result.systemPromptOptions.selectedTools = this.getActiveToolNames();\n\t\t\tmessages = [\n\t\t\t\t...startingMessages,\n\t\t\t\t...this._pendingNextTurnMessages,\n\t\t\t\t...result.messages.map((message) => ({\n\t\t\t\t\t...message,\n\t\t\t\t\trole: \"custom\" as const,\n\t\t\t\t\tcontent: message.content ?? [],\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})),\n\t\t\t];\n\t\t\tconst updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);\n\t\t\tthis._runSystemPromptOptions = result.systemPromptOptions;\n\t\t\tif (updateMessage) messages.unshift(updateMessage);\n\t\t}\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) this._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\tif (ownsPreparation) {\n\t\t\tawait this._flushPendingBashMessages();\n\t\t\tawait this._flushPendingCustomMessages();\n\t\t\tthis._isPreparingRun = false;\n\t\t}\n\t\tif (this._disposed || lifetime.aborted || sessionGenerationClosing.has(this))\n\t\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tthis._pendingToolNames.clear();\n\t\treportDispatch?.(\"started\");\n\t\tconst turn = this.agent.prompt(messages);\n\t\treleasePreparation();\n\t\tif (this.isStreaming) promptStarted?.();\n\t\tawait turn;\n\t\tawait this.waitForRetry();\n\t\tif (lifetime.aborted || sessionGenerationClosing.has(this)) return;\n\t\tif (\n\t\t\tthis._agentRunAbortRequested &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\tthis._protectedStreamingCustomMessages?.some((entry) => entry.phase === \"queued\")\n\t\t) {\n\t\t\tthis._agentRunAbortRequested = false;\n\t\t}\n\t\t// Abort still has to answer a queued message already in the transcript.\n\t\t// `_continueQueuedAgentMessages` skips remaining queue drains while abort\n\t\t// is requested; skipping it entirely reintroduces issue #2362.\n\t\tawait this._continueQueuedAgentMessages();\n\t\tif (this._agentRunAbortRequested) return;\n\t\tawait this._awaitPendingPostCompactionContinuation();\n\t\tawait runBeforeSettleContinuations(this);\n\t} finally {\n\t\treleasePreparation();\n\t\tif (ownsPreparation && !preparation) this._isPreparingRun = false;\n\t\tthis._runSystemPromptOptions = undefined;\n\t\tthis._cacheWarmer?.onAgentSettled();\n\t\tawait this._agentEventQueue;\n\t\tawait this._flushPendingCustomMessages();\n\t\tthis._isEmittingAgentSettled = true;\n\t\ttry {\n\t\t\tconst aborted = this._agentRunAbortRequested === true;\n\t\t\tif (typeof this._extensionRunner?.emit === \"function\") {\n\t\t\t\tawait this._extensionRunner.emit({ type: \"agent_settled\", aborted });\n\t\t\t}\n\t\t\tthis._emit?.({ type: \"agent_settled\", aborted });\n\t\t} finally {\n\t\t\tthis._isEmittingAgentSettled = false;\n\t\t}\n\t\tif (this._subagentMessageAdmission) await settleSubagentMessages(this);\n\t\tthis._activePromptCount -= 1;\n\t\t// Runs deferred by agent_settled handlers start only after every settled handler completed.\n\t\t// Guarded because prompt-handshake suites drive this function on a synthetic session.\n\t\tconst deferred = this._deferredSettledActions?.splice(0) ?? [];\n\t\tfor (const action of deferred) await action();\n\t}\n}\n\n/**\n * Give `agent_before_settle` handlers a chance to append entries and request one explicit\n * continuation before the run settles. Each continuation is followed by the same queued\n * and post-compaction drains as the initial run, then the boundary is offered again.\n */\nasync function runBeforeSettleContinuations(session: AgentSession): Promise<void> {\n\t// Guarded because prompt-handshake suites drive this function on a synthetic session.\n\tif (typeof session._extensionRunner?.hasHandlers !== \"function\") return;\n\tif (typeof session._runBeforeSettleBoundary !== \"function\") return;\n\twhile (!session._agentRunAbortRequested) {\n\t\tawait session._agentEventQueue?.catch(() => {});\n\t\tif (!(await session._runBeforeSettleBoundary())) return;\n\t\t// An explicit stop or a paused queue keeps the requested continuation pending.\n\t\tif (session._agentRunAbortRequested || session._queuedMessagesPaused || session._stopAfterTurnBlockedContinuation)\n\t\t\treturn;\n\t\tawait session._runAgentContinue();\n\t\tif (session._agentRunAbortRequested) return;\n\t\tawait session._awaitPendingPostCompactionContinuation();\n\t}\n}\n\nasync function settleSubagentMessages(session: AgentSession): Promise<void> {\n\tconst admission = session._subagentMessageAdmission!;\n\t// A host-requested stop is terminal for a child, like cancellation. Retain\n\t// protected input for persistence without restarting work or spinning on it.\n\tif (session._stopAfterTurnBlockedContinuation) session.pauseQueuedMessages();\n\t// Keep receiving while admitted input is answered. Seal synchronously only\n\t// after both producer commits and native continuations have drained.\n\tdo {\n\t\tawait admission.waitForPendingDeliveries();\n\t\tawait session._continueQueuedAgentMessages();\n\t\tif (session._stopAfterTurnBlockedContinuation) session.pauseQueuedMessages();\n\t} while (admission.hasPendingDeliveries() || (!session._queuedMessagesPaused && session.agent.hasQueuedMessages()));\n\tadmission.seal();\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tif (this._agentRunAbortRequested || sessionGenerationClosing.has(this) || sessionLifetime(this).aborted) return;\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n/** Restore priority input the moment the native loop can poll it again. */\nfunction preparePriorityContinuation(session: AgentSession): Promise<void> | undefined {\n\tconst boundary = session._subagentMessageAdmission ?? session._workflowStageAdmission;\n\t// Explicit SDK interrupts own a native turn and the shared hold. An admitted\n\t// receiver's task must join that owner before checking its priority input;\n\t// otherwise it can settle before the interrupt finalizer restores the queue.\n\tif (boundary && session._pendingInterruptDeliveries > 0) {\n\t\treturn session._interruptDeliveryQueue.then(() => preparePriorityContinuation(session));\n\t}\n\tconst restore = (): void => {\n\t\tif (!session._priorityInterruptPending) return;\n\t\tsession._priorityInterruptPending = false;\n\t\tsession._restoreAndClearActiveInterruptQueueHold();\n\t};\n\t// Keep the idle prompt start synchronous unless a producer commit is still in flight.\n\tif (!boundary?.hasMessageDeliveries()) {\n\t\trestore();\n\t\treturn undefined;\n\t}\n\t// A producer can enqueue an explicit SDK interrupt while this await yields.\n\t// Recheck its ownership before restoring the shared hold.\n\treturn boundary.waitForMessageDeliveries().then(() => preparePriorityContinuation(session));\n}\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst closing = () => this._disposed || lifetime.aborted || sessionGenerationClosing.has(this);\n\tif (closing()) return;\n\tawait this._agentEventQueue;\n\tif (closing()) return;\n\tawait preparePriorityContinuation(this);\n\tif (closing()) return;\n\n\tif (\n\t\t!this._agentRunAbortRequested &&\n\t\t!this._stopAfterTurnBlockedContinuation &&\n\t\t!this._queuedMessagesPaused &&\n\t\tthis.agent.hasQueuedMessages()\n\t) {\n\t\twhile (\n\t\t\t!this._agentRunAbortRequested &&\n\t\t\t!closing() &&\n\t\t\t!this._stopAfterTurnBlockedContinuation &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\tthis.agent.hasQueuedMessages()\n\t\t) {\n\t\t\tawait this.agent.continue();\n\t\t\tawait this.waitForRetry();\n\t\t\tawait this._agentEventQueue;\n\t\t\tawait preparePriorityContinuation(this);\n\t\t}\n\t}\n\tif (this._stopAfterTurnBlockedContinuation) return;\n\tif (closing()) return;\n\n\tawait answerAdmittedQueuedMessage(this);\n}\n\n/**\n * Answer a queued message the agent loop already admitted into the transcript but\n * never replied to.\n *\n * `pauseQueuedMessages()` can only hold entries still sitting in the agent's own\n * steering/follow-up queues. Once the loop has polled a message it lives inside the\n * loop, is pushed into the transcript on the next iteration, and an interrupt at that\n * moment leaves it with a contentless aborted assistant reply. The message is no\n * longer queued and no longer held, so neither the pause release nor the queued\n * continuation above schedules the turn it is waiting for (issue #2362).\n *\n * This is deliberately disjoint from the paused-hold contract: a *held* message is\n * still released without starting a turn, while an *admitted* one gets its reply.\n */\nasync function answerAdmittedQueuedMessage(session: AgentSession): Promise<void> {\n\tconst admitted = session._admittedQueuedMessageAwaitingReply;\n\t// One attempt per admission: clear before continuing so an interrupt of the\n\t// recovery turn ends the sequence instead of restarting it.\n\tsession._admittedQueuedMessageAwaitingReply = undefined;\n\tif (admitted === undefined || session._disposed) return;\n\t// An interrupt delivery already in flight aborts this reply and then starts its\n\t// own turn, so continuing concurrently would reject the caller's prompt() with\n\t// \"Agent is already processing.\" Wait for it on the same boundary the resume\n\t// path uses, then let the checks below re-read the transcript: a delivery that\n\t// started its own turn changes the tail so they decline, while one that only\n\t// joined a paused hold leaves the admitted message still waiting for its reply.\n\tif (session._pendingInterruptDeliveries > 0) {\n\t\tawait session._interruptDeliveryQueue;\n\t\tif (session._disposed) return;\n\t}\n\n\tconst messages = session.agent.state.messages;\n\tlet replyIndex = messages.length - 1;\n\twhile (replyIndex >= 0 && messages[replyIndex]?.role === \"system\") replyIndex--;\n\tconst reply = messages[replyIndex];\n\t// Only an interrupt that produced nothing is recoverable. A partially streamed\n\t// reply already answered the message; restarting it would duplicate output.\n\tif (reply?.role !== \"assistant\" || reply.stopReason !== \"aborted\" || assistantHasRecoverableOutput(reply)) return;\n\tconst message = messages[replyIndex - 1];\n\tif (message?.role !== \"user\" || session._getUserMessageText(message) !== admitted) return;\n\n\t// Omit the empty aborted reply from the model projection so `continue()` resumes\n\t// from the admitted user message. Raw session history keeps it, as the retry paths do.\n\tawait session._omitRecoveryAttempt(reply);\n\t// Publish this turn before it starts. It begins after the pause abort boundary\n\t// resolves, so a submission that only waited for that boundary would race it\n\t// and be rejected by the streaming guard while the queue is still paused.\n\tconst recovery = Promise.resolve().then(async () => {\n\t\tawait session.agent.continue();\n\t\tawait session.waitForRetry();\n\t\tawait session._agentEventQueue;\n\t});\n\tconst settled = recovery.catch(() => undefined);\n\tsession._admittedRecoveryTurn = settled;\n\ttry {\n\t\tawait recovery;\n\t} finally {\n\t\tif (session._admittedRecoveryTurn === settled) session._admittedRecoveryTurn = undefined;\n\t}\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst quitSignal = sessionQuitSignal(this);\n\tconst command = this._extensionRunner.getCommand(commandName, quitSignal);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait runCallback(\n\t\t\t{ kind: \"extension.hook\", name: `command:${commandName}`, sourcePath: command.sourceInfo.path },\n\t\t\t() => command.handler(args, ctx),\n\t\t);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (quitSignal.aborted) return true;\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst selector = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\tconst resolution = getSkillCatalog(this.resourceLoader).resolve(selector);\n\tif (!resolution.ok) {\n\t\tif (selector.includes(\"@\")) {\n\t\t\tthis._extensionRunner.emitError({\n\t\t\t\textensionPath: `skill:${selector}`,\n\t\t\t\tevent: \"skill_expansion\",\n\t\t\t\terror: resolution.message,\n\t\t\t});\n\t\t}\n\t\treturn text;\n\t}\n\tconst { skill, id } = resolution.candidate;\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${selector}\" location=\"${skill.filePath}\" candidate=\"${id}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\nasync function queueUserInput(\n\tsession: AgentSession,\n\ttext: string,\n\timages: ImageContent[] | undefined,\n\tbehavior: \"steer\" | \"followUp\",\n\tsource: NonNullable<PromptOptions[\"source\"]>,\n): Promise<QueuedInputDisposition> {\n\tassertSessionOpen(session);\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return queueUserInput(owner, text, images, behavior, source);\n\treturn trackSessionWork(session, () => admittedQueueUserInput(session, text, images, behavior, source));\n}\n\nasync function admittedQueueUserInput(\n\tsession: AgentSession,\n\ttext: string,\n\timages: ImageContent[] | undefined,\n\tbehavior: \"steer\" | \"followUp\",\n\tsource: NonNullable<PromptOptions[\"source\"]>,\n): Promise<QueuedInputDisposition> {\n\tconst lifetime = sessionLifetime(session);\n\tif (text.startsWith(\"/\")) session._throwIfExtensionCommand(text);\n\tif (session._extensionRunner?.hasHandlers(\"input\")) {\n\t\tconst result = await session._extensionRunner.emitInput(\n\t\t\ttext,\n\t\t\timages,\n\t\t\tsource,\n\t\t\tsession.isStreaming ? behavior : undefined,\n\t\t);\n\t\tassertSessionOpen(session);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tif (result.action === \"handled\") return \"handled\";\n\t\tif (result.action === \"transform\") {\n\t\t\ttext = result.text;\n\t\t\timages = result.images ?? images;\n\t\t}\n\t}\n\tconst expandedText = expandPromptTemplate(session._expandSkillCommand(text), [...session.promptTemplates]);\n\tif (behavior === \"steer\") await session._queueSteer(expandedText, images);\n\telse await session._queueFollowUp(expandedText, images);\n\treturn \"queued\";\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\toptions?: Pick<PromptOptions, \"source\">,\n): Promise<QueuedInputDisposition> {\n\treturn queueUserInput(this, text, images, \"steer\", options?.source ?? \"interactive\");\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\toptions?: Pick<PromptOptions, \"source\">,\n): Promise<QueuedInputDisposition> {\n\treturn queueUserInput(this, text, images, \"followUp\", options?.source ?? \"interactive\");\n}\n\n/**\n * Send a user message and trigger a turn.\n *\n * By default the text is delivered literally: extension commands are not\n * dispatched and skill commands / prompt templates are not expanded. Set\n * `expandPromptTemplates: true` to dispatch a registered extension or skill\n * command (or expand a prompt template) instead of sending the raw text —\n * with that option the message may DISPATCH a command rather than be sent.\n *\n * @param content User message content (string or content array)\n * @param options.deliverAs Delivery mode when streaming: \"steer\" or \"followUp\"\n * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.\n */\nexport async function sendUserMessage(\n\tthis: AgentSession,\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: {\n\t\tdeliverAs?: \"steer\" | \"followUp\";\n\t\texpandPromptTemplates?: boolean;\n\t\t__workflowDelivery?: PromptOptionsWithWorkflowDelivery[\"__workflowDelivery\"];\n\t},\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// prompt() owns command dispatch and template expansion; the default (false)\n\t// keeps every pre-existing caller sending literally. The private delivery hook\n\t// lets workflow routing report and gate the branch selected after asynchronous\n\t// input/compaction extension preflight.\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: options?.expandPromptTemplates ?? false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t\t__workflowDelivery: options?.__workflowDelivery,\n\t} as PromptOptionsWithWorkflowDelivery);\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
1
+ {"version":3,"file":"agent-session-prompt.js","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAGvC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,OAAO,EACN,0BAA0B,EAC1B,4BAA4B,EAC5B,4BAA4B,GAC5B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAEN,2BAA2B,EAC3B,YAAY,EACZ,mBAAmB,GACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACN,iBAAiB,EACjB,wBAAwB,EACxB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,oB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MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YACnB,CAAC;QACF,CAAC;QACD,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5B,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;YAAE,MAAM,GAAG,SAAS,CAAC;IAC7C,CAAC;IAED,6EAA6E;IAC7E,+EAA+E;IAC/E,+EAA+E;IAC/E,wCAAwC;IACxC,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE;QACvB,qBAAqB,EAAE,OAAO,EAAE,qBAAqB,IAAI,KAAK;QAC9D,iBAAiB,EAAE,OAAO,EAAE,SAAS;QACrC,MAAM;QACN,MAAM,EAAE,WAAW;QACnB,kBAAkB,EAAE,OAAO,EAAE,kBAAkB;KACV,CAAC,CAAC;AACzC,CAAC;AAED;;;;GAIG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,MAAM;IACN,eAAe;IACf,iBAAiB;IACjB,4BAA4B;IAC5B,2BAA2B;IAC3B,mBAAmB;IACnB,KAAK;IACL,QAAQ;IACR,eAAe;CACf,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { ImageContent, TextContent } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport { processImage } from \"../utils/image-process.ts\";\nimport { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptDisposition, PromptOptions, QueuedInputDisposition } from \"./agent-session-types.js\";\nimport {\n\tformatNoApiKeyFoundMessage,\n\tformatNoModelSelectedMessage,\n\tformatUnresolvedModelMessage,\n} from \"./auth-guidance.ts\";\nimport { runCallback } from \"./callback-activity.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport {\n\ttype QueuedInputAdmission,\n\treserveQueuedInputAdmission,\n\trunInputHook,\n\tUNORDERED_ADMISSION,\n} from \"./queued-input-admission.ts\";\nimport {\n\tassertSessionOpen,\n\tsessionGenerationClosing,\n\tsessionLifetime,\n\tsessionQuitSignal,\n\ttrackSessionWork,\n} from \"./session-lifecycle-work.ts\";\nimport { getSkillCatalog } from \"./skill-catalog.ts\";\n\nconst customPreparations = new WeakMap<AgentSession, Promise<void>>();\n\nexport async function waitForCustomMessagePreparation(session: AgentSession): Promise<void> {\n\tawait customPreparations.get(session);\n}\n\ntype UserMessageDeliveryAction = \"prompt\" | \"steer\" | \"followUp\" | \"handled\";\n\nfunction assistantHasRecoverableOutput(message: AgentMessage): boolean {\n\tif (message.role !== \"assistant\") return false;\n\treturn message.content.some((block) => {\n\t\tif (block.type === \"text\") return block.text.length > 0;\n\t\tif (block.type === \"thinking\") return block.thinking.length > 0;\n\t\treturn true;\n\t});\n}\n\ntype PromptOptionsWithWorkflowDelivery = PromptOptions & {\n\treadonly __workflowDelivery?: {\n\t\treadonly beforeDelivery?: () => void;\n\t\t/** Called only after an idle prompt has synchronously entered the agent turn. */\n\t\treadonly promptStarted?: () => void;\n\t\treadonly delivered?: (action: UserMessageDeliveryAction) => void;\n\t};\n};\n\n/** Dispatch registered extension slash commands without changing the raw queue pause gate. */\nexport async function tryExecuteSessionSlashCommand(\n\tsession: Pick<AgentSession, \"_tryExecuteExtensionCommand\">,\n\ttext: string,\n): Promise<boolean> {\n\tif (!text.startsWith(\"/\")) return false;\n\treturn session._tryExecuteExtensionCommand(text);\n}\n\nasync function _normalizePromptImages(\n\tthis: AgentSession,\n\timages: ImageContent[] | undefined,\n): Promise<{ images: ImageContent[]; hints: string[] }> {\n\tif (!images) return { images: [], hints: [] };\n\n\tconst normalizedImages: ImageContent[] = [];\n\tconst hints: string[] = [];\n\tfor (const image of images) {\n\t\tconst processed = await processImage(Buffer.from(image.data, \"base64\"), image.mimeType, {\n\t\t\tautoResizeImages: this.settingsManager.getImageAutoResize(),\n\t\t\tresizeOptions: this.model?.inputLimits?.images?.resize,\n\t\t});\n\t\tif (!processed.ok) {\n\t\t\thints.push(processed.message);\n\t\t\tcontinue;\n\t\t}\n\t\tnormalizedImages.push({ type: \"image\", data: processed.data, mimeType: processed.mimeType });\n\t\thints.push(...processed.hints);\n\t}\n\treturn { images: normalizedImages, hints };\n}\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tif (this._isEmittingAgentSettled) {\n\t\t// A run started by an agent_settled handler waits until every settled handler completes.\n\t\tthis._deferredSettledActions.push(async () => await this.prompt(text, options));\n\t\treturn;\n\t}\n\treturn trackSessionWork(this, () => admittedPrompt.call(this, text, options));\n}\n\nasync function admittedPrompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tif (this._activePromptCount === 0 && !this.isStreaming) this._agentRunAbortRequested = false;\n\tthis._activePromptCount += 1;\n\ttry {\n\t\tawait promptInternal.call(this, text, options);\n\t\tconst boundary = this._subagentMessageAdmission ?? this._workflowStageAdmission;\n\t\tif (\n\t\t\t!this._disposed &&\n\t\t\t!sessionGenerationClosing.has(this) &&\n\t\t\tthis._activePromptCount === 1 &&\n\t\t\t!this.isStreaming &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\t(this._priorityInterruptPending || boundary?.hasMessageDeliveries())\n\t\t) {\n\t\t\t// A command/input hook may consume the original prompt during preflight.\n\t\t\t// Its owner still owes independently admitted priority input a reply; drain\n\t\t\t// that input without replaying preflight or starting another task prompt.\n\t\t\tawait this._continueQueuedAgentMessages();\n\t\t\tif (this._subagentMessageAdmission) await settleSubagentMessages(this);\n\t\t}\n\t} finally {\n\t\tthis._activePromptCount -= 1;\n\t}\n}\n\nfunction isExtensionCommand(session: AgentSession, text: string): boolean {\n\tif (!text.startsWith(\"/\")) return false;\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\treturn session._extensionRunner?.getCommand(commandName) !== undefined;\n}\n\n/** Extension commands and extension-delivered messages run immediately rather than in submission order. */\nfunction reserveAdmissionForQueuedPrompt(\n\tsession: AgentSession,\n\ttext: string,\n\toptions: PromptOptions | undefined,\n): QueuedInputAdmission {\n\tconst lane = options?.streamingBehavior;\n\tif (lane === undefined || options?.source === \"extension\") return UNORDERED_ADMISSION;\n\tif ((options?.expandPromptTemplates ?? true) && isExtensionCommand(session, text)) return UNORDERED_ADMISSION;\n\treturn reserveQueuedInputAdmission(session, lane, sessionLifetime(session));\n}\n\nasync function promptInternal(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst assertCurrent = () => {\n\t\tif (this._disposed || lifetime.aborted || sessionGenerationClosing.has(this))\n\t\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t};\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.prompt(text, options);\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tconst workflowDelivery = (options as PromptOptionsWithWorkflowDelivery | undefined)?.__workflowDelivery;\n\tlet messages: AgentMessage[] | undefined;\n\tlet preparingRun = false;\n\tconst admission = reserveAdmissionForQueuedPrompt(this, text, options);\n\n\ttry {\n\t\t// Authorize workflow delivery before commands or input extensions can perform side effects.\n\t\t// A later terminal transition cannot retroactively reject input accepted at this boundary.\n\t\tworkflowDelivery?.beforeDelivery?.();\n\t\t// Registered slash commands execute without releasing ordinary queued work.\n\t\t// Unknown slash input continues through the normal paused admission path.\n\t\tif (expandPromptTemplates && (await tryExecuteSessionSlashCommand(this, text))) {\n\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\tpreflightResult?.(true, \"handled\");\n\t\t\treturn;\n\t\t}\n\t\tassertCurrent();\n\t\t// Real user input is on its way in, so a summary describing the previous turn is about\n\t\t// to be stale; stop paying for it. Deliberately after the authorization boundary and\n\t\t// the slash-command path, both of which must observe an untouched session. The\n\t\t// generation discards itself via its token/anchor checks either way.\n\t\tthis.abortSessionSummary();\n\t\t// A controlled pause is an admission gate, including the idle gap after\n\t\t// abort settles. Preserve the raw user payload without running input hooks,\n\t\t// compaction, or a provider turn; explicit resume makes it eligible again.\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst delivery = options?.streamingBehavior === \"followUp\" ? \"followUp\" : \"steer\";\n\t\t\tconst earlierAdmissions = admission.waitForTurn();\n\t\t\tif (earlierAdmissions) await earlierAdmissions;\n\t\t\tassertCurrent();\n\t\t\tif (delivery === \"followUp\") await this._queueFollowUp(text, options?.images);\n\t\t\telse await this._queueSteer(text, options?.images);\n\t\t\tworkflowDelivery?.delivered?.(delivery);\n\t\t\tpreflightResult?.(true, \"queued\");\n\t\t\treturn;\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await runInputHook(() =>\n\t\t\t\tthis._extensionRunner.emitInput(\n\t\t\t\t\tcurrentText,\n\t\t\t\t\tcurrentImages,\n\t\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t\t),\n\t\t\t);\n\t\t\tassertCurrent();\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tworkflowDelivery?.delivered?.(\"handled\");\n\t\t\t\tpreflightResult?.(true, \"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\tconst earlierAdmissions = admission.waitForTurn();\n\t\tif (earlierAdmissions) await earlierAdmissions;\n\t\tassertCurrent();\n\n\t\t// If streaming, queue via steer() or followUp() based on option. The run is still\n\t\t// open while agent_before_settle handlers decide on its continuation, so input sent\n\t\t// from that boundary queues for the continuation instead of starting a second run.\n\t\tif (this.isStreaming || this._isPreparingRun || this._isBeforeSettle) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tworkflowDelivery?.delivered?.(options.streamingBehavior);\n\t\t\tpreflightResult?.(true, \"queued\");\n\t\t\treturn;\n\t\t}\n\t\tadmission.release();\n\n\t\t// Close the completed fallback lifecycle before validating credentials for\n\t\t// the next idle prompt. The selected fallback remains the session model.\n\t\tif (typeof this._settleFallbackModelScope === \"function\") await this._settleFallbackModelScope();\n\t\tassertCurrent();\n\t\t// Flush context-only messages deferred until the previous turn's tool results were appended.\n\t\tawait this._flushPendingBashMessages();\n\t\tawait this._flushPendingCustomMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRuntime.hasConfiguredAuth(this.model.provider)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\tthis._isPreparingRun = \"user\";\n\t\tpreparingRun = true;\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t\tassertCurrent();\n\t\t}\n\n\t\t// Emit before_agent_start before normalizing images so extension-driven model\n\t\t// selection determines the resize profile used for the request and history.\n\t\tconst selectedToolsBefore = this._baseSystemPromptOptions.selectedTools ?? [];\n\t\tconst emitted = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\tconst result = emitted ?? { systemPromptOptions: this._baseSystemPromptOptions };\n\t\tassertCurrent();\n\t\tconst nextTools = result.systemPromptOptions.selectedTools ?? selectedToolsBefore;\n\t\tconst handlerEditedTools =\n\t\t\tnextTools.length !== selectedToolsBefore.length ||\n\t\t\tnextTools.some((name, index) => name !== selectedToolsBefore[index]);\n\t\tif (!handlerEditedTools && typeof this.getActiveToolNames === \"function\") {\n\t\t\tresult.systemPromptOptions.selectedTools = this.getActiveToolNames();\n\t\t}\n\n\t\tconst normalized = await _normalizePromptImages.call(this, currentImages);\n\t\tassertCurrent();\n\t\tconst userText = normalized.hints.length > 0 ? `${expandedText}\\n\\n${normalized.hints.join(\"\\n\")}` : expandedText;\n\n\t\t// Build messages only after hooks and image normalization have completed.\n\t\tmessages = [];\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: userText }];\n\t\tuserContent.push(...normalized.images);\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content ?? [],\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tconst updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);\n\t\tthis._runSystemPromptOptions = result.systemPromptOptions;\n\t\tif (updateMessage) messages.unshift(updateMessage);\n\t} catch (error) {\n\t\tif (preparingRun) this._isPreparingRun = false;\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t} finally {\n\t\tadmission.release();\n\t}\n\n\tassertCurrent();\n\tlet dispatched = false;\n\tconst reportDispatch = (disposition: PromptDisposition) => {\n\t\tif (dispatched) return;\n\t\tdispatched = true;\n\t\tpreflightResult?.(true, disposition);\n\t};\n\tconst turn = this._runAgentPrompt(messages, workflowDelivery?.promptStarted, reportDispatch, true);\n\tworkflowDelivery?.delivered?.(\"prompt\");\n\ttry {\n\t\tawait turn;\n\t} catch (error) {\n\t\tif (!dispatched) {\n\t\t\tdispatched = true;\n\t\t\tpreflightResult?.(false);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport async function _runAgentPrompt(\n\tthis: AgentSession,\n\tmessages: AgentMessage | AgentMessage[],\n\tpromptStarted?: () => void,\n\treportDispatch?: (disposition: PromptDisposition) => void,\n\tprepared = false,\n\tcustomStarter?: CustomMessage,\n): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\tif (owner._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) owner._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\treturn owner._runAgentPrompt(messages, promptStarted, reportDispatch, prepared, customStarter);\n\t}\n\tif (this._isEmittingAgentSettled) {\n\t\tthis._deferredSettledActions.push(\n\t\t\tasync () => await this._runAgentPrompt(messages, promptStarted, reportDispatch, prepared, customStarter),\n\t\t);\n\t\treturn;\n\t}\n\tif (this._activePromptCount === 0 && !this.isStreaming) this._agentRunAbortRequested = false;\n\tconst startingMessages = Array.isArray(messages) ? messages : [messages];\n\tconst customMessage = !prepared\n\t\t? (customStarter ?? startingMessages.find((message) => message.role === \"custom\"))\n\t\t: undefined;\n\tconst ownsPreparation = prepared || customMessage !== undefined;\n\tconst preparation = customMessage ? Promise.withResolvers<void>() : undefined;\n\tif (preparation) {\n\t\tcustomPreparations.set(this, preparation.promise);\n\t\tthis._isPreparingRun = \"custom\";\n\t}\n\tconst releasePreparation = () => {\n\t\tif (preparation && customPreparations.get(this) === preparation.promise) {\n\t\t\tcustomPreparations.delete(this);\n\t\t\tthis._isPreparingRun = false;\n\t\t\tpreparation.resolve();\n\t\t}\n\t};\n\tthis._activePromptCount += 1;\n\ttry {\n\t\tif (this._subagentMessageAdmission) {\n\t\t\tawait this._subagentMessageAdmission.waitForPendingDeliveries();\n\t\t\tif (!this._subagentMessageAdmission.isOpen()) {\n\t\t\t\treportDispatch?.(\"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tconst pendingPriority = preparePriorityContinuation(this);\n\t\tif (pendingPriority) await pendingPriority;\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tif (this.agent.state.isStreaming || this._queuedMessagesPaused) {\n\t\t\t\treportDispatch?.(\"handled\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this._isPreparingRun) this._agentRunAbortRequested = false;\n\t\t}\n\t\t// An explicit stop may win during input preflight or priority preparation.\n\t\t// Preserve the prepared input without opening a native turn past that gate.\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) this._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\tif (customMessage?.role === \"custom\") {\n\t\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\t\tif (lastAssistant) await this._checkCompaction(lastAssistant, false);\n\t\t\tconst selectedToolsBefore = this._baseSystemPromptOptions.selectedTools ?? [];\n\t\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\t\t\"\",\n\t\t\t\tundefined,\n\t\t\t\tthis._baseSystemPromptOptions,\n\t\t\t\tcustomMessage,\n\t\t\t);\n\t\t\tconst nextTools = result.systemPromptOptions.selectedTools;\n\t\t\tconst handlerEditedTools =\n\t\t\t\tnextTools.length !== selectedToolsBefore.length ||\n\t\t\t\tnextTools.some((name, index) => name !== selectedToolsBefore[index]);\n\t\t\tif (!handlerEditedTools) result.systemPromptOptions.selectedTools = this.getActiveToolNames();\n\t\t\tmessages = [\n\t\t\t\t...startingMessages,\n\t\t\t\t...this._pendingNextTurnMessages,\n\t\t\t\t...result.messages.map((message) => ({\n\t\t\t\t\t...message,\n\t\t\t\t\trole: \"custom\" as const,\n\t\t\t\t\tcontent: message.content ?? [],\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t})),\n\t\t\t];\n\t\t\tconst updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);\n\t\t\tthis._runSystemPromptOptions = result.systemPromptOptions;\n\t\t\tif (updateMessage) messages.unshift(updateMessage);\n\t\t}\n\t\tif (this._queuedMessagesPaused) {\n\t\t\tconst items = Array.isArray(messages) ? messages : [messages];\n\t\t\tfor (const message of items) this._queueAgentMessage(message, \"steer\");\n\t\t\treportDispatch?.(\"queued\");\n\t\t\treturn;\n\t\t}\n\t\tif (ownsPreparation) {\n\t\t\tawait this._flushPendingBashMessages();\n\t\t\tawait this._flushPendingCustomMessages();\n\t\t\tthis._isPreparingRun = false;\n\t\t}\n\t\tif (this._disposed || lifetime.aborted || sessionGenerationClosing.has(this))\n\t\t\tthrow Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tthis._pendingToolNames.clear();\n\t\treportDispatch?.(\"started\");\n\t\tconst turn = this.agent.prompt(messages);\n\t\treleasePreparation();\n\t\tif (this.isStreaming) promptStarted?.();\n\t\tawait turn;\n\t\tawait this.waitForRetry();\n\t\tif (lifetime.aborted || sessionGenerationClosing.has(this)) return;\n\t\tif (\n\t\t\tthis._agentRunAbortRequested &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\tthis._protectedStreamingCustomMessages?.some((entry) => entry.phase === \"queued\")\n\t\t) {\n\t\t\tthis._agentRunAbortRequested = false;\n\t\t}\n\t\t// Abort still has to answer a queued message already in the transcript.\n\t\t// `_continueQueuedAgentMessages` skips remaining queue drains while abort\n\t\t// is requested; skipping it entirely reintroduces issue #2362.\n\t\tawait this._continueQueuedAgentMessages();\n\t\tif (this._agentRunAbortRequested) return;\n\t\tawait this._awaitPendingPostCompactionContinuation();\n\t\tawait runBeforeSettleContinuations(this);\n\t} finally {\n\t\treleasePreparation();\n\t\tif (ownsPreparation && !preparation) this._isPreparingRun = false;\n\t\tthis._runSystemPromptOptions = undefined;\n\t\tthis._cacheWarmer?.onAgentSettled();\n\t\tawait this._agentEventQueue;\n\t\tawait this._flushPendingCustomMessages();\n\t\tthis._isEmittingAgentSettled = true;\n\t\ttry {\n\t\t\tconst aborted = this._agentRunAbortRequested === true;\n\t\t\tif (typeof this._extensionRunner?.emit === \"function\") {\n\t\t\t\tawait this._extensionRunner.emit({ type: \"agent_settled\", aborted });\n\t\t\t}\n\t\t\tthis._emit?.({ type: \"agent_settled\", aborted });\n\t\t} finally {\n\t\t\tthis._isEmittingAgentSettled = false;\n\t\t}\n\t\tif (this._subagentMessageAdmission) await settleSubagentMessages(this);\n\t\tthis._activePromptCount -= 1;\n\t\t// Runs deferred by agent_settled handlers start only after every settled handler completed.\n\t\t// Guarded because prompt-handshake suites drive this function on a synthetic session.\n\t\tconst deferred = this._deferredSettledActions?.splice(0) ?? [];\n\t\tfor (const action of deferred) await action();\n\t}\n}\n\n/**\n * Give `agent_before_settle` handlers a chance to append entries and request one explicit\n * continuation before the run settles. Each continuation is followed by the same queued\n * and post-compaction drains as the initial run, then the boundary is offered again.\n */\nasync function runBeforeSettleContinuations(session: AgentSession): Promise<void> {\n\t// Guarded because prompt-handshake suites drive this function on a synthetic session.\n\tif (typeof session._extensionRunner?.hasHandlers !== \"function\") return;\n\tif (typeof session._runBeforeSettleBoundary !== \"function\") return;\n\twhile (!session._agentRunAbortRequested) {\n\t\tawait session._agentEventQueue?.catch(() => {});\n\t\tif (!(await session._runBeforeSettleBoundary())) return;\n\t\t// An explicit stop or a paused queue keeps the requested continuation pending.\n\t\tif (session._agentRunAbortRequested || session._queuedMessagesPaused || session._stopAfterTurnBlockedContinuation)\n\t\t\treturn;\n\t\tawait session._runAgentContinue();\n\t\tif (session._agentRunAbortRequested) return;\n\t\tawait session._awaitPendingPostCompactionContinuation();\n\t}\n}\n\nasync function settleSubagentMessages(session: AgentSession): Promise<void> {\n\tconst admission = session._subagentMessageAdmission!;\n\t// A host-requested stop is terminal for a child, like cancellation. Retain\n\t// protected input for persistence without restarting work or spinning on it.\n\tif (session._stopAfterTurnBlockedContinuation) session.pauseQueuedMessages();\n\t// Keep receiving while admitted input is answered. Seal synchronously only\n\t// after both producer commits and native continuations have drained.\n\tdo {\n\t\tawait admission.waitForPendingDeliveries();\n\t\tawait session._continueQueuedAgentMessages();\n\t\tif (session._stopAfterTurnBlockedContinuation) session.pauseQueuedMessages();\n\t} while (admission.hasPendingDeliveries() || (!session._queuedMessagesPaused && session.agent.hasQueuedMessages()));\n\tadmission.seal();\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tif (this._agentRunAbortRequested || sessionGenerationClosing.has(this) || sessionLifetime(this).aborted) return;\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n/** Restore priority input the moment the native loop can poll it again. */\nfunction preparePriorityContinuation(session: AgentSession): Promise<void> | undefined {\n\tconst boundary = session._subagentMessageAdmission ?? session._workflowStageAdmission;\n\t// Explicit SDK interrupts own a native turn and the shared hold. An admitted\n\t// receiver's task must join that owner before checking its priority input;\n\t// otherwise it can settle before the interrupt finalizer restores the queue.\n\tif (boundary && session._pendingInterruptDeliveries > 0) {\n\t\treturn session._interruptDeliveryQueue.then(() => preparePriorityContinuation(session));\n\t}\n\tconst restore = (): void => {\n\t\tif (!session._priorityInterruptPending) return;\n\t\tsession._priorityInterruptPending = false;\n\t\tsession._restoreAndClearActiveInterruptQueueHold();\n\t};\n\t// Keep the idle prompt start synchronous unless a producer commit is still in flight.\n\tif (!boundary?.hasMessageDeliveries()) {\n\t\trestore();\n\t\treturn undefined;\n\t}\n\t// A producer can enqueue an explicit SDK interrupt while this await yields.\n\t// Recheck its ownership before restoring the shared hold.\n\treturn boundary.waitForMessageDeliveries().then(() => preparePriorityContinuation(session));\n}\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tconst lifetime = sessionLifetime(this);\n\tconst closing = () => this._disposed || lifetime.aborted || sessionGenerationClosing.has(this);\n\tif (closing()) return;\n\tawait this._agentEventQueue;\n\tif (closing()) return;\n\tawait preparePriorityContinuation(this);\n\tif (closing()) return;\n\n\tif (\n\t\t!this._agentRunAbortRequested &&\n\t\t!this._stopAfterTurnBlockedContinuation &&\n\t\t!this._queuedMessagesPaused &&\n\t\tthis.agent.hasQueuedMessages()\n\t) {\n\t\twhile (\n\t\t\t!this._agentRunAbortRequested &&\n\t\t\t!closing() &&\n\t\t\t!this._stopAfterTurnBlockedContinuation &&\n\t\t\t!this._queuedMessagesPaused &&\n\t\t\tthis.agent.hasQueuedMessages()\n\t\t) {\n\t\t\tawait this.agent.continue();\n\t\t\tawait this.waitForRetry();\n\t\t\tawait this._agentEventQueue;\n\t\t\tawait preparePriorityContinuation(this);\n\t\t}\n\t}\n\tif (this._stopAfterTurnBlockedContinuation) return;\n\tif (closing()) return;\n\n\tawait answerAdmittedQueuedMessage(this);\n}\n\n/**\n * Answer a queued message the agent loop already admitted into the transcript but\n * never replied to.\n *\n * `pauseQueuedMessages()` can only hold entries still sitting in the agent's own\n * steering/follow-up queues. Once the loop has polled a message it lives inside the\n * loop, is pushed into the transcript on the next iteration, and an interrupt at that\n * moment leaves it with a contentless aborted assistant reply. The message is no\n * longer queued and no longer held, so neither the pause release nor the queued\n * continuation above schedules the turn it is waiting for (issue #2362).\n *\n * This is deliberately disjoint from the paused-hold contract: a *held* message is\n * still released without starting a turn, while an *admitted* one gets its reply.\n */\nasync function answerAdmittedQueuedMessage(session: AgentSession): Promise<void> {\n\tconst admitted = session._admittedQueuedMessageAwaitingReply;\n\t// One attempt per admission: clear before continuing so an interrupt of the\n\t// recovery turn ends the sequence instead of restarting it.\n\tsession._admittedQueuedMessageAwaitingReply = undefined;\n\tif (admitted === undefined || session._disposed) return;\n\t// An interrupt delivery already in flight aborts this reply and then starts its\n\t// own turn, so continuing concurrently would reject the caller's prompt() with\n\t// \"Agent is already processing.\" Wait for it on the same boundary the resume\n\t// path uses, then let the checks below re-read the transcript: a delivery that\n\t// started its own turn changes the tail so they decline, while one that only\n\t// joined a paused hold leaves the admitted message still waiting for its reply.\n\tif (session._pendingInterruptDeliveries > 0) {\n\t\tawait session._interruptDeliveryQueue;\n\t\tif (session._disposed) return;\n\t}\n\n\tconst messages = session.agent.state.messages;\n\tlet replyIndex = messages.length - 1;\n\twhile (replyIndex >= 0 && messages[replyIndex]?.role === \"system\") replyIndex--;\n\tconst reply = messages[replyIndex];\n\t// Only an interrupt that produced nothing is recoverable. A partially streamed\n\t// reply already answered the message; restarting it would duplicate output.\n\tif (reply?.role !== \"assistant\" || reply.stopReason !== \"aborted\" || assistantHasRecoverableOutput(reply)) return;\n\tconst message = messages[replyIndex - 1];\n\tif (message?.role !== \"user\" || session._getUserMessageText(message) !== admitted) return;\n\n\t// Omit the empty aborted reply from the model projection so `continue()` resumes\n\t// from the admitted user message. Raw session history keeps it, as the retry paths do.\n\tawait session._omitRecoveryAttempt(reply);\n\t// Publish this turn before it starts. It begins after the pause abort boundary\n\t// resolves, so a submission that only waited for that boundary would race it\n\t// and be rejected by the streaming guard while the queue is still paused.\n\tconst recovery = Promise.resolve().then(async () => {\n\t\tawait session.agent.continue();\n\t\tawait session.waitForRetry();\n\t\tawait session._agentEventQueue;\n\t});\n\tconst settled = recovery.catch(() => undefined);\n\tsession._admittedRecoveryTurn = settled;\n\ttry {\n\t\tawait recovery;\n\t} finally {\n\t\tif (session._admittedRecoveryTurn === settled) session._admittedRecoveryTurn = undefined;\n\t}\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst quitSignal = sessionQuitSignal(this);\n\tconst command = this._extensionRunner.getCommand(commandName, quitSignal);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait runCallback(\n\t\t\t{ kind: \"extension.hook\", name: `command:${commandName}`, sourcePath: command.sourceInfo.path },\n\t\t\t() => command.handler(args, ctx),\n\t\t);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (quitSignal.aborted) return true;\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst selector = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\tconst resolution = getSkillCatalog(this.resourceLoader).resolve(selector);\n\tif (!resolution.ok) {\n\t\tif (selector.includes(\"@\")) {\n\t\t\tthis._extensionRunner.emitError({\n\t\t\t\textensionPath: `skill:${selector}`,\n\t\t\t\tevent: \"skill_expansion\",\n\t\t\t\terror: resolution.message,\n\t\t\t});\n\t\t}\n\t\treturn text;\n\t}\n\tconst { skill, id } = resolution.candidate;\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${selector}\" location=\"${skill.filePath}\" candidate=\"${id}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\nasync function queueUserInput(\n\tsession: AgentSession,\n\ttext: string,\n\timages: ImageContent[] | undefined,\n\tbehavior: \"steer\" | \"followUp\",\n\tsource: NonNullable<PromptOptions[\"source\"]>,\n): Promise<QueuedInputDisposition> {\n\tassertSessionOpen(session);\n\tconst owner = resolveWorkflowStageDeliveryTarget(session);\n\tif (owner !== session) return queueUserInput(owner, text, images, behavior, source);\n\treturn trackSessionWork(session, () => admittedQueueUserInput(session, text, images, behavior, source));\n}\n\nasync function admittedQueueUserInput(\n\tsession: AgentSession,\n\ttext: string,\n\timages: ImageContent[] | undefined,\n\tbehavior: \"steer\" | \"followUp\",\n\tsource: NonNullable<PromptOptions[\"source\"]>,\n): Promise<QueuedInputDisposition> {\n\tconst lifetime = sessionLifetime(session);\n\tif (text.startsWith(\"/\")) session._throwIfExtensionCommand(text);\n\tconst admission =\n\t\tsource === \"extension\" ? UNORDERED_ADMISSION : reserveQueuedInputAdmission(session, behavior, lifetime);\n\ttry {\n\t\tif (session._extensionRunner?.hasHandlers(\"input\")) {\n\t\t\tconst result = await runInputHook(() =>\n\t\t\t\tsession._extensionRunner.emitInput(text, images, source, session.isStreaming ? behavior : undefined),\n\t\t\t);\n\t\t\tassertSessionOpen(session);\n\t\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\t\tif (result.action === \"handled\") return \"handled\";\n\t\t\tif (result.action === \"transform\") {\n\t\t\t\ttext = result.text;\n\t\t\t\timages = result.images ?? images;\n\t\t\t}\n\t\t}\n\t\tconst expandedText = expandPromptTemplate(session._expandSkillCommand(text), [...session.promptTemplates]);\n\t\tconst earlierAdmissions = admission.waitForTurn();\n\t\tif (earlierAdmissions) await earlierAdmissions;\n\t\tassertSessionOpen(session);\n\t\tif (lifetime.aborted) throw Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" });\n\t\tif (behavior === \"steer\") await session._queueSteer(expandedText, images);\n\t\telse await session._queueFollowUp(expandedText, images);\n\t\treturn \"queued\";\n\t} finally {\n\t\tadmission.release();\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\toptions?: Pick<PromptOptions, \"source\">,\n): Promise<QueuedInputDisposition> {\n\treturn queueUserInput(this, text, images, \"steer\", options?.source ?? \"interactive\");\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(\n\tthis: AgentSession,\n\ttext: string,\n\timages?: ImageContent[],\n\toptions?: Pick<PromptOptions, \"source\">,\n): Promise<QueuedInputDisposition> {\n\treturn queueUserInput(this, text, images, \"followUp\", options?.source ?? \"interactive\");\n}\n\n/**\n * Send a user message and trigger a turn.\n *\n * By default the text is delivered literally: extension commands are not\n * dispatched and skill commands / prompt templates are not expanded. Set\n * `expandPromptTemplates: true` to dispatch a registered extension or skill\n * command (or expand a prompt template) instead of sending the raw text —\n * with that option the message may DISPATCH a command rather than be sent.\n *\n * @param content User message content (string or content array)\n * @param options.deliverAs Delivery mode when streaming: \"steer\" or \"followUp\"\n * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.\n */\nexport async function sendUserMessage(\n\tthis: AgentSession,\n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: {\n\t\tdeliverAs?: \"steer\" | \"followUp\";\n\t\texpandPromptTemplates?: boolean;\n\t\t__workflowDelivery?: PromptOptionsWithWorkflowDelivery[\"__workflowDelivery\"];\n\t},\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// prompt() owns command dispatch and template expansion; the default (false)\n\t// keeps every pre-existing caller sending literally. The private delivery hook\n\t// lets workflow routing report and gate the branch selected after asynchronous\n\t// input/compaction extension preflight.\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: options?.expandPromptTemplates ?? false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t\t__workflowDelivery: options?.__workflowDelivery,\n\t} as PromptOptionsWithWorkflowDelivery);\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
@@ -0,0 +1,20 @@
1
+ export type QueuedInputLane = "steer" | "followUp";
2
+ export interface QueuedInputAdmission {
3
+ /**
4
+ * Resolves once every earlier admission in the same lane has queued, been handled, or failed,
5
+ * or once the session lifetime ends, so closing or reloading the session never waits on a hook
6
+ * that is itself waiting on that close. Returns undefined when nothing is pending, so an
7
+ * uncontended submission queues without yielding.
8
+ */
9
+ waitForTurn(): Promise<void> | undefined;
10
+ release(): void;
11
+ }
12
+ export declare const UNORDERED_ADMISSION: QueuedInputAdmission;
13
+ /**
14
+ * Reserve a place in a session's steer or follow-up lane at submission time, so asynchronous
15
+ * input hooks cannot reorder same-lane messages. Input submitted from inside an input hook
16
+ * is not ordered: the hook may await it, and it would otherwise wait for the hook's own message.
17
+ */
18
+ export declare function reserveQueuedInputAdmission(session: object, lane: QueuedInputLane, lifetime: AbortSignal): QueuedInputAdmission;
19
+ export declare function runInputHook<T>(hook: () => Promise<T>): Promise<T>;
20
+ //# sourceMappingURL=queued-input-admission.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queued-input-admission.d.ts","sourceRoot":"","sources":["../../src/core/queued-input-admission.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,eAAe,GAAG,OAAO,GAAG,UAAU,CAAC;AAEnD,MAAM,WAAW,oBAAoB;IACpC;;;;;OAKG;IACH,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC;IACzC,OAAO,IAAI,IAAI,CAAC;CAChB;AAkBD,eAAO,MAAM,mBAAmB,EAAE,oBAGjC,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,2BAA2B,CAC1C,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,eAAe,EACrB,QAAQ,EAAE,WAAW,GACnB,oBAAoB,CA4BtB;AAED,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAElE"}
@@ -0,0 +1,55 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ function createReservation() {
3
+ let release;
4
+ const released = new Promise((resolve) => {
5
+ release = resolve;
6
+ });
7
+ return { released, release };
8
+ }
9
+ const lanes = new WeakMap();
10
+ const insideInputHook = new AsyncLocalStorage();
11
+ export const UNORDERED_ADMISSION = {
12
+ waitForTurn: () => undefined,
13
+ release: () => undefined,
14
+ };
15
+ /**
16
+ * Reserve a place in a session's steer or follow-up lane at submission time, so asynchronous
17
+ * input hooks cannot reorder same-lane messages. Input submitted from inside an input hook
18
+ * is not ordered: the hook may await it, and it would otherwise wait for the hook's own message.
19
+ */
20
+ export function reserveQueuedInputAdmission(session, lane, lifetime) {
21
+ if (insideInputHook.getStore())
22
+ return UNORDERED_ADMISSION;
23
+ const sessionLanes = lanes.get(session) ?? new Map();
24
+ lanes.set(session, sessionLanes);
25
+ const reservations = sessionLanes.get(lane) ?? [];
26
+ sessionLanes.set(lane, reservations);
27
+ const reservation = createReservation();
28
+ reservations.push(reservation);
29
+ return {
30
+ waitForTurn() {
31
+ const earlier = reservations.slice(0, reservations.indexOf(reservation));
32
+ if (earlier.length === 0 || lifetime.aborted)
33
+ return undefined;
34
+ return new Promise((resolve) => {
35
+ const finish = () => {
36
+ lifetime.removeEventListener("abort", finish);
37
+ resolve();
38
+ };
39
+ lifetime.addEventListener("abort", finish, { once: true });
40
+ void Promise.all(earlier.map((entry) => entry.released)).then(finish);
41
+ });
42
+ },
43
+ release() {
44
+ const index = reservations.indexOf(reservation);
45
+ if (index === -1)
46
+ return;
47
+ reservations.splice(index, 1);
48
+ reservation.release();
49
+ },
50
+ };
51
+ }
52
+ export function runInputHook(hook) {
53
+ return insideInputHook.run(true, hook);
54
+ }
55
+ //# sourceMappingURL=queued-input-admission.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queued-input-admission.js","sourceRoot":"","sources":["../../src/core/queued-input-admission.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAoBrD,SAAS,iBAAiB;IACzB,IAAI,OAAoB,CAAC;IACzB,MAAM,QAAQ,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAA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mB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;oBAC9C,OAAO,EAAE,CAAC;gBACX,CAAC,CAAC;gBACF,QAAQ,CAAC,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;gBAC3D,KAAK,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACvE,CAAC,CAAC,CAAC;QACJ,CAAC;QACD,OAAO;YACN,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;YAChD,IAAI,KAAK,KAAK,CAAC,CAAC;gBAAE,OAAO;YACzB,YAAY,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YAC9B,WAAW,CAAC,OAAO,EAAE,CAAC;QACvB,CAAC;KACD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,YAAY,CAAI,IAAsB;IACrD,OAAO,eAAe,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\n\nexport type QueuedInputLane = \"steer\" | \"followUp\";\n\nexport interface QueuedInputAdmission {\n\t/**\n\t * Resolves once every earlier admission in the same lane has queued, been handled, or failed,\n\t * or once the session lifetime ends, so closing or reloading the session never waits on a hook\n\t * that is itself waiting on that close. Returns undefined when nothing is pending, so an\n\t * uncontended submission queues without yielding.\n\t */\n\twaitForTurn(): Promise<void> | undefined;\n\trelease(): void;\n}\n\ninterface Reservation {\n\treadonly released: Promise<void>;\n\treadonly release: () => void;\n}\n\nfunction createReservation(): Reservation {\n\tlet release!: () => void;\n\tconst released = new Promise<void>((resolve) => {\n\t\trelease = resolve;\n\t});\n\treturn { released, release };\n}\n\nconst lanes = new WeakMap<object, Map<QueuedInputLane, Reservation[]>>();\nconst insideInputHook = new AsyncLocalStorage<true>();\n\nexport const UNORDERED_ADMISSION: QueuedInputAdmission = {\n\twaitForTurn: () => undefined,\n\trelease: () => undefined,\n};\n\n/**\n * Reserve a place in a session's steer or follow-up lane at submission time, so asynchronous\n * input hooks cannot reorder same-lane messages. Input submitted from inside an input hook\n * is not ordered: the hook may await it, and it would otherwise wait for the hook's own message.\n */\nexport function reserveQueuedInputAdmission(\n\tsession: object,\n\tlane: QueuedInputLane,\n\tlifetime: AbortSignal,\n): QueuedInputAdmission {\n\tif (insideInputHook.getStore()) return UNORDERED_ADMISSION;\n\tconst sessionLanes = lanes.get(session) ?? new Map<QueuedInputLane, Reservation[]>();\n\tlanes.set(session, sessionLanes);\n\tconst reservations = sessionLanes.get(lane) ?? [];\n\tsessionLanes.set(lane, reservations);\n\tconst reservation = createReservation();\n\treservations.push(reservation);\n\treturn {\n\t\twaitForTurn() {\n\t\t\tconst earlier = reservations.slice(0, reservations.indexOf(reservation));\n\t\t\tif (earlier.length === 0 || lifetime.aborted) return undefined;\n\t\t\treturn new Promise<void>((resolve) => {\n\t\t\t\tconst finish = () => {\n\t\t\t\t\tlifetime.removeEventListener(\"abort\", finish);\n\t\t\t\t\tresolve();\n\t\t\t\t};\n\t\t\t\tlifetime.addEventListener(\"abort\", finish, { once: true });\n\t\t\t\tvoid Promise.all(earlier.map((entry) => entry.released)).then(finish);\n\t\t\t});\n\t\t},\n\t\trelease() {\n\t\t\tconst index = reservations.indexOf(reservation);\n\t\t\tif (index === -1) return;\n\t\t\treservations.splice(index, 1);\n\t\t\treservation.release();\n\t\t},\n\t};\n}\n\nexport function runInputHook<T>(hook: () => Promise<T>): Promise<T> {\n\treturn insideInputHook.run(true, hook);\n}\n"]}
@@ -278,13 +278,14 @@ export class StreamableHttpTransport extends TransportEvents {
278
278
  await consumeSseStream(stream, {
279
279
  maxEventBytes: this.options.maxMessageBytes ?? DEFAULT_MAX_MESSAGE_BYTES,
280
280
  onId: (id) => {
281
+ if (id !== cursor.lastEventId)
282
+ cursor.advanced = true;
281
283
  cursor.lastEventId = id;
282
284
  },
283
285
  onRetry: (delayMs) => {
284
286
  cursor.retryMs = delayMs;
285
287
  },
286
288
  onEvent: (event) => {
287
- cursor.received = true;
288
289
  // Events without data prime resumption; other event types are not JSON-RPC.
289
290
  if (!event.data.trim() || (event.event !== undefined && event.event !== "message"))
290
291
  return;
@@ -307,7 +308,7 @@ export class StreamableHttpTransport extends TransportEvents {
307
308
  * server may close response streams at will. Otherwise only this request fails.
308
309
  */
309
310
  async consumeResponseStream(body, requestId) {
310
- const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
311
+ const cursor = { lastEventId: undefined, retryMs: undefined, advanced: false };
311
312
  let answered = false;
312
313
  const onMessage = (message) => {
313
314
  if (isJsonRpcResponse(message) && message.id === requestId)
@@ -331,9 +332,9 @@ export class StreamableHttpTransport extends TransportEvents {
331
332
  break;
332
333
  if (cursor.lastEventId === undefined || attempt >= this.maxRetries())
333
334
  break;
334
- if (cursor.received)
335
+ if (cursor.advanced)
335
336
  attempt = 0;
336
- cursor.received = false;
337
+ cursor.advanced = false;
337
338
  if (!(await this.sleep(this.reconnectDelay(attempt++, cursor.retryMs))))
338
339
  return;
339
340
  try {
@@ -363,7 +364,7 @@ export class StreamableHttpTransport extends TransportEvents {
363
364
  }
364
365
  /** Keep the server-to-client stream open, reconnecting with backoff when it drops. */
365
366
  async runGetStream() {
366
- const cursor = { lastEventId: undefined, retryMs: undefined, received: false };
367
+ const cursor = { lastEventId: undefined, retryMs: undefined, advanced: false };
367
368
  for (let attempt = 0; !this.closed;) {
368
369
  try {
369
370
  const stream = await this.openSseStream(cursor.lastEventId);
@@ -372,8 +373,8 @@ export class StreamableHttpTransport extends TransportEvents {
372
373
  return;
373
374
  const openedAt = Date.now();
374
375
  await this.consumeSse(stream, cursor);
375
- // A stream that stayed up for a while counts as healthy, even if it was idle.
376
- if (cursor.received || Date.now() - openedAt > this.maxDelay())
376
+ // Resumable progress, or a stream that stayed up for a while, counts as healthy.
377
+ if (cursor.advanced || Date.now() - openedAt > this.maxDelay())
377
378
  attempt = 0;
378
379
  }
379
380
  catch (error) {
@@ -384,7 +385,7 @@ export class StreamableHttpTransport extends TransportEvents {
384
385
  return;
385
386
  }
386
387
  }
387
- cursor.received = false;
388
+ cursor.advanced = false;
388
389
  if (attempt >= this.maxRetries()) {
389
390
  this.emitError(new Error("MCP server-to-client stream dropped and could not be reopened"));
390
391
  return;