@bastani/atomic 0.9.28-alpha.2 → 0.9.28-alpha.3

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 (158) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/native-client-licenses/NOTICE +2 -0
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/CHANGELOG.md +11 -0
  8. package/dist/builtin/workflows/package.json +1 -1
  9. package/dist/builtin/workflows/src/extension/index.bundle.mjs +14733 -14704
  10. package/dist/cli/args.d.ts.map +1 -1
  11. package/dist/cli/args.js +8 -1
  12. package/dist/cli/args.js.map +1 -1
  13. package/dist/config.d.ts +2 -1
  14. package/dist/config.d.ts.map +1 -1
  15. package/dist/config.js +4 -2
  16. package/dist/config.js.map +1 -1
  17. package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
  18. package/dist/core/agent-session-extension-bindings.js +3 -2
  19. package/dist/core/agent-session-extension-bindings.js.map +1 -1
  20. package/dist/core/agent-session-methods.d.ts +1 -0
  21. package/dist/core/agent-session-methods.d.ts.map +1 -1
  22. package/dist/core/agent-session-methods.js.map +1 -1
  23. package/dist/core/agent-session-tool-registry.js.map +1 -1
  24. package/dist/core/agent-session-types.d.ts +1 -0
  25. package/dist/core/agent-session-types.d.ts.map +1 -1
  26. package/dist/core/agent-session-types.js.map +1 -1
  27. package/dist/core/agent-session.d.ts +1 -0
  28. package/dist/core/agent-session.d.ts.map +1 -1
  29. package/dist/core/agent-session.js +6 -1
  30. package/dist/core/agent-session.js.map +1 -1
  31. package/dist/core/bash-executor.d.ts.map +1 -1
  32. package/dist/core/bash-executor.js +22 -4
  33. package/dist/core/bash-executor.js.map +1 -1
  34. package/dist/core/child-session-options.d.ts.map +1 -1
  35. package/dist/core/child-session-options.js +17 -2
  36. package/dist/core/child-session-options.js.map +1 -1
  37. package/dist/core/extensions/loader-virtual-modules.d.ts +3 -4
  38. package/dist/core/extensions/loader-virtual-modules.d.ts.map +1 -1
  39. package/dist/core/extensions/loader-virtual-modules.js +14 -9
  40. package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
  41. package/dist/core/extensions/tool-events.d.ts +1 -1
  42. package/dist/core/extensions/tool-events.js.map +1 -1
  43. package/dist/core/extensions/ts-source-specifiers.d.ts +18 -0
  44. package/dist/core/extensions/ts-source-specifiers.d.ts.map +1 -0
  45. package/dist/core/extensions/ts-source-specifiers.js +142 -0
  46. package/dist/core/extensions/ts-source-specifiers.js.map +1 -0
  47. package/dist/core/sdk-exports.d.ts +2 -2
  48. package/dist/core/sdk-exports.js.map +1 -1
  49. package/dist/core/sdk-types.d.ts +3 -0
  50. package/dist/core/sdk-types.d.ts.map +1 -1
  51. package/dist/core/sdk-types.js.map +1 -1
  52. package/dist/core/sdk.d.ts.map +1 -1
  53. package/dist/core/sdk.js +17 -8
  54. package/dist/core/sdk.js.map +1 -1
  55. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  56. package/dist/core/settings-manager-core.js.map +1 -1
  57. package/dist/core/settings-merge.d.ts +3 -0
  58. package/dist/core/settings-merge.d.ts.map +1 -1
  59. package/dist/core/settings-merge.js +18 -4
  60. package/dist/core/settings-merge.js.map +1 -1
  61. package/dist/core/settings-storage.js.map +1 -1
  62. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  63. package/dist/extensions/codemode/execute.js +14 -1
  64. package/dist/extensions/codemode/execute.js.map +1 -1
  65. package/dist/extensions/codemode/tool.js +2 -2
  66. package/dist/extensions/codemode/tool.js.map +1 -1
  67. package/dist/extensions/llama/provider.d.ts.map +1 -1
  68. package/dist/extensions/llama/provider.js +19 -8
  69. package/dist/extensions/llama/provider.js.map +1 -1
  70. package/dist/extensions/mcp/cli.js +18 -24
  71. package/dist/extensions/mcp/cli.js.map +1 -1
  72. package/dist/extensions/mcp/client/auth-provider.d.ts +4 -0
  73. package/dist/extensions/mcp/client/auth-provider.d.ts.map +1 -1
  74. package/dist/extensions/mcp/client/auth-provider.js.map +1 -1
  75. package/dist/extensions/mcp/client/oauth/discovery.d.ts +3 -0
  76. package/dist/extensions/mcp/client/oauth/discovery.d.ts.map +1 -1
  77. package/dist/extensions/mcp/client/oauth/discovery.js +8 -5
  78. package/dist/extensions/mcp/client/oauth/discovery.js.map +1 -1
  79. package/dist/extensions/mcp/client/oauth/flow.d.ts +4 -0
  80. package/dist/extensions/mcp/client/oauth/flow.d.ts.map +1 -1
  81. package/dist/extensions/mcp/client/oauth/flow.js +12 -2
  82. package/dist/extensions/mcp/client/oauth/flow.js.map +1 -1
  83. package/dist/extensions/mcp/client/transports/streamable-http.d.ts +3 -0
  84. package/dist/extensions/mcp/client/transports/streamable-http.d.ts.map +1 -1
  85. package/dist/extensions/mcp/client/transports/streamable-http.js +17 -14
  86. package/dist/extensions/mcp/client/transports/streamable-http.js.map +1 -1
  87. package/dist/extensions/mcp/index.d.ts.map +1 -1
  88. package/dist/extensions/mcp/index.js +150 -72
  89. package/dist/extensions/mcp/index.js.map +1 -1
  90. package/dist/extensions/mcp/oauth.d.ts +5 -3
  91. package/dist/extensions/mcp/oauth.d.ts.map +1 -1
  92. package/dist/extensions/mcp/oauth.js +36 -10
  93. package/dist/extensions/mcp/oauth.js.map +1 -1
  94. package/dist/extensions/mcp/ui.d.ts +3 -3
  95. package/dist/extensions/mcp/ui.d.ts.map +1 -1
  96. package/dist/extensions/mcp/ui.js +10 -2
  97. package/dist/extensions/mcp/ui.js.map +1 -1
  98. package/dist/index.d.ts +1 -1
  99. package/dist/index.js.map +1 -1
  100. package/dist/main-deferred-startup.d.ts +1 -0
  101. package/dist/main-deferred-startup.d.ts.map +1 -1
  102. package/dist/main-deferred-startup.js +9 -21
  103. package/dist/main-deferred-startup.js.map +1 -1
  104. package/dist/main.d.ts.map +1 -1
  105. package/dist/main.js +8 -6
  106. package/dist/main.js.map +1 -1
  107. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  108. package/dist/modes/interactive/interactive-input-handling.d.ts.map +1 -1
  109. package/dist/modes/interactive/interactive-input-handling.js +1 -47
  110. package/dist/modes/interactive/interactive-input-handling.js.map +1 -1
  111. package/dist/modes/interactive/interactive-mode-base.d.ts +0 -1
  112. package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
  113. package/dist/modes/interactive/interactive-mode-base.js +0 -1
  114. package/dist/modes/interactive/interactive-mode-base.js.map +1 -1
  115. package/dist/modes/interactive/interactive-mode-surface.d.ts +0 -1
  116. package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
  117. package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
  118. package/dist/modes/interactive/interactive-prompt-restore.d.ts.map +1 -1
  119. package/dist/modes/interactive/interactive-prompt-restore.js +0 -5
  120. package/dist/modes/interactive/interactive-prompt-restore.js.map +1 -1
  121. package/dist/modes/interactive/interactive-render-chat.js +0 -5
  122. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  123. package/dist/modes/rpc/rpc-client-process.d.ts +7 -0
  124. package/dist/modes/rpc/rpc-client-process.d.ts.map +1 -1
  125. package/dist/modes/rpc/rpc-client-process.js +20 -3
  126. package/dist/modes/rpc/rpc-client-process.js.map +1 -1
  127. package/dist/modes/rpc/rpc-command-timeouts.d.ts.map +1 -1
  128. package/dist/modes/rpc/rpc-command-timeouts.js +1 -0
  129. package/dist/modes/rpc/rpc-command-timeouts.js.map +1 -1
  130. package/dist/utils/ansi.d.ts +8 -0
  131. package/dist/utils/ansi.d.ts.map +1 -1
  132. package/dist/utils/ansi.js +29 -10
  133. package/dist/utils/ansi.js.map +1 -1
  134. package/dist/utils/clipboard.d.ts.map +1 -1
  135. package/dist/utils/clipboard.js +13 -3
  136. package/dist/utils/clipboard.js.map +1 -1
  137. package/dist/utils/image-resize-core.d.ts +8 -0
  138. package/dist/utils/image-resize-core.d.ts.map +1 -1
  139. package/dist/utils/image-resize-core.js +1 -0
  140. package/dist/utils/image-resize-core.js.map +1 -1
  141. package/dist/utils/image-resize-worker.js +3 -2
  142. package/dist/utils/image-resize-worker.js.map +1 -1
  143. package/dist/utils/image-resize.d.ts +2 -2
  144. package/dist/utils/image-resize.d.ts.map +1 -1
  145. package/dist/utils/image-resize.js +7 -10
  146. package/dist/utils/image-resize.js.map +1 -1
  147. package/docs/codemode.md +21 -1
  148. package/docs/llama-cpp.md +9 -2
  149. package/docs/mcp-servers.md +3 -3
  150. package/docs/models.md +10 -0
  151. package/docs/providers.md +27 -4
  152. package/docs/reference/cli.md +2 -2
  153. package/docs/sdk/reference.md +3 -3
  154. package/docs/settings.md +2 -2
  155. package/docs/tools.md +1 -1
  156. package/docs/workflows/operations.md +2 -2
  157. package/npm-shrinkwrap.json +32 -32
  158. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"agent-session.js","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,+BAA+B,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,sCAAsC,EAAE,MAAM,0CAA0C,CAAC;AAClG,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF,OAAO,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AqC,EACrC,oCAAoC,EACpC,+BAA+B,EAC/B,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,CACvB,CAAC","sourcesContent":["/**\n * AgentSession - Core abstraction for agent lifecycle and session management.\n *\n * The historical import path is preserved here as a facade. Responsibilities are\n * implemented in sibling modules by lifecycle area so each authored source file\n * stays focused.\n */\n\nimport { join } from \"node:path\";\nimport type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport type { Agent, AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { installAgentSessionAccessors } from \"./agent-session-accessors.ts\";\nimport { agentSessionAutoCompactionMethods } from \"./agent-session-auto-compaction.ts\";\nimport { agentSessionBashMethods } from \"./agent-session-bash.ts\";\nimport { agentSessionBoundaryMethods } from \"./agent-session-boundaries.ts\";\nimport { agentSessionCompactionMethods } from \"./agent-session-compaction.ts\";\nimport { agentSessionCustomMessageCommitMethods } from \"./agent-session-custom-message-commit.ts\";\nimport { agentSessionEventsMethods } from \"./agent-session-events.ts\";\nimport { agentSessionExportMethods } from \"./agent-session-export.ts\";\nimport { agentSessionExtensionBindingsMethods } from \"./agent-session-extension-bindings.ts\";\nimport { agentSessionMessageQueueMethods } from \"./agent-session-message-queue.ts\";\nimport type { AgentSessionInternalSurface, AgentSessionPublicSurface } from \"./agent-session-methods.ts\";\nimport { agentSessionModelsMethods } from \"./agent-session-models.ts\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPostToolCompactionMethods } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPromptMethods } from \"./agent-session-prompt.ts\";\nimport { agentSessionRetryMethods } from \"./agent-session-retry.ts\";\nimport { agentSessionStateMethods } from \"./agent-session-state.ts\";\nimport { agentSessionSummaryMethods, type SessionSummaryRun } from \"./agent-session-summary.ts\";\nimport { agentSessionTaskMethods, isSubagentChildSession } from \"./agent-session-tasks.js\";\nimport { agentSessionToolHooksMethods } from \"./agent-session-tool-hooks.ts\";\nimport { agentSessionToolRegistryMethods } from \"./agent-session-tool-registry.ts\";\nimport { agentSessionTreeMethods } from \"./agent-session-tree.ts\";\nimport type {\n\tAgentSessionConfig,\n\tAgentSessionEventListener,\n\tInterruptQueueHold,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.js\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tAgentActivityOutcome,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tSubagentChildPolicy,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.js\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { NormalizedBuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport { ChildTaskWaits } from \"./tasks/child-command-owner.js\";\nimport { createToolNameMatcher } from \"./tool-selection.ts\";\nimport { getDefaultToolNames } from \"./tools/index.ts\";\nimport { scheduleSessionTempCleanup } from \"./tools/session-temp-cleanup.ts\";\nimport { acquireProtectedPaths, type ProtectedPathLease, setActiveSessionTempId } from \"./tools/session-temp-dir.ts\";\nimport { ToolExecutionScheduler } from \"./tools/tool-concurrency.ts\";\nimport { TOOL_RESULTS_SUBDIR } from \"./tools/tool-limits.js\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\nexport type { ParsedSkillBlock } from \"./agent-session-skill-block.ts\";\nexport { parseSkillBlock } from \"./agent-session-skill-block.ts\";\nexport type {\n\tAgentSessionConfig,\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tCompactionReason,\n\tExtensionBindings,\n\tModelCycleResult,\n\tPromptDisposition,\n\tPromptOptions,\n\tQueuedInputDisposition,\n\tSessionStats,\n} from \"./agent-session-types.js\";\n\nclass AgentSessionBase {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n\n\tprotected _scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tprotected _fallbackModels: string[];\n\tprotected _isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\tprotected _fallbackAttemptedKeys: Set<string> = new Set();\n\t/** Models condemned for this turn by a failure retrying them cannot repair. */\n\tprotected _fallbackBlockedModels: Array<Model<Api>> = [];\n\tprotected _fallbackOriginModel: Model<Api> | undefined;\n\tprotected _fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\tprotected _fallbackScopeGeneration = 0;\n\tprotected _fallbackOriginGeneration: number | undefined;\n\tprotected _fallbackRestoreError: string | undefined;\n\tprotected _unsubscribeAgent?: () => void;\n\tprotected _eventListeners: AgentSessionEventListener[] = [];\n\tprotected _agentEventQueue: Promise<void> = Promise.resolve();\n\tprotected _steeringMessages: string[] = [];\n\tprotected _followUpMessages: string[] = [];\n\tprotected _interruptDeliveryQueue: Promise<void> = Promise.resolve();\n\tprotected _pendingInterruptDeliveries = 0;\n\tprotected _activeInterruptQueueHold: InterruptQueueHold | undefined = undefined;\n\tprotected _queuedMessagesPaused = false;\n\tprotected _queuedMessagesPauseAbortBoundary: Promise<void> | undefined = undefined;\n\t/**\n\t * Text of a queued steering/follow-up message the agent loop already admitted\n\t * into the transcript and that has not received an assistant reply yet. The\n\t * pause hold cannot reach such a message, so an interrupt would otherwise\n\t * strand it (issue #2362).\n\t */\n\tprotected _admittedQueuedMessageAwaitingReply: string | undefined = undefined;\n\t/**\n\t * Settlement boundary for the recovery turn that answers an already-admitted\n\t * queued message. It starts after the pause abort boundary resolves, so the\n\t * resume path must wait for it too or an ordinary submission made while it\n\t * streams is rejected by the streaming guard (issue #2362).\n\t */\n\tprotected _admittedRecoveryTurn: Promise<void> | undefined = undefined;\n\tprotected _workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined = undefined;\n\tprotected _activeInterruptAbortMessage: string | undefined = undefined;\n\t/** Priority input cancels the native operation, not the host-owned task. */\n\tprotected _priorityInterruptPending = false;\n\tprotected _activePromptCount = 0;\n\tprotected _agentRunAbortRequested = false;\n\tprotected _pendingNextTurnMessages: CustomMessage[] = [];\n\t/** Context-only custom messages queued during a run, flushed after the current turn's tool results. */\n\tprotected _pendingCustomMessages: CustomMessage[] = [];\n\tprotected _protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}> = [];\n\tprotected _compactionAbortController: AbortController | undefined = undefined;\n\tprotected _compactionReason: import(\"./agent-session-types.js\").CompactionReason | undefined = undefined;\n\tprotected _manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined = undefined;\n\tprotected _autoCompactionAbortController: AbortController | undefined = undefined;\n\t/** Resolves when the current automatic compaction has settled. */\n\tprotected _autoCompactionCompletion: Promise<void> | undefined = undefined;\n\tprotected _overflowRecoveryAttempted = false;\n\tprotected _recoverableLengthRecoveryAttempted = false;\n\t/** Set when compaction cannot recover a context overflow on the current model. */\n\tprotected _contextOverflowUnresolved = false;\n\tprotected _pendingPostCompactionContinuation: Promise<void> | undefined = undefined;\n\tprotected _postCompactionContinuationToken = 0;\n\tprotected _lengthContinuationAttempts = 0;\n\tprotected _outputBudgetErrorContinuationAttempts = 0;\n\tprotected _postToolCompactionPreflightError: string | undefined = undefined;\n\tprotected _pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined = undefined;\n\tprotected _terminatingToolCallIds = new Set<string>();\n\t/** A positive stop callback keeps queued work pending until an explicit new run. */\n\tprotected _stopAfterTurnBlockedContinuation = false;\n\tprotected _disposed = false;\n\tprotected _branchSummaryAbortController: AbortController | undefined = undefined;\n\t/** Settles after the currently active branch-summary navigation finishes cleanup. */\n\tprotected _branchSummaryCompletion: Promise<void> | undefined = undefined;\n\tprotected _sessionSummaryAbortController: AbortController | undefined = undefined;\n\tprotected _sessionSummaryToken = 0;\n\t/** The summary request currently in flight, published so a later launch can join it. */\n\tprotected _sessionSummaryRun: SessionSummaryRun | undefined = undefined;\n\tprotected _lastSummarizedMessageId: string | undefined = undefined;\n\tprotected _retryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAttempt = 0;\n\tprotected _retryPromise: Promise<void> | undefined = undefined;\n\tprotected _retryResolve: (() => void) | undefined = undefined;\n\tprotected _bashAbortControllers = new Map<string | symbol, Set<AbortController>>();\n\tprotected _pendingBashMessages: BashExecutionMessage[] = [];\n\tprotected _extensionRunner!: ExtensionRunner;\n\tprotected _turnIndex = 0;\n\t/** Source entry IDs for projected messages, so boundaries and omissions resolve provenance. */\n\tprotected readonly _entryIdsByMessage = new WeakMap<object, string>();\n\t/** Assistant messages whose actionable turn_end already ran from finishTurn. */\n\tprotected readonly _boundaryDispatchedMessages = new WeakSet<object>();\n\tprotected readonly _messagesAwaitingPersistence = new WeakSet<object>();\n\tprotected _lastAssistantToolResults: AgentMessage[] = [];\n\tprotected _lastActivityOutcome: AgentActivityOutcome = \"completed\";\n\tprotected _isBeforeSettle = false;\n\tprotected _abortDuringBeforeSettle = false;\n\tprotected _isEmittingAgentSettled = false;\n\tprotected readonly _deferredSettledActions: Array<() => Promise<void>> = [];\n\t/** Set when a caller's prepareNextTurnWithContext replaced the next request's context. */\n\tprotected _callerReplacedNextRequestContext = false;\n\tprotected _resourceLoader: ResourceLoader;\n\tprotected _customTools: ToolDefinition[];\n\tprotected _baseToolDefinitions: Map<string, ToolDefinition> = new Map();\n\tprotected _cwd: string;\n\tprotected _extensionRunnerRef?: { current?: ExtensionRunner };\n\tprotected _initialActiveToolNames?: string[];\n\tprotected _pendingToolNames = new Set<string>();\n\tprotected _usesDefaultTools: boolean;\n\t/** Resolved defaults last applied here, independent of shared settings publication. */\n\tprotected _appliedDefaultTools: Set<string>;\n\tprotected _subagentPolicy?: SubagentChildPolicy;\n\tprotected _allowedToolNames?: Set<string>;\n\tprotected _excludedToolNames?: Set<string>;\n\tprotected _allowedTools?: (name: string) => boolean;\n\tprotected _excludedTools?: (name: string) => boolean;\n\tprotected _childSessionOptions?: import(\"./child-session-options.ts\").ChildSessionOptionsResolver;\n\tprotected _baseToolsOverride?: Record<string, AgentTool>;\n\tprotected _sessionStartEvent: SessionStartEvent;\n\tprotected _orchestrationContext?: OrchestrationContext;\n\tprotected _extensionUIContext?: ExtensionUIContext;\n\tprotected _extensionHumanInput?: import(\"./extensions/host-input.js\").HostInput | null;\n\tprotected _extensionDiagnosticListener?: (diagnostic: import(\"./extensions/host-input.js\").HostDiagnostic) => void;\n\tprotected _extensionMode: ExtensionMode = \"print\";\n\tprotected _extensionCommandContextActions?: ExtensionCommandContextActions;\n\tprotected _extensionShutdownHandler?: () => void;\n\tprotected _extensionErrorListener?: ExtensionErrorListener;\n\tprotected _extensionErrorUnsubscriber?: () => void;\n\tprotected _modelRuntime: ModelRuntime;\n\tprotected _extensionProviderIds = new Set<string>();\n\tprotected _toolRegistry: Map<string, AgentTool> = new Map();\n\tprotected readonly _toolExecutionScheduler = new ToolExecutionScheduler();\n\tprotected _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();\n\tprotected _toolPromptSnippets: Map<string, string> = new Map();\n\tprotected _toolPromptGuidelines: Map<string, string[]> = new Map();\n\tprotected _baseSystemPromptOptions!: NormalizedBuildSystemPromptOptions;\n\tprotected _systemPromptTransform?: (prompt: string) => string;\n\tprotected _contextProjectionTransform?: (messages: AgentMessage[]) => AgentMessage[];\n\tprotected _runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;\n\tprotected _lastAssistantMessage: AssistantMessage | undefined = undefined;\n\t/** Protection claim on this session's temp tree and tool-results directory. */\n\tprotected _tempStorageLease: ProtectedPathLease | undefined;\n\tprotected _workflowStageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _subagentMessageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\tprotected _parentCommandTaskOwner: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner | undefined;\n\tprotected _childTaskWaits = new ChildTaskWaits();\n\tprotected _taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\tprotected _taskAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _cacheWarmer?: import(\"./cache-warmer.ts\").CacheWarmer;\n\tget cacheWarmingStatus(): import(\"./cache-warmer.ts\").CacheWarmingStatus | undefined {\n\t\treturn this._cacheWarmer?.status;\n\t}\n\tsetCacheWarmingMode(mode: import(\"./settings-manager.ts\").CacheWarmingMode): void {\n\t\tthis.settingsManager.setCacheWarmingMode(mode);\n\t\tthis._cacheWarmer?.onModeChanged();\n\t}\n\n\tconstructor(config: AgentSessionConfig) {\n\t\tthis.agent = config.agent;\n\t\tthis.sessionManager = config.sessionManager;\n\t\tthis.settingsManager = config.settingsManager;\n\t\tthis._scopedModels = config.scopedModels ?? [];\n\t\tthis._fallbackModels = config.fallbackModels ?? [];\n\t\tthis._isFallbackModelAllowed = config.isFallbackModelAllowed;\n\t\tthis._resourceLoader = config.resourceLoader;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._cwd = config.cwd;\n\t\tthis._modelRuntime = config.modelRuntime;\n\t\tthis._cacheWarmer = config.cacheWarmer;\n\t\tif (this._cacheWarmer)\n\t\t\tthis._cacheWarmer.onWarmed = (entry) =>\n\t\t\t\t(this as unknown as import(\"./agent-session-methods.ts\").AgentSessionInternalSurface)._emit({\n\t\t\t\t\ttype: \"entry_appended\",\n\t\t\t\t\tentry,\n\t\t\t\t});\n\t\tthis._extensionProviderIds = new Set(config.resourceLoader.getExtensions().runtime.extensionProviderIds);\n\t\tthis._extensionRunnerRef = config.extensionRunnerRef;\n\t\tthis._initialActiveToolNames = config.initialActiveToolNames;\n\t\tthis._usesDefaultTools = config.usesDefaultTools ?? false;\n\t\tthis._appliedDefaultTools = new Set(\n\t\t\tthis._usesDefaultTools ? (this.settingsManager.getDefaultTools() ?? getDefaultToolNames()) : [],\n\t\t);\n\t\tthis._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;\n\t\tthis._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;\n\t\tthis._allowedTools = config.allowedToolNames ? createToolNameMatcher(config.allowedToolNames) : undefined;\n\t\tthis._excludedTools = config.excludedToolNames ? createToolNameMatcher(config.excludedToolNames) : undefined;\n\t\tthis._childSessionOptions = config.childSessionOptions;\n\t\tthis._baseToolsOverride = config.baseToolsOverride;\n\t\tthis._sessionStartEvent = config.sessionStartEvent ?? { type: \"session_start\", reason: \"startup\" };\n\t\tthis._orchestrationContext = config.orchestrationContext;\n\t\tthis._subagentPolicy = config.subagentPolicy;\n\t\tthis._parentCommandTaskOwner = config.parentCommandTaskOwner;\n\t\tlet removeExecutionEndedListener: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (config.subagentPolicy?.executionEnded !== undefined) {\n\t\t\t\t// Reuse the stable-key admission/drain primitive, not workflow identity or task ownership.\n\t\t\t\tconst admission = WorkflowStageAdmissionBoundary.restore(this.sessionManager.getBranch());\n\t\t\t\tthis._subagentMessageAdmission = admission;\n\t\t\t\tthis._subagentPolicy = {\n\t\t\t\t\t...config.subagentPolicy,\n\t\t\t\t\tmessageAdmission: {\n\t\t\t\t\t\tisOpen: () => admission.isOpen(),\n\t\t\t\t\t\trun: (deliver) =>\n\t\t\t\t\t\t\tadmission.runMessageDelivery(deliver, () => {\n\t\t\t\t\t\t\t\tthrow new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst ended = config.subagentPolicy.executionEnded;\n\t\t\t\tif (ended.aborted) admission.seal();\n\t\t\t\telse {\n\t\t\t\t\tconst seal = () => admission.seal();\n\t\t\t\t\tended.addEventListener(\"abort\", seal, { once: true });\n\t\t\t\t\tremoveExecutionEndedListener = () => ended.removeEventListener(\"abort\", seal);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._systemPromptTransform = config.systemPromptTransform;\n\t\t\tthis._contextProjectionTransform = config.contextProjectionTransform;\n\t\t\tconst stageContext =\n\t\t\t\tconfig.orchestrationContext?.kind === \"workflow-stage\" ? config.orchestrationContext : undefined;\n\t\t\tthis._workflowStageAdmission =\n\t\t\t\tstageContext?.messageAdmission?.boundary ??\n\t\t\t\t(stageContext ? WorkflowStageAdmissionBoundary.restore(this.sessionManager.getBranch()) : undefined);\n\t\t\tif (stageContext) {\n\t\t\t\tthis._workflowStageAdmission?.bindTaskIdentity(\n\t\t\t\t\tthis.sessionManager.getSessionId(),\n\t\t\t\t\tstageContext.workflowRunId,\n\t\t\t\t\tstageContext.workflowStageId,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (this._workflowStageAdmission && stageContext && stageContext.messageAdmission === undefined) {\n\t\t\t\t(\n\t\t\t\t\tstageContext as {\n\t\t\t\t\t\tmessageAdmission?: {\n\t\t\t\t\t\t\tboundary: WorkflowStageAdmissionBoundary;\n\t\t\t\t\t\t\textensionState: Map<string, object>;\n\t\t\t\t\t\t\tisOpen(): boolean;\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t).messageAdmission = {\n\t\t\t\t\tboundary: this._workflowStageAdmission,\n\t\t\t\t\textensionState: new Map(),\n\t\t\t\t\tisOpen: () => this._workflowStageAdmission?.isOpen() === true,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Claim this session's storage before any tool can spill into it, so the\n\t\t\t// sweeper below never reaps a directory this process is still writing to.\n\t\t\t// The claim is a lease, released in dispose(): a session that is gone must\n\t\t\t// stop protecting a tree the startup sweep exists to collect.\n\t\t\ttry {\n\t\t\t\tconst sessionId = this.sessionManager.getSessionId();\n\t\t\t\tconst sessionDir = this.sessionManager.getSessionDir() || undefined;\n\t\t\t\tthis._tempStorageLease = acquireProtectedPaths([\n\t\t\t\t\tsetActiveSessionTempId(sessionId),\n\t\t\t\t\t// A disk-backed session's results are read back by path, and a replayed\n\t\t\t\t\t// result reuses an old file without touching its mtime, so age alone\n\t\t\t\t\t// cannot keep it alive.\n\t\t\t\t\t...(sessionDir ? [join(sessionDir, TOOL_RESULTS_SUBDIR)] : []),\n\t\t\t\t]);\n\t\t\t\t// A custom `--session-dir` keeps its tool results directly under that\n\t\t\t\t// directory, outside the project-nested roots the default sweep walks,\n\t\t\t\t// so it has to be named as its own target.\n\t\t\t\tconst customSessionDir = this.sessionManager.usesDefaultSessionDir() ? undefined : sessionDir;\n\t\t\t\tscheduleSessionTempCleanup(customSessionDir ? { sessionDirs: [customSessionDir] } : {});\n\t\t\t} catch {\n\t\t\t\t// Temp-storage housekeeping must never block session construction.\n\t\t\t}\n\t\t\tconst internals = this as unknown as AgentSessionInternalSurface;\n\t\t\tinternals._handleAgentEvent = internals._handleAgentEvent.bind(this);\n\t\t\tthis._unsubscribeAgent = this.agent.subscribe(internals._handleAgentEvent);\n\t\t\tinternals._installAgentToolHooks();\n\t\t\tinternals._installAgentNextTurnRefresh();\n\t\t\tinternals._installAgentRequestProjection();\n\t\t\tinternals._installAgentBoundaryHooks();\n\t\t\tinternals._buildRuntime({\n\t\t\t\tactiveToolNames: this._initialActiveToolNames,\n\t\t\t\tincludeAllExtensionTools: true,\n\t\t\t});\n\t\t\tinternals._restoreToolsFromTranscript({ keepLoadout: this._initialActiveToolNames !== undefined });\n\t\t\tif (this._workflowStageAdmission?.hasAgentTaskHost() && !isSubagentChildSession(internals))\n\t\t\t\tinternals.getAgentTaskHost();\n\t\t} catch (error) {\n\t\t\t// No session escapes a failed constructor to release these acquisitions later.\n\t\t\tconst failures: unknown[] = [];\n\t\t\tfor (const release of [\n\t\t\t\t() => removeExecutionEndedListener?.(),\n\t\t\t\t() => this._unsubscribeAgent?.(),\n\t\t\t\t() => this._tempStorageLease?.release(),\n\t\t\t\t() => this._extensionRunner?.invalidate(\"Session construction failed\"),\n\t\t\t]) {\n\t\t\t\ttry {\n\t\t\t\t\trelease();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tfailures.push(cause);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._extensionRunnerRef) this._extensionRunnerRef.current = undefined;\n\t\t\tif (failures.length)\n\t\t\t\tthrow Object.assign(new AggregateError([error, ...failures], \"Session construction cleanup failed\"), {\n\t\t\t\t\tcode: \"ShutdownFailed\",\n\t\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nexport interface AgentSession extends AgentSessionBase, AgentSessionPublicSurface {}\n\nexport const AgentSession = AgentSessionBase as unknown as {\n\tnew (config: AgentSessionConfig): AgentSession;\n\treadonly prototype: AgentSession;\n};\n\ninstallAgentSessionAccessors(AgentSession.prototype as unknown as AgentSessionInternalSurface);\nObject.assign(\n\tAgentSession.prototype,\n\tagentSessionToolHooksMethods,\n\tagentSessionBoundaryMethods,\n\tagentSessionEventsMethods,\n\tagentSessionStateMethods,\n\tagentSessionPromptMethods,\n\tagentSessionCustomMessageCommitMethods,\n\tagentSessionMessageQueueMethods,\n\tagentSessionModelsMethods,\n\tagentSessionCompactionMethods,\n\tagentSessionAutoCompactionMethods,\n\tagentSessionPostToolCompactionMethods,\n\tagentSessionExtensionBindingsMethods,\n\tagentSessionToolRegistryMethods,\n\tagentSessionRetryMethods,\n\tagentSessionBashMethods,\n\tagentSessionTreeMethods,\n\tagentSessionExportMethods,\n\tagentSessionSummaryMethods,\n\tagentSessionTaskMethods,\n);\n"]}
1
+ {"version":3,"file":"agent-session.js","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAGjC,OAAO,EAAE,4BAA4B,EAAE,MAA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AAC,KAAK,CAAC,CAAC;gBACtB,CAAC;YACF,CAAC;YACD,IAAI,IAAI,CAAC,mBAAmB;gBAAE,IAAI,CAAC,mBAAmB,CAAC,OAAO,GAAG,SAAS,CAAC;YAC3E,IAAI,QAAQ,CAAC,MAAM;gBAClB,MAAM,MAAM,CAAC,MAAM,CAAC,IAAI,cAAc,CAAC,CAAC,KAAK,EAAE,GAAG,QAAQ,CAAC,EAAE,qCAAqC,CAAC,EAAE;oBACpG,IAAI,EAAE,gBAAgB;iBACtB,CAAC,CAAC;YACJ,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;CACD;AAID,MAAM,CAAC,MAAM,YAAY,GAAG,gBAG3B,CAAC;AAEF,4BAA4B,CAAC,YAAY,CAAC,SAAmD,CAAC,CAAC;AAC/F,MAAM,CAAC,MAAM,CACZ,YAAY,CAAC,SAAS,EACtB,4BAA4B,EAC5B,2BAA2B,EAC3B,yBAAyB,EACzB,wBAAwB,EACxB,yBAAyB,EACzB,sCAAsC,EACtC,+BAA+B,EAC/B,yBAAyB,EACzB,6BAA6B,EAC7B,iCAAiC,EACjC,qCAAqC,EACrC,oCAAoC,EACpC,+BAA+B,EAC/B,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,yBAAyB,EACzB,0BAA0B,EAC1B,uBAAuB,CACvB,CAAC","sourcesContent":["/**\n * AgentSession - Core abstraction for agent lifecycle and session management.\n *\n * The historical import path is preserved here as a facade. Responsibilities are\n * implemented in sibling modules by lifecycle area so each authored source file\n * stays focused.\n */\n\nimport { join } from \"node:path\";\nimport type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport type { Agent, AgentMessage, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { installAgentSessionAccessors } from \"./agent-session-accessors.ts\";\nimport { agentSessionAutoCompactionMethods } from \"./agent-session-auto-compaction.ts\";\nimport { agentSessionBashMethods } from \"./agent-session-bash.ts\";\nimport { agentSessionBoundaryMethods } from \"./agent-session-boundaries.ts\";\nimport { agentSessionCompactionMethods } from \"./agent-session-compaction.ts\";\nimport { agentSessionCustomMessageCommitMethods } from \"./agent-session-custom-message-commit.ts\";\nimport { agentSessionEventsMethods } from \"./agent-session-events.ts\";\nimport { agentSessionExportMethods } from \"./agent-session-export.ts\";\nimport { agentSessionExtensionBindingsMethods } from \"./agent-session-extension-bindings.ts\";\nimport { agentSessionMessageQueueMethods } from \"./agent-session-message-queue.ts\";\nimport type { AgentSessionInternalSurface, AgentSessionPublicSurface } from \"./agent-session-methods.ts\";\nimport { agentSessionModelsMethods } from \"./agent-session-models.ts\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPostToolCompactionMethods } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPromptMethods } from \"./agent-session-prompt.ts\";\nimport { agentSessionRetryMethods } from \"./agent-session-retry.ts\";\nimport { agentSessionStateMethods } from \"./agent-session-state.ts\";\nimport { agentSessionSummaryMethods, type SessionSummaryRun } from \"./agent-session-summary.ts\";\nimport { agentSessionTaskMethods, isSubagentChildSession } from \"./agent-session-tasks.js\";\nimport { agentSessionToolHooksMethods } from \"./agent-session-tool-hooks.ts\";\nimport { agentSessionToolRegistryMethods } from \"./agent-session-tool-registry.ts\";\nimport { agentSessionTreeMethods } from \"./agent-session-tree.ts\";\nimport type {\n\tAgentSessionConfig,\n\tAgentSessionEventListener,\n\tInterruptQueueHold,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.js\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tAgentActivityOutcome,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tSubagentChildPolicy,\n\tToolDefinition,\n} from \"./extensions/index.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.js\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { applyToolModifiers } from \"./settings-merge.js\";\nimport type { NormalizedBuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport { ChildTaskWaits } from \"./tasks/child-command-owner.js\";\nimport { createToolNameMatcher } from \"./tool-selection.ts\";\nimport { getDefaultToolNames } from \"./tools/index.js\";\nimport { scheduleSessionTempCleanup } from \"./tools/session-temp-cleanup.ts\";\nimport { acquireProtectedPaths, type ProtectedPathLease, setActiveSessionTempId } from \"./tools/session-temp-dir.ts\";\nimport { ToolExecutionScheduler } from \"./tools/tool-concurrency.ts\";\nimport { TOOL_RESULTS_SUBDIR } from \"./tools/tool-limits.js\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\nexport type { ParsedSkillBlock } from \"./agent-session-skill-block.ts\";\nexport { parseSkillBlock } from \"./agent-session-skill-block.ts\";\nexport type {\n\tAgentSessionConfig,\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tCompactionReason,\n\tExtensionBindings,\n\tModelCycleResult,\n\tPromptDisposition,\n\tPromptOptions,\n\tQueuedInputDisposition,\n\tSessionStats,\n} from \"./agent-session-types.js\";\n\nclass AgentSessionBase {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n\n\tprotected _scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tprotected _fallbackModels: string[];\n\tprotected _isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\tprotected _fallbackAttemptedKeys: Set<string> = new Set();\n\t/** Models condemned for this turn by a failure retrying them cannot repair. */\n\tprotected _fallbackBlockedModels: Array<Model<Api>> = [];\n\tprotected _fallbackOriginModel: Model<Api> | undefined;\n\tprotected _fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\tprotected _fallbackScopeGeneration = 0;\n\tprotected _fallbackOriginGeneration: number | undefined;\n\tprotected _fallbackRestoreError: string | undefined;\n\tprotected _unsubscribeAgent?: () => void;\n\tprotected _eventListeners: AgentSessionEventListener[] = [];\n\tprotected _agentEventQueue: Promise<void> = Promise.resolve();\n\tprotected _steeringMessages: string[] = [];\n\tprotected _followUpMessages: string[] = [];\n\tprotected _interruptDeliveryQueue: Promise<void> = Promise.resolve();\n\tprotected _pendingInterruptDeliveries = 0;\n\tprotected _activeInterruptQueueHold: InterruptQueueHold | undefined = undefined;\n\tprotected _queuedMessagesPaused = false;\n\tprotected _queuedMessagesPauseAbortBoundary: Promise<void> | undefined = undefined;\n\t/**\n\t * Text of a queued steering/follow-up message the agent loop already admitted\n\t * into the transcript and that has not received an assistant reply yet. The\n\t * pause hold cannot reach such a message, so an interrupt would otherwise\n\t * strand it (issue #2362).\n\t */\n\tprotected _admittedQueuedMessageAwaitingReply: string | undefined = undefined;\n\t/**\n\t * Settlement boundary for the recovery turn that answers an already-admitted\n\t * queued message. It starts after the pause abort boundary resolves, so the\n\t * resume path must wait for it too or an ordinary submission made while it\n\t * streams is rejected by the streaming guard (issue #2362).\n\t */\n\tprotected _admittedRecoveryTurn: Promise<void> | undefined = undefined;\n\tprotected _workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined = undefined;\n\tprotected _activeInterruptAbortMessage: string | undefined = undefined;\n\t/** Priority input cancels the native operation, not the host-owned task. */\n\tprotected _priorityInterruptPending = false;\n\tprotected _activePromptCount = 0;\n\tprotected _agentRunAbortRequested = false;\n\tprotected _pendingNextTurnMessages: CustomMessage[] = [];\n\t/** Context-only custom messages queued during a run, flushed after the current turn's tool results. */\n\tprotected _pendingCustomMessages: CustomMessage[] = [];\n\tprotected _protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}> = [];\n\tprotected _compactionAbortController: AbortController | undefined = undefined;\n\tprotected _compactionReason: import(\"./agent-session-types.js\").CompactionReason | undefined = undefined;\n\tprotected _manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined = undefined;\n\tprotected _autoCompactionAbortController: AbortController | undefined = undefined;\n\t/** Resolves when the current automatic compaction has settled. */\n\tprotected _autoCompactionCompletion: Promise<void> | undefined = undefined;\n\tprotected _overflowRecoveryAttempted = false;\n\tprotected _recoverableLengthRecoveryAttempted = false;\n\t/** Set when compaction cannot recover a context overflow on the current model. */\n\tprotected _contextOverflowUnresolved = false;\n\tprotected _pendingPostCompactionContinuation: Promise<void> | undefined = undefined;\n\tprotected _postCompactionContinuationToken = 0;\n\tprotected _lengthContinuationAttempts = 0;\n\tprotected _outputBudgetErrorContinuationAttempts = 0;\n\tprotected _postToolCompactionPreflightError: string | undefined = undefined;\n\tprotected _pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined = undefined;\n\tprotected _terminatingToolCallIds = new Set<string>();\n\t/** A positive stop callback keeps queued work pending until an explicit new run. */\n\tprotected _stopAfterTurnBlockedContinuation = false;\n\tprotected _disposed = false;\n\tprotected _branchSummaryAbortController: AbortController | undefined = undefined;\n\t/** Settles after the currently active branch-summary navigation finishes cleanup. */\n\tprotected _branchSummaryCompletion: Promise<void> | undefined = undefined;\n\tprotected _sessionSummaryAbortController: AbortController | undefined = undefined;\n\tprotected _sessionSummaryToken = 0;\n\t/** The summary request currently in flight, published so a later launch can join it. */\n\tprotected _sessionSummaryRun: SessionSummaryRun | undefined = undefined;\n\tprotected _lastSummarizedMessageId: string | undefined = undefined;\n\tprotected _retryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAttempt = 0;\n\tprotected _retryPromise: Promise<void> | undefined = undefined;\n\tprotected _retryResolve: (() => void) | undefined = undefined;\n\tprotected _bashAbortControllers = new Map<string | symbol, Set<AbortController>>();\n\tprotected _pendingBashMessages: BashExecutionMessage[] = [];\n\tprotected _extensionRunner!: ExtensionRunner;\n\tprotected _turnIndex = 0;\n\t/** Source entry IDs for projected messages, so boundaries and omissions resolve provenance. */\n\tprotected readonly _entryIdsByMessage = new WeakMap<object, string>();\n\t/** Assistant messages whose actionable turn_end already ran from finishTurn. */\n\tprotected readonly _boundaryDispatchedMessages = new WeakSet<object>();\n\tprotected readonly _messagesAwaitingPersistence = new WeakSet<object>();\n\tprotected _lastAssistantToolResults: AgentMessage[] = [];\n\tprotected _lastActivityOutcome: AgentActivityOutcome = \"completed\";\n\tprotected _isBeforeSettle = false;\n\tprotected _abortDuringBeforeSettle = false;\n\tprotected _isEmittingAgentSettled = false;\n\tprotected readonly _deferredSettledActions: Array<() => Promise<void>> = [];\n\t/** Set when a caller's prepareNextTurnWithContext replaced the next request's context. */\n\tprotected _callerReplacedNextRequestContext = false;\n\tprotected _resourceLoader: ResourceLoader;\n\tprotected _customTools: ToolDefinition[];\n\tprotected _baseToolDefinitions: Map<string, ToolDefinition> = new Map();\n\tprotected _cwd: string;\n\tprotected _extensionRunnerRef?: { current?: ExtensionRunner };\n\tprotected _initialActiveToolNames?: string[];\n\tprotected _pendingToolNames = new Set<string>();\n\tprotected _usesDefaultTools: boolean;\n\tprotected _defaultToolModifiers: string[];\n\t/** Resolved defaults last applied here, independent of shared settings publication. */\n\tprotected _appliedDefaultTools: Set<string>;\n\tprotected _subagentPolicy?: SubagentChildPolicy;\n\tprotected _allowedToolNames?: Set<string>;\n\tprotected _excludedToolNames?: Set<string>;\n\tprotected _allowedTools?: (name: string) => boolean;\n\tprotected _excludedTools?: (name: string) => boolean;\n\tprotected _childSessionOptions?: import(\"./child-session-options.ts\").ChildSessionOptionsResolver;\n\tprotected _baseToolsOverride?: Record<string, AgentTool>;\n\tprotected _sessionStartEvent: SessionStartEvent;\n\tprotected _orchestrationContext?: OrchestrationContext;\n\tprotected _extensionUIContext?: ExtensionUIContext;\n\tprotected _extensionHumanInput?: import(\"./extensions/host-input.js\").HostInput | null;\n\tprotected _extensionDiagnosticListener?: (diagnostic: import(\"./extensions/host-input.js\").HostDiagnostic) => void;\n\tprotected _extensionMode: ExtensionMode = \"print\";\n\tprotected _extensionCommandContextActions?: ExtensionCommandContextActions;\n\tprotected _extensionShutdownHandler?: () => void;\n\tprotected _extensionErrorListener?: ExtensionErrorListener;\n\tprotected _extensionErrorUnsubscriber?: () => void;\n\tprotected _modelRuntime: ModelRuntime;\n\tprotected _extensionProviderIds = new Set<string>();\n\tprotected _toolRegistry: Map<string, AgentTool> = new Map();\n\tprotected readonly _toolExecutionScheduler = new ToolExecutionScheduler();\n\tprotected _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();\n\tprotected _toolPromptSnippets: Map<string, string> = new Map();\n\tprotected _toolPromptGuidelines: Map<string, string[]> = new Map();\n\tprotected _baseSystemPromptOptions!: NormalizedBuildSystemPromptOptions;\n\tprotected _systemPromptTransform?: (prompt: string) => string;\n\tprotected _contextProjectionTransform?: (messages: AgentMessage[]) => AgentMessage[];\n\tprotected _runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;\n\tprotected _lastAssistantMessage: AssistantMessage | undefined = undefined;\n\t/** Protection claim on this session's temp tree and tool-results directory. */\n\tprotected _tempStorageLease: ProtectedPathLease | undefined;\n\tprotected _workflowStageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _subagentMessageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\tprotected _parentCommandTaskOwner: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner | undefined;\n\tprotected _childTaskWaits = new ChildTaskWaits();\n\tprotected _taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\tprotected _taskAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tprotected _cacheWarmer?: import(\"./cache-warmer.ts\").CacheWarmer;\n\tget cacheWarmingStatus(): import(\"./cache-warmer.ts\").CacheWarmingStatus | undefined {\n\t\treturn this._cacheWarmer?.status;\n\t}\n\tsetCacheWarmingMode(mode: import(\"./settings-manager.ts\").CacheWarmingMode): void {\n\t\tthis.settingsManager.setCacheWarmingMode(mode);\n\t\tthis._cacheWarmer?.onModeChanged();\n\t}\n\n\tconstructor(config: AgentSessionConfig) {\n\t\tthis.agent = config.agent;\n\t\tthis.sessionManager = config.sessionManager;\n\t\tthis.settingsManager = config.settingsManager;\n\t\tthis._scopedModels = config.scopedModels ?? [];\n\t\tthis._fallbackModels = config.fallbackModels ?? [];\n\t\tthis._isFallbackModelAllowed = config.isFallbackModelAllowed;\n\t\tthis._resourceLoader = config.resourceLoader;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._cwd = config.cwd;\n\t\tthis._modelRuntime = config.modelRuntime;\n\t\tthis._cacheWarmer = config.cacheWarmer;\n\t\tif (this._cacheWarmer)\n\t\t\tthis._cacheWarmer.onWarmed = (entry) =>\n\t\t\t\t(this as unknown as import(\"./agent-session-methods.ts\").AgentSessionInternalSurface)._emit({\n\t\t\t\t\ttype: \"entry_appended\",\n\t\t\t\t\tentry,\n\t\t\t\t});\n\t\tthis._extensionProviderIds = new Set(config.resourceLoader.getExtensions().runtime.extensionProviderIds);\n\t\tthis._extensionRunnerRef = config.extensionRunnerRef;\n\t\tthis._initialActiveToolNames = config.initialActiveToolNames;\n\t\tthis._usesDefaultTools = config.usesDefaultTools ?? false;\n\t\tthis._defaultToolModifiers = config.defaultToolModifiers ?? [];\n\t\tthis._appliedDefaultTools = new Set(\n\t\t\tthis._usesDefaultTools\n\t\t\t\t? applyToolModifiers(\n\t\t\t\t\t\tthis.settingsManager.getDefaultTools() ?? getDefaultToolNames(),\n\t\t\t\t\t\tthis._defaultToolModifiers,\n\t\t\t\t\t)\n\t\t\t\t: [],\n\t\t);\n\t\tthis._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;\n\t\tthis._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;\n\t\tthis._allowedTools = config.allowedToolNames ? createToolNameMatcher(config.allowedToolNames) : undefined;\n\t\tthis._excludedTools = config.excludedToolNames ? createToolNameMatcher(config.excludedToolNames) : undefined;\n\t\tthis._childSessionOptions = config.childSessionOptions;\n\t\tthis._baseToolsOverride = config.baseToolsOverride;\n\t\tthis._sessionStartEvent = config.sessionStartEvent ?? { type: \"session_start\", reason: \"startup\" };\n\t\tthis._orchestrationContext = config.orchestrationContext;\n\t\tthis._subagentPolicy = config.subagentPolicy;\n\t\tthis._parentCommandTaskOwner = config.parentCommandTaskOwner;\n\t\tlet removeExecutionEndedListener: (() => void) | undefined;\n\t\ttry {\n\t\t\tif (config.subagentPolicy?.executionEnded !== undefined) {\n\t\t\t\t// Reuse the stable-key admission/drain primitive, not workflow identity or task ownership.\n\t\t\t\tconst admission = WorkflowStageAdmissionBoundary.restore(this.sessionManager.getBranch());\n\t\t\t\tthis._subagentMessageAdmission = admission;\n\t\t\t\tthis._subagentPolicy = {\n\t\t\t\t\t...config.subagentPolicy,\n\t\t\t\t\tmessageAdmission: {\n\t\t\t\t\t\tisOpen: () => admission.isOpen(),\n\t\t\t\t\t\trun: (deliver) =>\n\t\t\t\t\t\t\tadmission.runMessageDelivery(deliver, () => {\n\t\t\t\t\t\t\t\tthrow new Error(\"Subagent execution is terminal and cannot accept messages\");\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t\tconst ended = config.subagentPolicy.executionEnded;\n\t\t\t\tif (ended.aborted) admission.seal();\n\t\t\t\telse {\n\t\t\t\t\tconst seal = () => admission.seal();\n\t\t\t\t\tended.addEventListener(\"abort\", seal, { once: true });\n\t\t\t\t\tremoveExecutionEndedListener = () => ended.removeEventListener(\"abort\", seal);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._systemPromptTransform = config.systemPromptTransform;\n\t\t\tthis._contextProjectionTransform = config.contextProjectionTransform;\n\t\t\tconst stageContext =\n\t\t\t\tconfig.orchestrationContext?.kind === \"workflow-stage\" ? config.orchestrationContext : undefined;\n\t\t\tthis._workflowStageAdmission =\n\t\t\t\tstageContext?.messageAdmission?.boundary ??\n\t\t\t\t(stageContext ? WorkflowStageAdmissionBoundary.restore(this.sessionManager.getBranch()) : undefined);\n\t\t\tif (stageContext) {\n\t\t\t\tthis._workflowStageAdmission?.bindTaskIdentity(\n\t\t\t\t\tthis.sessionManager.getSessionId(),\n\t\t\t\t\tstageContext.workflowRunId,\n\t\t\t\t\tstageContext.workflowStageId,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (this._workflowStageAdmission && stageContext && stageContext.messageAdmission === undefined) {\n\t\t\t\t(\n\t\t\t\t\tstageContext as {\n\t\t\t\t\t\tmessageAdmission?: {\n\t\t\t\t\t\t\tboundary: WorkflowStageAdmissionBoundary;\n\t\t\t\t\t\t\textensionState: Map<string, object>;\n\t\t\t\t\t\t\tisOpen(): boolean;\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t).messageAdmission = {\n\t\t\t\t\tboundary: this._workflowStageAdmission,\n\t\t\t\t\textensionState: new Map(),\n\t\t\t\t\tisOpen: () => this._workflowStageAdmission?.isOpen() === true,\n\t\t\t\t};\n\t\t\t}\n\t\t\t// Claim this session's storage before any tool can spill into it, so the\n\t\t\t// sweeper below never reaps a directory this process is still writing to.\n\t\t\t// The claim is a lease, released in dispose(): a session that is gone must\n\t\t\t// stop protecting a tree the startup sweep exists to collect.\n\t\t\ttry {\n\t\t\t\tconst sessionId = this.sessionManager.getSessionId();\n\t\t\t\tconst sessionDir = this.sessionManager.getSessionDir() || undefined;\n\t\t\t\tthis._tempStorageLease = acquireProtectedPaths([\n\t\t\t\t\tsetActiveSessionTempId(sessionId),\n\t\t\t\t\t// A disk-backed session's results are read back by path, and a replayed\n\t\t\t\t\t// result reuses an old file without touching its mtime, so age alone\n\t\t\t\t\t// cannot keep it alive.\n\t\t\t\t\t...(sessionDir ? [join(sessionDir, TOOL_RESULTS_SUBDIR)] : []),\n\t\t\t\t]);\n\t\t\t\t// A custom `--session-dir` keeps its tool results directly under that\n\t\t\t\t// directory, outside the project-nested roots the default sweep walks,\n\t\t\t\t// so it has to be named as its own target.\n\t\t\t\tconst customSessionDir = this.sessionManager.usesDefaultSessionDir() ? undefined : sessionDir;\n\t\t\t\tscheduleSessionTempCleanup(customSessionDir ? { sessionDirs: [customSessionDir] } : {});\n\t\t\t} catch {\n\t\t\t\t// Temp-storage housekeeping must never block session construction.\n\t\t\t}\n\t\t\tconst internals = this as unknown as AgentSessionInternalSurface;\n\t\t\tinternals._handleAgentEvent = internals._handleAgentEvent.bind(this);\n\t\t\tthis._unsubscribeAgent = this.agent.subscribe(internals._handleAgentEvent);\n\t\t\tinternals._installAgentToolHooks();\n\t\t\tinternals._installAgentNextTurnRefresh();\n\t\t\tinternals._installAgentRequestProjection();\n\t\t\tinternals._installAgentBoundaryHooks();\n\t\t\tinternals._buildRuntime({\n\t\t\t\tactiveToolNames: this._initialActiveToolNames,\n\t\t\t\tincludeAllExtensionTools: true,\n\t\t\t});\n\t\t\tinternals._restoreToolsFromTranscript({ keepLoadout: this._initialActiveToolNames !== undefined });\n\t\t\tif (this._workflowStageAdmission?.hasAgentTaskHost() && !isSubagentChildSession(internals))\n\t\t\t\tinternals.getAgentTaskHost();\n\t\t} catch (error) {\n\t\t\t// No session escapes a failed constructor to release these acquisitions later.\n\t\t\tconst failures: unknown[] = [];\n\t\t\tfor (const release of [\n\t\t\t\t() => removeExecutionEndedListener?.(),\n\t\t\t\t() => this._unsubscribeAgent?.(),\n\t\t\t\t() => this._tempStorageLease?.release(),\n\t\t\t\t() => this._extensionRunner?.invalidate(\"Session construction failed\"),\n\t\t\t]) {\n\t\t\t\ttry {\n\t\t\t\t\trelease();\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tfailures.push(cause);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this._extensionRunnerRef) this._extensionRunnerRef.current = undefined;\n\t\t\tif (failures.length)\n\t\t\t\tthrow Object.assign(new AggregateError([error, ...failures], \"Session construction cleanup failed\"), {\n\t\t\t\t\tcode: \"ShutdownFailed\",\n\t\t\t\t});\n\t\t\tthrow error;\n\t\t}\n\t}\n}\n\nexport interface AgentSession extends AgentSessionBase, AgentSessionPublicSurface {}\n\nexport const AgentSession = AgentSessionBase as unknown as {\n\tnew (config: AgentSessionConfig): AgentSession;\n\treadonly prototype: AgentSession;\n};\n\ninstallAgentSessionAccessors(AgentSession.prototype as unknown as AgentSessionInternalSurface);\nObject.assign(\n\tAgentSession.prototype,\n\tagentSessionToolHooksMethods,\n\tagentSessionBoundaryMethods,\n\tagentSessionEventsMethods,\n\tagentSessionStateMethods,\n\tagentSessionPromptMethods,\n\tagentSessionCustomMessageCommitMethods,\n\tagentSessionMessageQueueMethods,\n\tagentSessionModelsMethods,\n\tagentSessionCompactionMethods,\n\tagentSessionAutoCompactionMethods,\n\tagentSessionPostToolCompactionMethods,\n\tagentSessionExtensionBindingsMethods,\n\tagentSessionToolRegistryMethods,\n\tagentSessionRetryMethods,\n\tagentSessionBashMethods,\n\tagentSessionTreeMethods,\n\tagentSessionExportMethods,\n\tagentSessionSummaryMethods,\n\tagentSessionTaskMethods,\n);\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.d.ts","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,OAAO,KAAK,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AASzE,MAAM,WAAW,mBAAmB;IACnC,+FAA+F;IAC/F,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,KAAK,IAAI,CAAC;IAC9D,mCAAmC;IACnC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,sDAAsD;IACtD,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,qEAAqE;IACrE,GAAG,CAAC,EAAE,OAAO,CAAC;IACd;;;OAGG;IACH,cAAc,CAAC,EAAE,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Ac,CAAC,EAAE,MAAM,CAAC;CACxB;AAMD;;;GAGG;AACH,wBAAsB,yBAAyB,CAC9C,OAAO,EAAE,MAAM,EACf,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,cAAc,EAC1B,OAAO,CAAC,EAAE,mBAAmB,GAC3B,OAAO,CAAC,UAAU,CAAC,CAoJrB"}
@@ -8,7 +8,7 @@
8
8
  import { randomBytes } from "node:crypto";
9
9
  import { join } from "node:path";
10
10
  import { APP_NAME } from "../config.js";
11
- import { stripAnsi } from "../utils/ansi.js";
11
+ import { splitIncompleteAnsiSuffix, stripAnsi } from "../utils/ansi.js";
12
12
  import { sanitizeBinaryOutput } from "../utils/shell.js";
13
13
  import { PersistedOutputFile } from "./tools/persisted-output-file.js";
14
14
  import { ensureSessionTempDir } from "./tools/session-temp-dir.js";
@@ -69,10 +69,13 @@ export async function executeBashWithOperations(command, cwd, operations, option
69
69
  }
70
70
  };
71
71
  const decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
72
- const onData = (data, channel = "stdout") => {
73
- totalBytes += data.length;
72
+ const pendingAnsi = { stdout: "", stderr: "" };
73
+ const appendText = (rawText, channel) => {
74
74
  // Sanitize: strip ANSI, replace binary garbage, normalize newlines
75
- const text = sanitizeBinaryOutput(stripAnsi(decoders[channel].decode(data, { stream: true }))).replace(/\r/g, "");
75
+ const text = sanitizeBinaryOutput(stripAnsi(rawText)).replace(/\r/g, "");
76
+ if (!text) {
77
+ return;
78
+ }
76
79
  // Start writing to temp file if exceeds threshold
77
80
  if (totalBytes > DEFAULT_MAX_BYTES) {
78
81
  ensureTempFile();
@@ -92,6 +95,19 @@ export async function executeBashWithOperations(command, cwd, operations, option
92
95
  options.onChunk(text, channel);
93
96
  }
94
97
  };
98
+ const onData = (data, channel = "stdout") => {
99
+ totalBytes += data.length;
100
+ const { complete, pending } = splitIncompleteAnsiSuffix(pendingAnsi[channel] + decoders[channel].decode(data, { stream: true }));
101
+ pendingAnsi[channel] = pending;
102
+ appendText(complete, channel);
103
+ };
104
+ const flushOutput = () => {
105
+ for (const channel of ["stdout", "stderr"]) {
106
+ const rest = pendingAnsi[channel] + decoders[channel].decode();
107
+ pendingAnsi[channel] = "";
108
+ appendText(rest, channel);
109
+ }
110
+ };
95
111
  try {
96
112
  const result = await operations.exec(command, cwd, {
97
113
  onData,
@@ -99,6 +115,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
99
115
  env: options?.env,
100
116
  pty: options?.pty,
101
117
  });
118
+ flushOutput();
102
119
  const fullOutput = outputChunks.join("");
103
120
  const truncationResult = truncateTail(fullOutput);
104
121
  if (truncationResult.truncated) {
@@ -117,6 +134,7 @@ export async function executeBashWithOperations(command, cwd, operations, option
117
134
  catch (err) {
118
135
  // Check if it was an abort
119
136
  if (options?.signal?.aborted) {
137
+ flushOutput();
120
138
  const fullOutput = outputChunks.join("");
121
139
  const truncationResult = truncateTail(fullOutput);
122
140
  if (truncationResult.truncated) {
@@ -1 +1 @@
1
- {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAmCtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf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,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,MAAM,cAAc,EAAE,CAAC;QAEvB,MAAM,GAAG,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { APP_NAME } from \"../config.js\";\nimport { stripAnsi } from \"../utils/ansi.js\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations, BashOutputChannel } from \"./tools/bash.js\";\nimport { PersistedOutputFile } from \"./tools/persisted-output-file.ts\";\nimport { ensureSessionTempDir } from \"./tools/session-temp-dir.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized), preserving the source channel. */\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Complete environment for the execution backend. */\n\tenv?: NodeJS.ProcessEnv;\n\t/** Run with PTY handling when supported by the operations backend */\n\tpty?: boolean;\n\t/**\n\t * Session-scoped directory for the overflow log. Defaults to the active\n\t * session's temp directory so the log is reaped with that session.\n\t */\n\tsessionTempDir?: string;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFile: PersistedOutputFile | undefined;\n\tlet totalBytes = 0;\n\n\tlet tempFileUnavailable = false;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath || tempFileUnavailable) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst dir = ensureSessionTempDir(options?.sessionTempDir);\n\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\ttempFilePath = join(dir, `${APP_NAME}-bash-${id}.log`);\n\t\t\ttempFile = new PersistedOutputFile(tempFilePath);\n\t\t} catch {\n\t\t\t// The session temp directory was refused (see ensureTempDir). Run without\n\t\t\t// an overflow log rather than advertising a path outside the owned tree.\n\t\t\ttempFileUnavailable = true;\n\t\t\ttempFilePath = undefined;\n\t\t\ttempFile = undefined;\n\t\t\treturn;\n\t\t}\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFile.write(chunk);\n\t\t}\n\t};\n\n\t/**\n\t * Close the overflow log and confirm it landed. A spill file that failed to\n\t * write must not be advertised: `fullOutputPath` is dropped instead, so the\n\t * `Full output:` contract never points at a file that is not there.\n\t */\n\tconst finishTempFile = async () => {\n\t\tconst file = tempFile;\n\t\tif (!file) {\n\t\t\treturn;\n\t\t}\n\t\ttempFile = undefined;\n\t\ttry {\n\t\t\tawait file.close();\n\t\t} catch {\n\t\t\ttempFilePath = undefined;\n\t\t}\n\t};\n\n\tconst decoders: Record<BashOutputChannel, TextDecoder> = { stdout: new TextDecoder(), stderr: new TextDecoder() };\n\tconst onData = (data: Buffer, channel: BashOutputChannel = \"stdout\") => {\n\t\ttotalBytes += data.length;\n\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(decoders[channel].decode(data, { stream: true }))).replace(/\\r/g, \"\");\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFile) {\n\t\t\ttempFile.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text, channel);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\tenv: options?.env,\n\t\t\tpty: options?.pty,\n\t\t});\n\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tawait finishTempFile();\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tawait finishTempFile();\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tawait finishTempFile();\n\n\t\tthrow err;\n\t}\n}\n"]}
1
+ {"version":3,"file":"bash-executor.js","sourceRoot":"","sources":["../../src/core/bash-executor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,yBAAyB,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAEzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAmCtE,+EAA+E;AAC/E,iBAAiB;AACjB,+EAA+E;AAE/E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC9C,OAAe,EACf,GAAW,EACX,UAA0B,EAC1B,OAA6B;IAE7B,MAAM,YAAY,GAAa,EAAE,CAAC;IAClC,IAAI,WAAW,GAAG,CAAC,CAAC;IACpB,MAAM,cAAc,GAAG,iBAAiB,GAAG,CAAC,CAAC;IAE7C,IAAI,YAAgC,CAAC;IACrC,IAAI,QAAyC,CAAC;IAC9C,IAAI,UAAU,GAAG,CAAC,CAAC;IAEnB,IAAI,mBAAmB,GAAG,KAAK,CAAC;IAEhC,MAAM,cAAc,GAAG,GAAG,EAAE;QAC3B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AAc,EAAE,YAAY;SAC5B,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACd,2BAA2B;QAC3B,IAAI,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;YAC9B,WAAW,EAAE,CAAC;YACd,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YACzC,MAAM,gBAAgB,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC;YAClD,IAAI,gBAAgB,CAAC,SAAS,EAAE,CAAC;gBAChC,cAAc,EAAE,CAAC;YAClB,CAAC;YACD,MAAM,cAAc,EAAE,CAAC;YACvB,OAAO;gBACN,MAAM,EAAE,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU;gBAC1E,QAAQ,EAAE,SAAS;gBACnB,SAAS,EAAE,IAAI;gBACf,SAAS,EAAE,gBAAgB,CAAC,SAAS;gBACrC,cAAc,EAAE,YAAY;aAC5B,CAAC;QACH,CAAC;QAED,MAAM,cAAc,EAAE,CAAC;QAEvB,MAAM,GAAG,CAAC;IACX,CAAC;AACF,CAAC","sourcesContent":["/**\n * Bash command execution with streaming support and cancellation.\n *\n * This module provides a unified bash execution implementation used by:\n * - AgentSession.executeBash() for interactive and RPC modes\n * - Direct calls from modes that need bash execution\n */\n\nimport { randomBytes } from \"node:crypto\";\nimport { join } from \"node:path\";\nimport { APP_NAME } from \"../config.js\";\nimport { splitIncompleteAnsiSuffix, stripAnsi } from \"../utils/ansi.js\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { BashOperations, BashOutputChannel } from \"./tools/bash.js\";\nimport { PersistedOutputFile } from \"./tools/persisted-output-file.ts\";\nimport { ensureSessionTempDir } from \"./tools/session-temp-dir.ts\";\nimport { DEFAULT_MAX_BYTES, truncateTail } from \"./tools/truncate.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BashExecutorOptions {\n\t/** Callback for streaming output chunks (already sanitized), preserving the source channel. */\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void;\n\t/** AbortSignal for cancellation */\n\tsignal?: AbortSignal;\n\t/** Complete environment for the execution backend. */\n\tenv?: NodeJS.ProcessEnv;\n\t/** Run with PTY handling when supported by the operations backend */\n\tpty?: boolean;\n\t/**\n\t * Session-scoped directory for the overflow log. Defaults to the active\n\t * session's temp directory so the log is reaped with that session.\n\t */\n\tsessionTempDir?: string;\n}\n\nexport interface BashResult {\n\t/** Combined stdout + stderr output (sanitized, possibly truncated) */\n\toutput: string;\n\t/** Process exit code (undefined if killed/cancelled) */\n\texitCode: number | undefined;\n\t/** Whether the command was cancelled via signal */\n\tcancelled: boolean;\n\t/** Whether the output was truncated */\n\ttruncated: boolean;\n\t/** Path to temp file containing full output (if output exceeded truncation threshold) */\n\tfullOutputPath?: string;\n}\n\n// ============================================================================\n// Implementation\n// ============================================================================\n\n/**\n * Execute a bash command using custom BashOperations.\n * Used for remote execution (SSH, containers, etc.).\n */\nexport async function executeBashWithOperations(\n\tcommand: string,\n\tcwd: string,\n\toperations: BashOperations,\n\toptions?: BashExecutorOptions,\n): Promise<BashResult> {\n\tconst outputChunks: string[] = [];\n\tlet outputBytes = 0;\n\tconst maxOutputBytes = DEFAULT_MAX_BYTES * 2;\n\n\tlet tempFilePath: string | undefined;\n\tlet tempFile: PersistedOutputFile | undefined;\n\tlet totalBytes = 0;\n\n\tlet tempFileUnavailable = false;\n\n\tconst ensureTempFile = () => {\n\t\tif (tempFilePath || tempFileUnavailable) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tconst dir = ensureSessionTempDir(options?.sessionTempDir);\n\t\t\tconst id = randomBytes(8).toString(\"hex\");\n\t\t\ttempFilePath = join(dir, `${APP_NAME}-bash-${id}.log`);\n\t\t\ttempFile = new PersistedOutputFile(tempFilePath);\n\t\t} catch {\n\t\t\t// The session temp directory was refused (see ensureTempDir). Run without\n\t\t\t// an overflow log rather than advertising a path outside the owned tree.\n\t\t\ttempFileUnavailable = true;\n\t\t\ttempFilePath = undefined;\n\t\t\ttempFile = undefined;\n\t\t\treturn;\n\t\t}\n\t\tfor (const chunk of outputChunks) {\n\t\t\ttempFile.write(chunk);\n\t\t}\n\t};\n\n\t/**\n\t * Close the overflow log and confirm it landed. A spill file that failed to\n\t * write must not be advertised: `fullOutputPath` is dropped instead, so the\n\t * `Full output:` contract never points at a file that is not there.\n\t */\n\tconst finishTempFile = async () => {\n\t\tconst file = tempFile;\n\t\tif (!file) {\n\t\t\treturn;\n\t\t}\n\t\ttempFile = undefined;\n\t\ttry {\n\t\t\tawait file.close();\n\t\t} catch {\n\t\t\ttempFilePath = undefined;\n\t\t}\n\t};\n\n\tconst decoders: Record<BashOutputChannel, TextDecoder> = { stdout: new TextDecoder(), stderr: new TextDecoder() };\n\tconst pendingAnsi: Record<BashOutputChannel, string> = { stdout: \"\", stderr: \"\" };\n\n\tconst appendText = (rawText: string, channel: BashOutputChannel) => {\n\t\t// Sanitize: strip ANSI, replace binary garbage, normalize newlines\n\t\tconst text = sanitizeBinaryOutput(stripAnsi(rawText)).replace(/\\r/g, \"\");\n\t\tif (!text) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Start writing to temp file if exceeds threshold\n\t\tif (totalBytes > DEFAULT_MAX_BYTES) {\n\t\t\tensureTempFile();\n\t\t}\n\n\t\tif (tempFile) {\n\t\t\ttempFile.write(text);\n\t\t}\n\n\t\t// Keep rolling buffer\n\t\toutputChunks.push(text);\n\t\toutputBytes += text.length;\n\t\twhile (outputBytes > maxOutputBytes && outputChunks.length > 1) {\n\t\t\tconst removed = outputChunks.shift()!;\n\t\t\toutputBytes -= removed.length;\n\t\t}\n\n\t\t// Stream to callback\n\t\tif (options?.onChunk) {\n\t\t\toptions.onChunk(text, channel);\n\t\t}\n\t};\n\n\tconst onData = (data: Buffer, channel: BashOutputChannel = \"stdout\") => {\n\t\ttotalBytes += data.length;\n\t\tconst { complete, pending } = splitIncompleteAnsiSuffix(\n\t\t\tpendingAnsi[channel] + decoders[channel].decode(data, { stream: true }),\n\t\t);\n\t\tpendingAnsi[channel] = pending;\n\t\tappendText(complete, channel);\n\t};\n\n\tconst flushOutput = () => {\n\t\tfor (const channel of [\"stdout\", \"stderr\"] as const) {\n\t\t\tconst rest = pendingAnsi[channel] + decoders[channel].decode();\n\t\t\tpendingAnsi[channel] = \"\";\n\t\t\tappendText(rest, channel);\n\t\t}\n\t};\n\n\ttry {\n\t\tconst result = await operations.exec(command, cwd, {\n\t\t\tonData,\n\t\t\tsignal: options?.signal,\n\t\t\tenv: options?.env,\n\t\t\tpty: options?.pty,\n\t\t});\n\n\t\tflushOutput();\n\t\tconst fullOutput = outputChunks.join(\"\");\n\t\tconst truncationResult = truncateTail(fullOutput);\n\t\tif (truncationResult.truncated) {\n\t\t\tensureTempFile();\n\t\t}\n\t\tawait finishTempFile();\n\t\tconst cancelled = options?.signal?.aborted ?? false;\n\n\t\treturn {\n\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\texitCode: cancelled ? undefined : (result.exitCode ?? undefined),\n\t\t\tcancelled,\n\t\t\ttruncated: truncationResult.truncated,\n\t\t\tfullOutputPath: tempFilePath,\n\t\t};\n\t} catch (err) {\n\t\t// Check if it was an abort\n\t\tif (options?.signal?.aborted) {\n\t\t\tflushOutput();\n\t\t\tconst fullOutput = outputChunks.join(\"\");\n\t\t\tconst truncationResult = truncateTail(fullOutput);\n\t\t\tif (truncationResult.truncated) {\n\t\t\t\tensureTempFile();\n\t\t\t}\n\t\t\tawait finishTempFile();\n\t\t\treturn {\n\t\t\t\toutput: truncationResult.truncated ? truncationResult.content : fullOutput,\n\t\t\t\texitCode: undefined,\n\t\t\t\tcancelled: true,\n\t\t\t\ttruncated: truncationResult.truncated,\n\t\t\t\tfullOutputPath: tempFilePath,\n\t\t\t};\n\t\t}\n\n\t\tawait finishTempFile();\n\n\t\tthrow err;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"child-session-options.d.ts","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAGhE,2FAA2F;AAC3F,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,yBAAyB,KAAK,yBAAyB,CAAC;AAO5G,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,yBAAyB,EACjC,KAAK,EAAE,yBAAyB,EAChC,kBAAkB,GAAE,SAAS,MAAM,EAAO,GACxC,yBAAyB,CAmC3B"}
1
+ {"version":3,"file":"child-session-options.d.ts","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gBAAgB,CAAC;AAKhE,2FAA2F;AAC3F,MAAM,MAAM,2BAA2B,GAAG,CAAC,OAAO,EAAE,yBAAyB,KAAK,yBAAyB,CAAC;AAO5G,wBAAgB,0BAA0B,CACzC,MAAM,EAAE,yBAAyB,EACjC,KAAK,EAAE,yBAAyB,EAChC,kBAAkB,GAAE,SAAS,MAAM,EAAO,GACxC,yBAAyB,CAoD3B"}
@@ -1,5 +1,7 @@
1
1
  import { resolve } from "node:path";
2
+ import { applyToolModifiers, getToolListError, isToolModifier } from "./settings-merge.js";
2
3
  import { createToolNameMatcher, isMcpToolName } from "./tool-selection.js";
4
+ import { allToolNames, getDefaultToolNames } from "./tools/index.js";
3
5
  /** Optional undefined values retain inheritance; null and other explicit values do not. */
4
6
  function definedOptions(options) {
5
7
  return Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined));
@@ -13,10 +15,23 @@ export function inheritChildSessionOptions(parent, child, availableToolNames = [
13
15
  const ceiling = parent.noTools === "all" ? [] : parent.tools;
14
16
  const parentAllows = createToolNameMatcher(ceiling ?? []);
15
17
  const parentNamesMcp = createToolNameMatcher((ceiling ?? []).filter((entry) => entry.startsWith("mcp__")));
16
- const childAllows = child.tools === undefined ? undefined : createToolNameMatcher(child.tools);
18
+ const toolListError = child.tools ? getToolListError(child.tools) : undefined;
19
+ if (toolListError)
20
+ throw new Error(`Invalid tools option: ${toolListError}`);
21
+ const codingToolNames = new Set(allToolNames);
22
+ const inheritedCustomToolNames = [...new Set([...availableToolNames, ...(ceiling ?? [])])].filter((name) => !name.includes("*") && !codingToolNames.has(name) && parentAllows(name));
23
+ const childToolNames = child.tools?.some(isToolModifier)
24
+ ? applyToolModifiers([
25
+ ...((child.noTools ?? parent.noTools)
26
+ ? []
27
+ : ((child.settingsManager ?? parent.settingsManager)?.getDefaultTools() ?? getDefaultToolNames())),
28
+ ...inheritedCustomToolNames,
29
+ ], child.tools)
30
+ : child.tools;
31
+ const childAllows = childToolNames === undefined ? undefined : createToolNameMatcher(childToolNames);
17
32
  const tools = ceiling === undefined
18
33
  ? child.tools
19
- : [...new Set([...availableToolNames, ...ceiling, ...(child.tools ?? [])])].filter((name) => !name.includes("*") &&
34
+ : [...new Set([...availableToolNames, ...ceiling, ...(childToolNames ?? [])])].filter((name) => !name.includes("*") &&
20
35
  parentAllows(name) &&
21
36
  (!childAllows || childAllows(name)) &&
22
37
  (!isMcpToolName(name) || ceiling.includes(name) || parentNamesMcp(name)));
@@ -1 +1 @@
1
- {"version":3,"file":"child-session-options.js","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAK3E,2FAA2F;AAC3F,SAAS,cAAc,CAAmB,OAAsB;IAC/D,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAe,CAAC;AACnH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ent":["import { resolve } from \"node:path\";\nimport type { CreateAgentSessionOptions } from \"./sdk-types.ts\";\nimport { createToolNameMatcher, isMcpToolName } from \"./tool-selection.ts\";\n\n/** Internal owner-bound adapter seam. Does not admit work or transfer parent authority. */\nexport type ChildSessionOptionsResolver = (options: CreateAgentSessionOptions) => CreateAgentSessionOptions;\n\n/** Optional undefined values retain inheritance; null and other explicit values do not. */\nfunction definedOptions<T extends object>(options: T | undefined): Partial<T> {\n\treturn Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\nexport function inheritChildSessionOptions(\n\tparent: CreateAgentSessionOptions,\n\tchild: CreateAgentSessionOptions,\n\tavailableToolNames: readonly string[] = [],\n): CreateAgentSessionOptions {\n\tconst builtins = { ...parent.builtins, ...definedOptions(child.builtins) };\n\tfor (const name of [\"workflows\", \"subagents\", \"mcp\", \"web-access\", \"intercom\"] as const) {\n\t\tif (parent.builtins?.[name] === false) builtins[name] = false;\n\t}\n\tconst ceiling = parent.noTools === \"all\" ? [] : parent.tools;\n\tconst parentAllows = createToolNameMatcher(ceiling ?? []);\n\tconst parentNamesMcp = createToolNameMatcher((ceiling ?? []).filter((entry) => entry.startsWith(\"mcp__\")));\n\tconst childAllows = child.tools === undefined ? undefined : createToolNameMatcher(child.tools);\n\tconst tools =\n\t\tceiling === undefined\n\t\t\t? child.tools\n\t\t\t: [...new Set([...availableToolNames, ...ceiling, ...(child.tools ?? [])])].filter(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!name.includes(\"*\") &&\n\t\t\t\t\t\tparentAllows(name) &&\n\t\t\t\t\t\t(!childAllows || childAllows(name)) &&\n\t\t\t\t\t\t(!isMcpToolName(name) || ceiling.includes(name) || parentNamesMcp(name)),\n\t\t\t\t);\n\tconst parentGate = parent.isFallbackModelAllowed;\n\tconst childGate = child.isFallbackModelAllowed;\n\treturn {\n\t\t...parent,\n\t\t...definedOptions(child),\n\t\tcwd: resolve(parent.cwd!, child.cwd ?? child.sessionManager?.getCwd() ?? \".\"),\n\t\tbuiltins,\n\t\ttools,\n\t\texcludedTools: [...(parent.excludedTools ?? []), ...(child.excludedTools ?? [])],\n\t\tnoTools: parent.noTools === \"all\" ? \"all\" : (child.noTools ?? parent.noTools),\n\t\textensionBindings: { ...parent.extensionBindings, ...definedOptions(child.extensionBindings) },\n\t\tisFallbackModelAllowed:\n\t\t\tparentGate && childGate\n\t\t\t\t? (model, effort) => parentGate(model, effort) && childGate(model, effort)\n\t\t\t\t: (parentGate ?? childGate),\n\t};\n}\n"]}
1
+ {"version":3,"file":"child-session-options.js","sourceRoot":"","sources":["../../src/core/child-session-options.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC3F,OAAO,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAC3E,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAKrE,2FAA2F;AAC3F,SAAS,cAAc,CAAmB,OAAsB;IAC/D,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAAe,CAAC;AACnH,CAAC;AAED,MAAM,UAAU,0BAA0B,CACzC,MAAiC,EACjC,KAAgC,EAChC,kBAAkB,GAAsB,EAAE;IAE1C,MAAM,QAAQ,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,GAAG,cAAc,CAAC,KAAK,CAAC,QAAQ,CAAC,EAAE,CAAC;IAC3E,KAAK,MAAM,IAAI,IAAI,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,EAAE,YAAY,EAAE,UAAU,CAAU,EAAE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;QAC7E,QAAQ;QACR,KAAK;QACL,aAAa,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,EAAE,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC,CAAC;QAChF,OAAO,EAAE,MAAM,CAAC,OAAO,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,IAAI,MAAM,CAAC,OAAO,CAAC;QAC7E,iBAAiB,EAAE,EAAE,GAAG,MAAM,CAAC,iBAAiB,EAAE,GAAG,cAAc,CAAC,KAAK,CAAC,iBAAiB,CAAC,EAAE;QAC9F,sBAAsB,EACrB,UAAU,IAAI,SAAS;YACtB,CAAC,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC;YAC1E,CAAC,CAAC,CAAC,UAAU,IAAI,SAAS,CAAC;KAC7B,CAAC;AACH,CAAC","sourcesContent":["import { resolve } from \"node:path\";\nimport type { CreateAgentSessionOptions } from \"./sdk-types.ts\";\nimport { applyToolModifiers, getToolListError, isToolModifier } from \"./settings-merge.js\";\nimport { createToolNameMatcher, isMcpToolName } from \"./tool-selection.ts\";\nimport { allToolNames, getDefaultToolNames } from \"./tools/index.js\";\n\n/** Internal owner-bound adapter seam. Does not admit work or transfer parent authority. */\nexport type ChildSessionOptionsResolver = (options: CreateAgentSessionOptions) => CreateAgentSessionOptions;\n\n/** Optional undefined values retain inheritance; null and other explicit values do not. */\nfunction definedOptions<T extends object>(options: T | undefined): Partial<T> {\n\treturn Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== undefined)) as Partial<T>;\n}\n\nexport function inheritChildSessionOptions(\n\tparent: CreateAgentSessionOptions,\n\tchild: CreateAgentSessionOptions,\n\tavailableToolNames: readonly string[] = [],\n): CreateAgentSessionOptions {\n\tconst builtins = { ...parent.builtins, ...definedOptions(child.builtins) };\n\tfor (const name of [\"workflows\", \"subagents\", \"mcp\", \"web-access\", \"intercom\"] as const) {\n\t\tif (parent.builtins?.[name] === false) builtins[name] = false;\n\t}\n\tconst ceiling = parent.noTools === \"all\" ? [] : parent.tools;\n\tconst parentAllows = createToolNameMatcher(ceiling ?? []);\n\tconst parentNamesMcp = createToolNameMatcher((ceiling ?? []).filter((entry) => entry.startsWith(\"mcp__\")));\n\tconst toolListError = child.tools ? getToolListError(child.tools) : undefined;\n\tif (toolListError) throw new Error(`Invalid tools option: ${toolListError}`);\n\tconst codingToolNames = new Set<string>(allToolNames);\n\tconst inheritedCustomToolNames = [...new Set([...availableToolNames, ...(ceiling ?? [])])].filter(\n\t\t(name) => !name.includes(\"*\") && !codingToolNames.has(name) && parentAllows(name),\n\t);\n\tconst childToolNames = child.tools?.some(isToolModifier)\n\t\t? applyToolModifiers(\n\t\t\t\t[\n\t\t\t\t\t...((child.noTools ?? parent.noTools)\n\t\t\t\t\t\t? []\n\t\t\t\t\t\t: ((child.settingsManager ?? parent.settingsManager)?.getDefaultTools() ?? getDefaultToolNames())),\n\t\t\t\t\t...inheritedCustomToolNames,\n\t\t\t\t],\n\t\t\t\tchild.tools,\n\t\t\t)\n\t\t: child.tools;\n\tconst childAllows = childToolNames === undefined ? undefined : createToolNameMatcher(childToolNames);\n\tconst tools =\n\t\tceiling === undefined\n\t\t\t? child.tools\n\t\t\t: [...new Set([...availableToolNames, ...ceiling, ...(childToolNames ?? [])])].filter(\n\t\t\t\t\t(name) =>\n\t\t\t\t\t\t!name.includes(\"*\") &&\n\t\t\t\t\t\tparentAllows(name) &&\n\t\t\t\t\t\t(!childAllows || childAllows(name)) &&\n\t\t\t\t\t\t(!isMcpToolName(name) || ceiling.includes(name) || parentNamesMcp(name)),\n\t\t\t\t);\n\tconst parentGate = parent.isFallbackModelAllowed;\n\tconst childGate = child.isFallbackModelAllowed;\n\treturn {\n\t\t...parent,\n\t\t...definedOptions(child),\n\t\tcwd: resolve(parent.cwd!, child.cwd ?? child.sessionManager?.getCwd() ?? \".\"),\n\t\tbuiltins,\n\t\ttools,\n\t\texcludedTools: [...(parent.excludedTools ?? []), ...(child.excludedTools ?? [])],\n\t\tnoTools: parent.noTools === \"all\" ? \"all\" : (child.noTools ?? parent.noTools),\n\t\textensionBindings: { ...parent.extensionBindings, ...definedOptions(child.extensionBindings) },\n\t\tisFallbackModelAllowed:\n\t\t\tparentGate && childGate\n\t\t\t\t? (model, effort) => parentGate(model, effort) && childGate(model, effort)\n\t\t\t\t: (parentGate ?? childGate),\n\t};\n}\n"]}
@@ -2,10 +2,9 @@ import { loadVirtualModules } from "./loader-host-modules.js";
2
2
  import type { ExtensionFactory } from "./types.ts";
3
3
  export { getVirtualModules } from "./loader-host-modules.js";
4
4
  /**
5
- * Persistent on-disk cache for jiti-transpiled extension modules.
6
- * jiti keys cache entries by source-content hash, so entries self-invalidate
7
- * when extension sources change; stale sibling version dirs are pruned
8
- * in the background.
5
+ * Persistent on-disk cache for transpiled extension modules. Entries are keyed
6
+ * by source content and resolved TypeScript siblings, so they self-invalidate
7
+ * when either changes; stale sibling version dirs are pruned in the background.
9
8
  */
10
9
  declare function getTranspileCacheDir(): string;
11
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"loader-virtual-modules.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/loader-virtual-modules.ts"],"names":[],"mappings":"AAWA,OAAO,EAAqB,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEjF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAc7D;;;;;GAKG;AACH,iBAAS,oBAAoB,IAAI,MAAM,CAMtC;AAiBD;;;;;GAKG;AACH,MAAM,WAAW,sBAAsB;IACtC,OAAO,EAAE,CAAC,CAAC;IACX,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,MAA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duleDirFromMetaUrl } from "../../utils/split-launcher.js";
18
18
  import { installHostModuleBridge } from "./host-module-bridge.js";
19
19
  import { getVirtualModules, loadVirtualModules } from "./loader-host-modules.js";
20
20
  import { isNativeBuiltinExtensionPath } from "./native-builtin-entries.js";
21
+ import { createTypeScriptSourceSpecifierTransform } from "./ts-source-specifiers.js";
21
22
  export { getVirtualModules } from "./loader-host-modules.js";
22
23
  const require = createRequire(import.meta.url);
23
24
  let _aliases = null;
24
25
  let _transpileCacheDir = null;
25
26
  let createJitiPromise;
27
+ let typeScriptSourceSpecifierTransform;
26
28
  function getCreateJiti() {
27
29
  createJitiPromise ??= (isBunBinary || isBundledBuild ? import("./jiti-static-loader.js") : import("./jiti-loader.js")).then((module) => module.createJiti);
28
30
  return createJitiPromise;
29
31
  }
32
+ function getTypeScriptSourceSpecifierTransform(createJitiImpl) {
33
+ typeScriptSourceSpecifierTransform ??= createTypeScriptSourceSpecifierTransform(createJitiImpl, resolutionBaseUrl(import.meta.url), getTranspileCacheDir);
34
+ return typeScriptSourceSpecifierTransform;
35
+ }
30
36
  /**
31
- * Persistent on-disk cache for jiti-transpiled extension modules.
32
- * jiti keys cache entries by source-content hash, so entries self-invalidate
33
- * when extension sources change; stale sibling version dirs are pruned
34
- * in the background.
37
+ * Persistent on-disk cache for transpiled extension modules. Entries are keyed
38
+ * by source content and resolved TypeScript siblings, so they self-invalidate
39
+ * when either changes; stale sibling version dirs are pruned in the background.
35
40
  */
36
41
  function getTranspileCacheDir() {
37
42
  if (_transpileCacheDir)
@@ -373,6 +378,7 @@ function getAliases() {
373
378
  const piAiEntry = resolveWorkspaceOrImport("ai/dist/compat.js", "@bastani/pi-ai");
374
379
  const piAiCodexResponsesEntry = resolveWorkspaceOrImport("ai/dist/api/openai-codex-responses.js", "@bastani/pi-ai");
375
380
  const piAiLlamaCppClassifyEntry = resolveWorkspaceOrImport("ai/dist/api/llama-cpp-classify.lazy.js", "@bastani/pi-ai");
381
+ const piAiTypesafeSystemOneEntry = resolveWorkspaceOrImport("ai/dist/api/typesafe-system-one.lazy.js", "@bastani/pi-ai");
376
382
  const piAiOauthEntry = resolveWorkspaceOrImport("ai/dist/oauth.js", "@bastani/pi-ai");
377
383
  const piAiModelsEntry = resolveWorkspaceOrImport("ai/dist/models.js", "@bastani/pi-ai");
378
384
  const piAiProvidersEntry = resolveWorkspaceOrImport("ai/dist/providers/all.js", "@bastani/pi-ai");
@@ -389,6 +395,7 @@ function getAliases() {
389
395
  "@earendil-works/pi-tui": piTuiEntry,
390
396
  "@bastani/pi-ai/api/openai-codex-responses": piAiCodexResponsesEntry,
391
397
  "@bastani/pi-ai/api/llama-cpp-classify.lazy": piAiLlamaCppClassifyEntry,
398
+ "@bastani/pi-ai/api/typesafe-system-one.lazy": piAiTypesafeSystemOneEntry,
392
399
  "@bastani/pi-ai/oauth": piAiOauthEntry,
393
400
  "@bastani/pi-ai/models": piAiModelsEntry,
394
401
  "@bastani/pi-ai/providers/all": piAiProvidersEntry,
@@ -449,11 +456,9 @@ async function importExtensionModule(extensionPath, cacheToken, forceTransformed
449
456
  const createJitiImpl = await getCreateJiti();
450
457
  const jiti = createJitiImpl(resolutionBaseUrl(import.meta.url), {
451
458
  moduleCache: false,
452
- ...(forceTransformedImports
453
- ? { fsCache: getTranspileCacheDir(), tryNative: false }
454
- : isWindows
455
- ? { fsCache: getTranspileCacheDir() }
456
- : {}),
459
+ fsCache: false,
460
+ transform: getTypeScriptSourceSpecifierTransform(createJitiImpl),
461
+ ...(forceTransformedImports ? { tryNative: false } : {}),
457
462
  // A first native import can fall back to transformation too. Always share
458
463
  // the live host instead of re-evaluating its graph through source aliases.
459
464
  virtualModules: await getVirtualModules(),