@bastani/atomic 0.9.37 → 0.9.38-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +6 -0
- package/dist/builtin/workflows/builtin/{chunk-rhkg3d8e.js → chunk-3n2bnz64.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-3xffzzbg.js → chunk-ad83gc5p.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-7fvrnzhb.js → chunk-x6az1sxp.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-8c3ae7tt.js → chunk-ymwq372z.js} +1 -1
- package/dist/builtin/workflows/builtin/goal.js +2 -2
- package/dist/builtin/workflows/builtin/index.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +2 -2
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +7 -0
- package/dist/builtin/workflows/src/index.js +7 -0
- package/dist/cli/credential-print.d.ts.map +1 -1
- package/dist/cli/credential-print.js +4 -4
- package/dist/cli/credential-print.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +19 -5
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +2 -2
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-retry.js +1 -1
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-state.d.ts +4 -6
- package/dist/core/agent-session-state.d.ts.map +1 -1
- package/dist/core/agent-session-state.js +13 -8
- package/dist/core/agent-session-state.js.map +1 -1
- package/dist/core/agent-session-tool-registry.d.ts.map +1 -1
- package/dist/core/agent-session-tool-registry.js +3 -1
- package/dist/core/agent-session-tool-registry.js.map +1 -1
- package/dist/core/agent-session.js +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/export-html/template-js/message-tools.js +20 -7
- package/dist/core/export-html/template-js/tree-filter-render.js +1 -9
- package/dist/core/export-html/template.js +21 -16
- package/dist/core/model-config.d.ts +9 -9
- package/dist/core/model-fallback-failures.d.ts.map +1 -1
- package/dist/core/model-fallback-failures.js +3 -1
- package/dist/core/model-fallback-failures.js.map +1 -1
- package/dist/core/model-resolver-cli.d.ts +2 -0
- package/dist/core/model-resolver-cli.d.ts.map +1 -1
- package/dist/core/model-resolver-cli.js +47 -143
- package/dist/core/model-resolver-cli.js.map +1 -1
- package/dist/core/model-resolver-patterns.d.ts +48 -22
- package/dist/core/model-resolver-patterns.d.ts.map +1 -1
- package/dist/core/model-resolver-patterns.js +154 -105
- package/dist/core/model-resolver-patterns.js.map +1 -1
- package/dist/core/model-resolver-scope.d.ts +6 -9
- package/dist/core/model-resolver-scope.d.ts.map +1 -1
- package/dist/core/model-resolver-scope.js +51 -53
- package/dist/core/model-resolver-scope.js.map +1 -1
- package/dist/core/model-resolver-types.d.ts +0 -6
- package/dist/core/model-resolver-types.d.ts.map +1 -1
- package/dist/core/model-resolver-types.js.map +1 -1
- package/dist/core/model-resolver.d.ts +3 -2
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +1 -1
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +6 -2
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/retry-policy.d.ts +5 -2
- package/dist/core/retry-policy.d.ts.map +1 -1
- package/dist/core/retry-policy.js +4 -3
- package/dist/core/retry-policy.js.map +1 -1
- package/dist/core/settings-manager-basic-accessors.d.ts +1 -0
- package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
- package/dist/core/settings-manager-basic-accessors.js +1 -0
- package/dist/core/settings-manager-basic-accessors.js.map +1 -1
- package/dist/core/tools/malformed-tool-arguments.d.ts +3 -0
- package/dist/core/tools/malformed-tool-arguments.d.ts.map +1 -0
- package/dist/core/tools/malformed-tool-arguments.js +23 -0
- package/dist/core/tools/malformed-tool-arguments.js.map +1 -0
- package/dist/core/tools/render-utils.d.ts +2 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +19 -0
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main-session-options.d.ts.map +1 -1
- package/dist/main-session-options.js +1 -0
- package/dist/main-session-options.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.js +2 -9
- package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
- package/docs/docs.json +2 -1
- package/docs/extensions/ui.md +10 -0
- package/docs/llama-cpp.md +2 -0
- package/docs/models/reference.md +7 -0
- package/docs/nvidia-rtx-llama-cpp.md +101 -0
- package/docs/prompt-templates.md +2 -0
- package/docs/providers.md +4 -0
- package/docs/reference/cli.md +3 -3
- package/docs/sessions.md +4 -0
- package/docs/settings.md +3 -3
- package/docs/tools.md +2 -0
- package/docs/workflows/api-reference.md +2 -0
- package/examples/extensions/minimal-mode.ts +1 -8
- package/examples/extensions/subagent/display.ts +4 -6
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
- package/schemas/models.schema.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolResultMessage,\n} from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tModelMutationOptions,\n\tPromptDisposition,\n\tPromptOptions,\n\tQueuedInputDisposition,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.js\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tAgentActivityOutcome,\n\tBoundaryContextPreview,\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionBoundaryDraft,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.js\";\nimport type { SessionWorkflows } from \"./extensions/workflow-run-control.js\";\nimport type { SessionWorkflowsHandle } from \"./extensions/workflow-run-control-hub.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ExtensionProviderTransaction, ModelRuntime } from \"./model-runtime.js\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionEntry, SessionManager, SessionSummaryEntry } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { NormalizedBuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { ToolStatusReport } from \"./tool-status.js\";\nimport type { BashOperations } from \"./tools/bash.js\";\nimport type { ToolExecutionScheduler } from \"./tools/tool-concurrency.ts\";\n\nexport interface SessionCompactOptions extends Partial<VerbatimCompactionParameters> {\n\t/** Exact `provider/model` ID for this run only; overrides the `compactionModel` setting without saving it. */\n\tcompactionModel?: string;\n}\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\tcompactionModel?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Reports when a session_before_compact override becomes the active compaction source. */\n\tonCompactionSource?: (fromExtension: boolean) => void;\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Outcome of an automatic compaction admission and persistence attempt. */\nexport type AutoCompactionRunOutcome = \"compacted\" | \"not_compactable\" | \"deferred\" | \"failed\";\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n\tpreserveRunner?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.js\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.js\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly sessionSummary: SessionSummaryEntry | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\t/** Typed management of the workflow runs this session owns. */\n\treadonly workflows: SessionWorkflows;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t\tsignal?: AbortSignal,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_installAgentRequestProjection(): void;\n\t_installAgentBoundaryHooks(): void;\n\t_refreshFinalizedContext(): void;\n\t_projectFinalizedMessages(): AgentMessage[];\n\trefreshContext(): void;\n\t_dispatchTurnEndBoundary(\n\t\tmessage: AssistantMessage,\n\t\ttoolResults: ToolResultMessage[],\n\t\tawaitPersistence?: boolean,\n\t): Promise<boolean>;\n\t_applyBoundaryDrafts(manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[];\n\t_createBoundaryPreviewManager(drafts: SessionBoundaryDraft[]): SessionManager;\n\t_getPendingBoundaryMessages(): AgentMessage[];\n\t_buildBoundaryContext(\n\t\tdrafts: SessionBoundaryDraft[],\n\t\tboundary: \"turn_end\" | \"agent_before_settle\",\n\t): BoundaryContextPreview;\n\t_commitBoundaryDrafts(drafts: SessionBoundaryDraft[]): void;\n\t_reportInvalidBoundaryContinuation(event: \"turn_end\" | \"agent_before_settle\"): void;\n\t_findPersistedMessageEntryId(message: AgentMessage): string | undefined;\n\t_omitRecoveryAttempt(message: AssistantMessage, toolResults?: AgentMessage[]): void;\n\t_omitTrailingAssistantAttempt(accept?: (message: AssistantMessage) => boolean): boolean;\n\t_runBeforeSettleBoundary(): Promise<boolean>;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\tdispose(): Promise<void>;\n\tgetAgentTaskHost(): import(\"./tasks/agent-adapter.js\").AgentTaskHost;\n\t_getCommandTaskOwner(): import(\"./tools/bash-pty-native.js\").SupervisedCommandOwner | undefined;\n\tcloseSessionTasks(): Promise<void>;\n\t/** Internal workflow pause: cancel owned execution without closing message admission. */\n\tpauseTasks(): Promise<void>;\n\tresumeTasks(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetCallableToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\t/** Explain which tools are active, which are not (and why), and which selected names nothing registered. */\n\tgetToolStatus(): ToolStatusReport;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\t_setActiveTools(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): void;\n\t_preparePromptAndToolLoadout(\n\t\toptions: NormalizedBuildSystemPromptOptions,\n\t\tmessages?: AgentMessage[],\n\t): import(\"@bastani/pi-ai\").SystemMessage | undefined;\n\t_restoreToolsFromTranscript(options?: { keepLoadout?: boolean }): void;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tpromptStarted?: () => void,\n\t\treportDispatch?: (disposition: PromptDisposition) => void,\n\t\tprepared?: boolean,\n\t\tcustomStarter?: CustomMessage,\n\t): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(\n\t\ttext: string,\n\t\timages?: ImageContent[],\n\t\toptions?: Pick<PromptOptions, \"source\">,\n\t): Promise<QueuedInputDisposition>;\n\tfollowUp(\n\t\ttext: string,\n\t\timages?: ImageContent[],\n\t\toptions?: Pick<PromptOptions, \"source\">,\n\t): Promise<QueuedInputDisposition>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_flushPendingCustomMessages(): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\" | \"interrupt\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>, options?: ModelMutationOptions): Promise<void>;\n\tcycleModel(\n\t\tdirection?: \"forward\" | \"backward\",\n\t\toptions?: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel, options?: ModelMutationOptions): void;\n\tcycleThinkingLevel(options?: ModelMutationOptions): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(targetModel?: Model<Api>, explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: SessionCompactOptions): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\tabortSessionSummary(): void;\n\t_maybeGenerateSessionSummary(): Promise<void>;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(\n\t\treason: \"overflow\" | \"threshold\",\n\t\twillRetry: boolean,\n\t\turgency?: CompactionUrgency,\n\t): Promise<AutoCompactionRunOutcome>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(\n\t\trunner: ExtensionRunner,\n\t\tpublication?: {\n\t\t\tresourceLoader: ResourceLoader;\n\t\t\tproviderTransaction: ExtensionProviderTransaction;\n\t\t\tproviderIds: Set<string>;\n\t\t\tdefer(effect: () => void | Promise<void>): void;\n\t\t},\n\t): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\tcompleteStartupResources(resourceLoader: ResourceLoader): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isFallbackableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\t_beginFallbackModelScope(): void;\n\t_clearFallbackModelScope(): void;\n\t_settleFallbackModelScope(): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string, options?: { themeName?: string }): Promise<string>;\n\texportToJsonl(outputPath?: string, options?: { includeShareContext?: boolean }): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"getAgentTaskHost\"\n\t\t| \"closeSessionTasks\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"sessionSummary\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"abortSessionSummary\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"workflows\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getCallableToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"getToolStatus\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"completeStartupResources\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"refreshContext\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\t_fallbackAttemptedKeys: Set<string>;\n\t_fallbackBlockedModels: Array<Model<Api>>;\n\t_fallbackOriginModel: Model<Api> | undefined;\n\t_fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\t_fallbackScopeGeneration: number;\n\t_fallbackOriginGeneration: number | undefined;\n\t_fallbackRestoreError: string | undefined;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_stopAfterTurnBlockedContinuation: boolean;\n\t_pendingInterruptDeliveries: number;\n\t_priorityInterruptPending: boolean;\n\t_activePromptCount: number;\n\t_isPreparingRun: false | \"user\" | \"custom\";\n\t_agentRunAbortRequested: boolean;\n\t_cacheWarmer?: import(\"./cache-warmer.ts\").CacheWarmer;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_admittedQueuedMessageAwaitingReply: string | undefined;\n\t_admittedRecoveryTurn: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_pendingCustomMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_autoCompactionCompletion: Promise<void> | undefined;\n\t_compactionReason: import(\"./agent-session-types.js\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_recoverableLengthRecoveryAttempted: boolean;\n\t_contextOverflowUnresolved: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_branchSummaryCompletion: Promise<void> | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, Set<AbortController>>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_workflows?: SessionWorkflowsHandle;\n\t_turnIndex: number;\n\treadonly _entryIdsByMessage: WeakMap<object, string>;\n\treadonly _boundaryDispatchedMessages: WeakSet<object>;\n\treadonly _messagesAwaitingPersistence: WeakSet<object>;\n\t_lastAssistantToolResults: AgentMessage[];\n\t_lastActivityOutcome: AgentActivityOutcome;\n\t_isBeforeSettle: boolean;\n\t_abortDuringBeforeSettle: boolean;\n\t_isEmittingAgentSettled: boolean;\n\treadonly _deferredSettledActions: Array<() => Promise<void>>;\n\t_callerReplacedNextRequestContext: boolean;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_pendingToolNames: Set<string>;\n\t_usesDefaultTools: boolean;\n\t_defaultToolModifiers: string[];\n\t_appliedDefaultTools: Set<string>;\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_allowedTools?: (name: string) => boolean;\n\t_excludedTools?: (name: string) => boolean;\n\t_childSessionOptions?: import(\"./child-session-options.ts\").ChildSessionOptionsResolver;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_subagentPolicy?: import(\"./extensions/index.js\").SubagentChildPolicy;\n\t_subagentMessageAdmission?: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionHumanInput?: import(\"./extensions/host-input.js\").HostInput | null;\n\t_extensionDiagnosticListener?: (diagnostic: import(\"./extensions/host-input.js\").HostDiagnostic) => void;\n\t_extensionMode: ExtensionMode;\n\t_disposed: boolean;\n\t_close(event: import(\"./extensions/types.ts\").SessionShutdownEvent, beforeInvalidate?: () => void): Promise<void>;\n\t_sessionSummaryAbortController: AbortController | undefined;\n\t_sessionSummaryToken: number;\n\t_sessionSummaryRun: import(\"./agent-session-summary.ts\").SessionSummaryRun | undefined;\n\t_lastSummarizedMessageId: string | undefined;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_extensionProviderIds: Set<string>;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolExecutionScheduler: ToolExecutionScheduler;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPromptOptions: NormalizedBuildSystemPromptOptions;\n\t_systemPromptTransform?: (prompt: string) => string;\n\t_contextProjectionTransform?: (messages: AgentMessage[]) => AgentMessage[];\n\t_runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_tempStorageLease: import(\"./tools/session-temp-dir.ts\").ProtectedPathLease | undefined;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n\t_agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\t_parentCommandTaskOwner: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner | undefined;\n\t_childTaskWaits: import(\"./tasks/child-command-owner.js\").ChildTaskWaits;\n\t_taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\t_taskAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderHeaders } from \"@bastani/pi-ai\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolResultMessage,\n} from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tModelMutationOptions,\n\tPromptDisposition,\n\tPromptOptions,\n\tQueuedInputDisposition,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.js\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tAgentActivityOutcome,\n\tBoundaryContextPreview,\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionBoundaryDraft,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.js\";\nimport type { SessionWorkflows } from \"./extensions/workflow-run-control.js\";\nimport type { SessionWorkflowsHandle } from \"./extensions/workflow-run-control-hub.js\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ExtensionProviderTransaction, ModelRuntime } from \"./model-runtime.js\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionEntry, SessionManager, SessionSummaryEntry } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { NormalizedBuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { ToolStatusReport } from \"./tool-status.js\";\nimport type { BashOperations } from \"./tools/bash.js\";\nimport type { ToolExecutionScheduler } from \"./tools/tool-concurrency.ts\";\n\nexport interface SessionCompactOptions extends Partial<VerbatimCompactionParameters> {\n\t/** Exact `provider/model` ID for this run only; overrides the `compactionModel` setting without saving it. */\n\tcompactionModel?: string;\n}\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\tcompactionModel?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Reports when a session_before_compact override becomes the active compaction source. */\n\tonCompactionSource?: (fromExtension: boolean) => void;\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Outcome of an automatic compaction admission and persistence attempt. */\nexport type AutoCompactionRunOutcome = \"compacted\" | \"not_compactable\" | \"deferred\" | \"failed\";\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n\tpreserveRunner?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.js\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.js\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly sessionSummary: SessionSummaryEntry | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\t/** Typed management of the workflow runs this session owns. */\n\treadonly workflows: SessionWorkflows;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t\tsignal?: AbortSignal,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_installAgentRequestProjection(): void;\n\t_installAgentBoundaryHooks(): void;\n\t_refreshFinalizedContext(): void;\n\t_projectFinalizedMessages(): AgentMessage[];\n\trefreshContext(): void;\n\t_dispatchTurnEndBoundary(\n\t\tmessage: AssistantMessage,\n\t\ttoolResults: ToolResultMessage[],\n\t\tawaitPersistence?: boolean,\n\t): Promise<boolean>;\n\t_applyBoundaryDrafts(manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[];\n\t_createBoundaryPreviewManager(drafts: SessionBoundaryDraft[]): SessionManager;\n\t_getPendingBoundaryMessages(): AgentMessage[];\n\t_buildBoundaryContext(\n\t\tdrafts: SessionBoundaryDraft[],\n\t\tboundary: \"turn_end\" | \"agent_before_settle\",\n\t): BoundaryContextPreview;\n\t_commitBoundaryDrafts(drafts: SessionBoundaryDraft[]): void;\n\t_reportInvalidBoundaryContinuation(event: \"turn_end\" | \"agent_before_settle\"): void;\n\t_findPersistedMessageEntryId(message: AgentMessage): string | undefined;\n\t_omitRecoveryAttempt(message: AssistantMessage, toolResults?: AgentMessage[]): void;\n\t_omitTrailingAssistantAttempt(accept?: (message: AssistantMessage) => boolean): boolean;\n\t_runBeforeSettleBoundary(): Promise<boolean>;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\tdispose(): Promise<void>;\n\tgetAgentTaskHost(): import(\"./tasks/agent-adapter.js\").AgentTaskHost;\n\t_getCommandTaskOwner(): import(\"./tools/bash-pty-native.js\").SupervisedCommandOwner | undefined;\n\tcloseSessionTasks(): Promise<void>;\n\t/** Internal workflow pause: cancel owned execution without closing message admission. */\n\tpauseTasks(): Promise<void>;\n\tresumeTasks(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetCallableToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\t/** Explain which tools are active, which are not (and why), and which selected names nothing registered. */\n\tgetToolStatus(): ToolStatusReport;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\t_setActiveTools(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): void;\n\t_preparePromptAndToolLoadout(\n\t\toptions: NormalizedBuildSystemPromptOptions,\n\t\tmessages?: AgentMessage[],\n\t): import(\"@bastani/pi-ai\").SystemMessage | undefined;\n\t_restoreToolsFromTranscript(options?: { startup?: boolean }): void;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tpromptStarted?: () => void,\n\t\treportDispatch?: (disposition: PromptDisposition) => void,\n\t\tprepared?: boolean,\n\t\tcustomStarter?: CustomMessage,\n\t): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(\n\t\ttext: string,\n\t\timages?: ImageContent[],\n\t\toptions?: Pick<PromptOptions, \"source\">,\n\t): Promise<QueuedInputDisposition>;\n\tfollowUp(\n\t\ttext: string,\n\t\timages?: ImageContent[],\n\t\toptions?: Pick<PromptOptions, \"source\">,\n\t): Promise<QueuedInputDisposition>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\"; expandPromptTemplates?: boolean },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_flushPendingCustomMessages(): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\" | \"interrupt\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>, options?: ModelMutationOptions): Promise<void>;\n\tcycleModel(\n\t\tdirection?: \"forward\" | \"backward\",\n\t\toptions?: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(\n\t\tdirection: \"forward\" | \"backward\",\n\t\toptions: ModelMutationOptions,\n\t): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel, options?: ModelMutationOptions): void;\n\tcycleThinkingLevel(options?: ModelMutationOptions): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(targetModel?: Model<Api>, explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: SessionCompactOptions): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\tabortSessionSummary(): void;\n\t_maybeGenerateSessionSummary(): Promise<void>;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(\n\t\treason: \"overflow\" | \"threshold\",\n\t\twillRetry: boolean,\n\t\turgency?: CompactionUrgency,\n\t): Promise<AutoCompactionRunOutcome>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(\n\t\trunner: ExtensionRunner,\n\t\tpublication?: {\n\t\t\tresourceLoader: ResourceLoader;\n\t\t\tproviderTransaction: ExtensionProviderTransaction;\n\t\t\tproviderIds: Set<string>;\n\t\t\tdefer(effect: () => void | Promise<void>): void;\n\t\t},\n\t\tstartupToolNames?: readonly string[],\n\t): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\tcompleteStartupResources(resourceLoader: ResourceLoader): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isFallbackableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\t_beginFallbackModelScope(): void;\n\t_clearFallbackModelScope(): void;\n\t_settleFallbackModelScope(): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string, options?: { themeName?: string }): Promise<string>;\n\texportToJsonl(outputPath?: string, options?: { includeShareContext?: boolean }): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"getAgentTaskHost\"\n\t\t| \"closeSessionTasks\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"sessionSummary\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"abortSessionSummary\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"workflows\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getCallableToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"getToolStatus\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"completeStartupResources\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"refreshContext\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_isFallbackModelAllowed?: (model: Model<Api>, effort: string | undefined) => boolean;\n\t_fallbackAttemptedKeys: Set<string>;\n\t_fallbackBlockedModels: Array<Model<Api>>;\n\t_fallbackOriginModel: Model<Api> | undefined;\n\t_fallbackOriginThinkingLevel: ThinkingLevel | undefined;\n\t_fallbackScopeGeneration: number;\n\t_fallbackOriginGeneration: number | undefined;\n\t_fallbackRestoreError: string | undefined;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_stopAfterTurnBlockedContinuation: boolean;\n\t_pendingInterruptDeliveries: number;\n\t_priorityInterruptPending: boolean;\n\t_activePromptCount: number;\n\t_isPreparingRun: false | \"user\" | \"custom\";\n\t_agentRunAbortRequested: boolean;\n\t_cacheWarmer?: import(\"./cache-warmer.ts\").CacheWarmer;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_admittedQueuedMessageAwaitingReply: string | undefined;\n\t_admittedRecoveryTurn: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_pendingCustomMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_autoCompactionCompletion: Promise<void> | undefined;\n\t_compactionReason: import(\"./agent-session-types.js\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_recoverableLengthRecoveryAttempted: boolean;\n\t_contextOverflowUnresolved: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_branchSummaryCompletion: Promise<void> | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, Set<AbortController>>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_workflows?: SessionWorkflowsHandle;\n\t_turnIndex: number;\n\treadonly _entryIdsByMessage: WeakMap<object, string>;\n\treadonly _boundaryDispatchedMessages: WeakSet<object>;\n\treadonly _messagesAwaitingPersistence: WeakSet<object>;\n\t_lastAssistantToolResults: AgentMessage[];\n\t_lastActivityOutcome: AgentActivityOutcome;\n\t_isBeforeSettle: boolean;\n\t_abortDuringBeforeSettle: boolean;\n\t_isEmittingAgentSettled: boolean;\n\treadonly _deferredSettledActions: Array<() => Promise<void>>;\n\t_callerReplacedNextRequestContext: boolean;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_pendingToolNames: Set<string>;\n\t_usesDefaultTools: boolean;\n\t_defaultToolModifiers: string[];\n\t_appliedDefaultTools: Set<string>;\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_allowedTools?: (name: string) => boolean;\n\t_excludedTools?: (name: string) => boolean;\n\t_childSessionOptions?: import(\"./child-session-options.ts\").ChildSessionOptionsResolver;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_subagentPolicy?: import(\"./extensions/index.js\").SubagentChildPolicy;\n\t_subagentMessageAdmission?: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionHumanInput?: import(\"./extensions/host-input.js\").HostInput | null;\n\t_extensionDiagnosticListener?: (diagnostic: import(\"./extensions/host-input.js\").HostDiagnostic) => void;\n\t_extensionMode: ExtensionMode;\n\t_disposed: boolean;\n\t_close(event: import(\"./extensions/types.ts\").SessionShutdownEvent, beforeInvalidate?: () => void): Promise<void>;\n\t_sessionSummaryAbortController: AbortController | undefined;\n\t_sessionSummaryToken: number;\n\t_sessionSummaryRun: import(\"./agent-session-summary.ts\").SessionSummaryRun | undefined;\n\t_lastSummarizedMessageId: string | undefined;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_extensionProviderIds: Set<string>;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolExecutionScheduler: ToolExecutionScheduler;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPromptOptions: NormalizedBuildSystemPromptOptions;\n\t_systemPromptTransform?: (prompt: string) => string;\n\t_contextProjectionTransform?: (messages: AgentMessage[]) => AgentMessage[];\n\t_runSystemPromptOptions?: NormalizedBuildSystemPromptOptions;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_tempStorageLease: import(\"./tools/session-temp-dir.ts\").ProtectedPathLease | undefined;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n\t_agentTaskHost: import(\"./tasks/agent-adapter.js\").AgentTaskHost | undefined;\n\t_parentCommandTaskOwner: import(\"./tasks/child-command-owner.js\").ChildCommandTaskOwner | undefined;\n\t_childTaskWaits: import(\"./tasks/child-command-owner.js\").ChildTaskWaits;\n\t_taskCompletionOutbox: import(\"./tasks/completion.js\").TaskCompletionOutbox | undefined;\n\t_taskAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
|
|
@@ -386,7 +386,7 @@ export async function _handleRetryableError(message) {
|
|
|
386
386
|
// main chat and workflow stages cannot drift apart on the same settings. The
|
|
387
387
|
// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`
|
|
388
388
|
// closes the retry lifecycle before the fallback lifecycle opens.
|
|
389
|
-
const decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel);
|
|
389
|
+
const decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel, message);
|
|
390
390
|
this._retryAttempt += 1;
|
|
391
391
|
if (decision === undefined) {
|
|
392
392
|
if (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,IAAI,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EACN,uBAAuB,EACvB,2BAA2B,EAC3B,sBAAsB,EACtB,2BAA2B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,SAAS,UAAU,CAAC,KAA6B;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe,CAAC;AAClE,CAAC;AAED,SAAS,8BAA8B,CAAC,QAAgB,EAAE,KAAc,EAAE,IAAI,GAAG,IAAI,GAAG,EAAW;IAClG,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3E,IAAI,OAAO,KAAK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port { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// Safety/refusal errors remain bounded same-model retries, but do not spend\n\t// another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nfunction applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): boolean {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis.agent.state.thinkingLevel = level;\n\tif (previousLevel === level) return false;\n\tthis.sessionManager.appendThinkingLevelChange(level);\n\tthis._emit({ type: \"thinking_level_changed\", level });\n\tvoid this._extensionRunner?.emit({\n\t\ttype: \"thinking_level_select\",\n\t\tlevel,\n\t\tpreviousLevel,\n\t});\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Finish an active fallback lifecycle before an explicit model choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Finish an active fallback lifecycle without changing the selected fallback model. */\nexport async function _settleFallbackModelScope(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\tif (this._fallbackOriginGeneration !== originGeneration || this._fallbackOriginModel !== originModel) return false;\n\n\tconst currentModel = this.agent.state.model ?? this.model;\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(currentModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (this._isFallbackModelAllowed && !this._isFallbackModelAllowed(nextModel, nextLevel)) continue;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\t\tthis._omitTrailingAssistantAttempt();\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tapplyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._agentRunAbortRequested) return false;\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._retryAbortController = new AbortController();\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\tthis._omitTrailingAssistantAttempt();\n\n\t// Wait with exponential backoff (abortable)\n\tif (this._agentRunAbortRequested) this._retryAbortController.abort();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tfinishCancelledRetry.call(this);\n\t\tthis._retryAbortController = undefined;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tfinishCancelledRetry.call(this);\n\t\t\treturn;\n\t\t}\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nfunction finishCancelledRetry(this: AgentSession): void {\n\tif (this._retryAttempt === 0) return;\n\tconst attempt = this._retryAttempt;\n\tthis._retryAttempt = 0;\n\tthis._emit({ type: \"auto_retry_end\", success: false, attempt, finalError: \"Retry cancelled\" });\n}\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\tfinishCancelledRetry.call(this);\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setRetryEnabled(enabled));\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_settleFallbackModelScope,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-retry.js","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C,OAAO,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AACvD,OAAO,EAAE,WAAW,EAAE,oBAAoB,IAAI,8BAA8B,EAAE,MAAM,sBAAsB,CAAC;AAC3G,OAAO,EACN,uBAAuB,EACvB,2BAA2B,EAC3B,sBAAsB,EACtB,2BAA2B,GAC3B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AAEnE,SAAS,UAAU,CAAC,KAA6B;IAChD,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,IAAI,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,eAAe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C,MAAM,wBAAwB,GAAG;IACvC,iBAAiB;IACjB,oBAAoB;IACpB,kBAAkB;IAClB,gBAAgB;IAChB,qBAAqB;IACrB,yBAAyB;IACzB,wBAAwB;IACxB,wBAAwB;IACxB,yBAAyB;IACzB,UAAU;IACV,YAAY;IACZ,mBAAmB;CACnB,CAAC","sourcesContent":["import type { Api, AssistantMessage, Model } from \"@bastani/pi-ai/compat\";\nimport { clampThinkingLevel, isContextOverflow, modelsAreEqual } from \"@bastani/pi-ai/compat\";\nimport type { ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport { sleep } from \"../utils/sleep.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { isCodexTokenInvalidationError } from \"./codex-errors.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport { fallbackKey, resolveFallbackModel as resolveConfiguredFallbackModel } from \"./fallback-models.ts\";\nimport {\n\tisRetryableModelFailure,\n\tisRetryableSameModelFailure,\n\tisSafetyRefusalFailure,\n\tnormalizeModelFailureSignal,\n} from \"./model-fallback-failures.ts\";\nimport { nextRetryDecision } from \"./retry-policy.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\n\nfunction modelLabel(model: Model<Api> | undefined): string {\n\treturn model ? `${model.provider}/${model.id}` : \"unknown model\";\n}\n\nfunction containsCodexTokenInvalidation(provider: string, value: unknown, seen = new Set<unknown>()): boolean {\n\tif (value === null || value === undefined || seen.has(value)) return false;\n\tif (typeof value === \"string\") return isCodexTokenInvalidationError(provider, value);\n\tif (typeof value !== \"object\") return false;\n\tseen.add(value);\n\tconst record = value as Record<string, unknown>;\n\tfor (const field of [record.errorMessage, record.message, record.statusText]) {\n\t\tif (typeof field === \"string\" && isCodexTokenInvalidationError(provider, field)) return true;\n\t}\n\tfor (const nested of [\n\t\trecord.error,\n\t\trecord.cause,\n\t\t...(Array.isArray(record.diagnostics) ? record.diagnostics : []),\n\t]) {\n\t\tif (containsCodexTokenInvalidation(provider, nested, seen)) return true;\n\t}\n\treturn false;\n}\n\nfunction resolveFallbackModel(\n\tthis: AgentSession,\n\tvalue: string,\n): { model: Model<Api>; thinkingLevel?: ThinkingLevel } | undefined {\n\treturn resolveConfiguredFallbackModel(\n\t\tvalue,\n\t\tthis._modelRuntime,\n\t\tthis.model?.provider ?? this.settingsManager.getDefaultProvider(),\n\t);\n}\n\n/** Whether an assistant error may advance the configured fallback chain. */\nexport function _isFallbackableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return true;\n\tconst signal = normalizeModelFailureSignal(message);\n\tif (signal.kind === \"cancelled\" || signal.kind === \"task_failure\") return false;\n\treturn isRetryableModelFailure(message);\n}\n\n/**\n * Whether the current model should be requested again.\n *\n * Fallback eligibility is broader than same-model retry eligibility. Auth and\n * request-incompatible failures should spend a fallback candidate, but cannot\n * be repaired by sending the same request again. Codex token invalidation is\n * also terminal for the current model while remaining fallbackable.\n */\nexport function _isRetryableError(this: AgentSession, message: AssistantMessage): boolean {\n\tif (message.stopReason !== \"error\") return false;\n\n\t// Context overflow is handled by compaction, not retry.\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\tif (isContextOverflow(message, contextWindow)) return false;\n\n\tconst provider = message.provider || this.model?.provider;\n\tif (provider && containsCodexTokenInvalidation(provider, message)) return false;\n\n\t// Safety/refusal errors remain bounded same-model retries, but do not spend\n\t// another provider candidate. The refusal grammar lives in the shared\n\t// classifier so this decision cannot drift from workflow fallback handling.\n\tif (isSafetyRefusalFailure(message)) return true;\n\treturn isRetryableSameModelFailure(message);\n}\n\n/**\n * Detect a degenerate empty completion: the provider ended the stream with no\n * usable content and zero output tokens. Seen with github-copilot Gemini models\n * that emit finish_reason \"stop\" (or a tool-use stop) with an empty content array\n * and 0 output tokens, leaving the turn dead instead of producing the next step.\n *\n * These are treated as retryable so the harness re-issues the request rather than\n * silently stopping mid-task. Guarded tightly (no text, no tool call, no thinking,\n * and output === 0) so legitimate non-empty turns are never matched.\n *\n * Intentionally provider-agnostic (not gated to Copilot Gemini): a degenerate\n * empty turn is a transient failure for any provider. It is bounded by\n * `maxRetries` and falls through to normal handling on exhaustion.\n */\n\nexport function _isEmptyCompletion(this: AgentSession, message: AssistantMessage): boolean {\n\t// Only \"completed\" stop reasons can be deceptively empty. Real errors are handled\n\t// by _isRetryableError; aborted/length turns are intentional outcomes.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"toolUse\") return false;\n\n\tconst content = message.content;\n\tif (Array.isArray(content)) {\n\t\tconst hasContent = content.some((part) => {\n\t\t\tif (part.type === \"text\") return part.text.trim().length > 0;\n\t\t\tif (part.type === \"toolCall\") return true;\n\t\t\tif (part.type === \"thinking\") return part.redacted === true || part.thinking.trim().length > 0;\n\t\t\treturn true; // unknown part types count as content\n\t\t});\n\t\tif (hasContent) return false;\n\t}\n\n\t// A turn that produced output tokens but no surfaced content is not \"empty\"\n\t// (e.g. reasoning-only responses); leave those alone. Note: a provider that\n\t// fails to report `usage` (output defaults to 0) would make every\n\t// content-less turn match here; the dual requirement (empty content AND zero\n\t// output) keeps that false-positive risk low in practice.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\n/**\n * Detect a canned provider-side safety refusal that arrives as a *successful*\n * completion instead of an error. Seen with github-copilot GPT models under\n * heavy contexts: the endpoint intercepts the request and returns exactly\n * \"I'm sorry, but I cannot assist with that request.\" with zero usage and a\n * spurious stopReason of \"length\" (or \"stop\"), which the agent would otherwise\n * accept as the final answer and dead-end the turn (issue #1608).\n *\n * A text heuristic is unavoidable here: the OpenAI Responses API does signal\n * these interceptions structurally (`refusal` content parts plus\n * `incomplete_details.reason: \"content_filter\"`), but pi-ai's normalization\n * folds refusal parts into plain text blocks and collapses the `incomplete`\n * status to stopReason \"length\", discarding the reason — so no structured\n * refusal marker survives on the AssistantMessage. Providers whose safety\n * signals DO survive as structured errors (Anthropic refusal stops, OpenAI\n * `finish_reason: content_filter`) are matched in _isRetryableError instead.\n *\n * Guarded tightly so legitimate turns are never matched:\n * - only non-error completion stops (\"stop\" | \"length\" | \"toolUse\");\n * - content must be a single short canned refusal text — any tool call,\n * thinking block, or additional prose disqualifies the message;\n * - usage.output must be 0: a genuine model-authored refusal bills output\n * tokens, while the intercepted canned refusal reports zero usage.\n *\n * Treated as retryable so the harness re-requests the model call rather than\n * accepting the refusal; bounded by `maxRetries` like every other retry path.\n */\n\nconst CANNED_SAFETY_REFUSAL_PATTERN =\n\t/^(?:i['’]?m sorry[,.]?\\s+(?:but\\s+)?|sorry[,.]?\\s+(?:but\\s+)?)?i\\s+(?:cannot|can['’]?t|can\\s+not|am\\s+unable\\s+to|am\\s+not\\s+able\\s+to)\\s+(?:assist|help|comply|continue)(?:\\s+with)?(?:\\s+(?:that|this))?(?:\\s+(?:request|task))?\\.?$/i;\n\nconst CANNED_SAFETY_REFUSAL_MAX_LENGTH = 120;\n\nexport function _isSafetyRefusal(this: AgentSession, message: AssistantMessage): boolean {\n\t// Real errors are handled by _isRetryableError; aborts are user-initiated.\n\tif (message.stopReason !== \"stop\" && message.stopReason !== \"length\" && message.stopReason !== \"toolUse\") {\n\t\treturn false;\n\t}\n\n\tconst content = message.content;\n\tif (!Array.isArray(content) || content.length === 0) return false;\n\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (part.type === \"toolCall\") return false;\n\t\tif (part.type === \"thinking\" && (part.redacted === true || part.thinking.trim().length > 0)) return false;\n\t\tif (part.type === \"text\") text += part.text;\n\t}\n\ttext = text.trim();\n\tif (text.length === 0 || text.length > CANNED_SAFETY_REFUSAL_MAX_LENGTH) return false;\n\tif (!CANNED_SAFETY_REFUSAL_PATTERN.test(text)) return false;\n\n\t// Zero billed output distinguishes a provider interception from legitimate\n\t// model-authored refusal prose, which is never auto-retried.\n\treturn (message.usage?.output ?? 0) === 0;\n}\n\nfunction applyFallbackThinkingLevel(this: AgentSession, level: ThinkingLevel): boolean {\n\tconst previousLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis.agent.state.thinkingLevel = level;\n\tif (previousLevel === level) return false;\n\tthis.sessionManager.appendThinkingLevelChange(level);\n\tthis._emit({ type: \"thinking_level_changed\", level });\n\tvoid this._extensionRunner?.emit({\n\t\ttype: \"thinking_level_select\",\n\t\tlevel,\n\t\tpreviousLevel,\n\t});\n\treturn true;\n}\n\n/** Capture the user-selected model before the first fallback in a turn. */\nexport function _beginFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackOriginModel !== undefined || currentModel === undefined) return;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tthis._fallbackOriginGeneration = this._fallbackScopeGeneration;\n\tthis._fallbackOriginModel = currentModel;\n\tthis._fallbackOriginThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tthis._fallbackRestoreError = undefined;\n}\n\nfunction clearFallbackModelScopeState(this: AgentSession): void {\n\tthis._fallbackOriginGeneration = undefined;\n\tthis._fallbackOriginModel = undefined;\n\tthis._fallbackOriginThinkingLevel = undefined;\n\tthis._fallbackRestoreError = undefined;\n\tthis._fallbackAttemptedKeys.clear();\n\tthis._fallbackBlockedModels.length = 0;\n}\n\nfunction finishFallbackModelScope(\n\tthis: AgentSession,\n\toptions: {\n\t\treadonly success: boolean;\n\t\treadonly from?: string;\n\t\treadonly to?: string;\n\t\treadonly finalError?: string;\n\t},\n): boolean {\n\tif (this._fallbackOriginModel === undefined || this._fallbackOriginGeneration === undefined) return false;\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n\tthis._emit({\n\t\ttype: \"model_fallback_end\",\n\t\tsuccess: options.success,\n\t\t...(options.from === undefined ? {} : { from: options.from }),\n\t\t...(options.to === undefined ? {} : { to: options.to }),\n\t\t...(options.finalError === undefined ? {} : { finalError: options.finalError }),\n\t});\n\treturn true;\n}\n\n/** Finish an active fallback lifecycle before an explicit model choice. */\nexport function _clearFallbackModelScope(this: AgentSession): void {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tconst finalError = this._fallbackRestoreError;\n\tif (this._fallbackOriginModel !== undefined && this._fallbackOriginGeneration !== undefined) {\n\t\tfinishFallbackModelScope.call(this, {\n\t\t\tsuccess: finalError === undefined,\n\t\t\tfrom: modelLabel(currentModel),\n\t\t\t...(finalError === undefined ? {} : { finalError }),\n\t\t});\n\t\treturn;\n\t}\n\tthis._fallbackScopeGeneration = (this._fallbackScopeGeneration ?? 0) + 1;\n\tclearFallbackModelScopeState.call(this);\n}\n\n/** Finish an active fallback lifecycle without changing the selected fallback model. */\nexport async function _settleFallbackModelScope(this: AgentSession): Promise<boolean> {\n\tconst originModel = this._fallbackOriginModel;\n\tconst originGeneration = this._fallbackOriginGeneration;\n\tconst finalError = this._fallbackRestoreError;\n\tif (originModel === undefined || originGeneration === undefined) {\n\t\tclearFallbackModelScopeState.call(this);\n\t\treturn false;\n\t}\n\tif (this._fallbackOriginGeneration !== originGeneration || this._fallbackOriginModel !== originModel) return false;\n\n\tconst currentModel = this.agent.state.model ?? this.model;\n\treturn finishFallbackModelScope.call(this, {\n\t\tsuccess: finalError === undefined,\n\t\tfrom: modelLabel(currentModel),\n\t\t...(finalError === undefined ? {} : { finalError }),\n\t});\n}\n\n/** Handle retryable errors with exponential backoff. */\nexport async function _trySwitchToFallbackModel(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tconst currentModel = this.agent.state.model ?? this.model;\n\tif (this._fallbackModels.length === 0 || currentModel === undefined) return false;\n\n\t// A failure the chain may spend a candidate on, but that requesting the same\n\t// model again cannot repair — a rejected credential, an unavailable model, a\n\t// request this model cannot serve — condemns that model for the rest of the\n\t// turn. Reasoning level does not change any of those answers, so every\n\t// reasoning variant of it is blocked too. Transient rate-limit and transport\n\t// failures stay same-model retryable and keep their reasoning variants.\n\tif (isRetryableModelFailure(message) && !isRetryableSameModelFailure(message)) {\n\t\tif (!this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, currentModel))) {\n\t\t\tthis._fallbackBlockedModels.push(currentModel);\n\t\t}\n\t}\n\n\tconst currentThinkingLevel = this.agent.state.thinkingLevel ?? this.thinkingLevel;\n\tconst fromModel = currentModel;\n\tfor (const rawCandidate of this._fallbackModels) {\n\t\tconst candidate = resolveFallbackModel.call(this, rawCandidate);\n\t\tif (!candidate) continue;\n\t\tconst nextModel = candidate.model;\n\t\tconst nextLevel = clampThinkingLevel(\n\t\t\tnextModel,\n\t\t\tcandidate.thinkingLevel ??\n\t\t\t\tthis.settingsManager.getDefaultThinkingLevel() ??\n\t\t\t\tcurrentThinkingLevel ??\n\t\t\t\tDEFAULT_THINKING_LEVEL,\n\t\t) as ThinkingLevel;\n\t\tif (this._isFallbackModelAllowed && !this._isFallbackModelAllowed(nextModel, nextLevel)) continue;\n\t\tconst key = fallbackKey(nextModel, nextLevel);\n\t\tif (this._fallbackAttemptedKeys.has(key)) continue;\n\t\tif (modelsAreEqual(nextModel, fromModel) && nextLevel === currentThinkingLevel) continue;\n\t\t// Skipped before any lifecycle starts: a blocked variant emits no fallback\n\t\t// event and opens no scope.\n\t\tif (this._fallbackBlockedModels.some((blocked) => modelsAreEqual(blocked, nextModel))) continue;\n\n\t\t// Do not create a fallback lifecycle until a candidate can actually be\n\t\t// selected. An exhausted or unresolvable chain has no start to close.\n\t\t_beginFallbackModelScope.call(this);\n\t\tthis._fallbackAttemptedKeys.add(fallbackKey(currentModel, currentThinkingLevel));\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: true,\n\t\t\t\tattempt: Math.max(0, this._retryAttempt - 1),\n\t\t\t});\n\t\t}\n\t\tthis._fallbackAttemptedKeys.add(key);\n\t\tthis._emit({\n\t\t\ttype: \"model_fallback_start\",\n\t\t\tfrom: modelLabel(fromModel),\n\t\t\tto: `${nextModel.provider}/${nextModel.id}`,\n\t\t\treason: message.errorMessage || \"Retryable model error\",\n\t\t\tattempt: this._fallbackAttemptedKeys.size - 1,\n\t\t});\n\n\t\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\t\tthis._omitTrailingAssistantAttempt();\n\t\tthis.agent.state.model = nextModel;\n\t\tthis.sessionManager.appendModelChange(nextModel.provider, nextModel.id);\n\t\tapplyFallbackThinkingLevel.call(this, nextLevel);\n\t\tthis._refreshBaseSystemPromptFromActiveTools();\n\t\tthis._emitModelChanged(nextModel, fromModel, \"fallback\");\n\t\tawait this._emitModelSelect(nextModel, fromModel, \"fallback\");\n\t\tthis._retryAttempt = 0;\n\n\t\tconst fallbackGeneration = this._fallbackOriginGeneration;\n\t\tsetTimeout(() => {\n\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\tvoid this.agent.continue().catch(async (error: unknown) => {\n\t\t\t\tconst finalError = error instanceof Error ? error.message : String(error);\n\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\tthis._fallbackRestoreError = finalError;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\tif (this._fallbackOriginGeneration === fallbackGeneration) {\n\t\t\t\t\t\t\tfinishFallbackModelScope.call(this, {\n\t\t\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\t\t\tfrom: modelLabel(this.agent.state.model ?? this.model),\n\t\t\t\t\t\t\t\tfinalError,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t\tthis._resolveRetry();\n\t\t\t});\n\t\t}, 0);\n\t\treturn true;\n\t}\n\tif (this._fallbackOriginModel !== undefined) {\n\t\tthis._fallbackRestoreError = message.errorMessage || \"Model fallback exhausted\";\n\t}\n\treturn false;\n}\n\nexport async function _handleRetryableError(this: AgentSession, message: AssistantMessage): Promise<boolean> {\n\tif (this._agentRunAbortRequested) return false;\n\tconst settings = this.settingsManager.getRetrySettings();\n\tconst retryableError = this._isRetryableError?.(message) ?? true;\n\tconst fallbackableError = this._isFallbackableError?.(message) ?? retryableError;\n\tconst emptyCompletion = this._isEmptyCompletion?.(message) ?? false;\n\tconst safetyRefusal = this._isSafetyRefusal?.(message) ?? false;\n\tconst canRetrySameModel = retryableError || emptyCompletion || safetyRefusal;\n\t// Empty completions have historically been allowed to spend a fallback after\n\t// same-model retries. Provider safety refusals stay on the same model.\n\tconst canAdvanceToFallback = fallbackableError || emptyCompletion;\n\tif (!settings.enabled || !canRetrySameModel) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) return true;\n\t\tif (this._retryAttempt > 0) {\n\t\t\tthis._emit({\n\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\tsuccess: false,\n\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\tfinalError: message.errorMessage,\n\t\t\t});\n\t\t}\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\n\t// Retry promise is created synchronously in _handleAgentEvent for agent_end.\n\t// Keep a defensive fallback here in case a future refactor bypasses that path.\n\tif (!this._retryPromise) {\n\t\tthis._retryPromise = new Promise((resolve) => {\n\t\t\tthis._retryResolve = resolve;\n\t\t});\n\t}\n\n\t// One shared policy decides the bounded same-model budget and its backoff, so\n\t// main chat and workflow stages cannot drift apart on the same settings. The\n\t// counter still advances on the exhausting attempt, so `_trySwitchToFallbackModel`\n\t// closes the retry lifecycle before the fallback lifecycle opens.\n\tconst decision = nextRetryDecision(settings, this._retryAttempt, canRetrySameModel, message);\n\tthis._retryAttempt += 1;\n\tif (decision === undefined) {\n\t\tif (canAdvanceToFallback && (await this._trySwitchToFallbackModel(message))) {\n\t\t\treturn true;\n\t\t}\n\t\t// Max retries exceeded, emit final failure and reset\n\t\tthis._emit({\n\t\t\ttype: \"auto_retry_end\",\n\t\t\tsuccess: false,\n\t\t\tattempt: this._retryAttempt - 1,\n\t\t\tfinalError: message.errorMessage,\n\t\t});\n\t\tthis._retryAttempt = 0;\n\t\tthis._resolveRetry(); // Resolve so waitForRetry() completes\n\t\treturn false;\n\t}\n\n\tconst delayMs = decision.delayMs;\n\n\tthis._retryAbortController = new AbortController();\n\tthis._emit({\n\t\ttype: \"auto_retry_start\",\n\t\tattempt: this._retryAttempt,\n\t\tmaxAttempts: settings.maxRetries,\n\t\tdelayMs,\n\t\terrorMessage: message.errorMessage || \"Unknown error\",\n\t});\n\n\t// Keep the failed attempt in raw history while durably omitting it from model projection.\n\tthis._omitTrailingAssistantAttempt();\n\n\t// Wait with exponential backoff (abortable)\n\tif (this._agentRunAbortRequested) this._retryAbortController.abort();\n\ttry {\n\t\tawait sleep(delayMs, this._retryAbortController.signal);\n\t} catch {\n\t\t// Aborted during sleep - emit end event so UI can clean up\n\t\tfinishCancelledRetry.call(this);\n\t\tthis._retryAbortController = undefined;\n\t\tthis._resolveRetry();\n\t\treturn false;\n\t}\n\tthis._retryAbortController = undefined;\n\n\t// Retry via continue() - use setTimeout to break out of event handler chain\n\tsetTimeout(() => {\n\t\tif (this._agentRunAbortRequested) {\n\t\t\tfinishCancelledRetry.call(this);\n\t\t\treturn;\n\t\t}\n\t\tthis.agent.continue().catch(() => {\n\t\t\t// Retry failed - will be caught by next agent_end\n\t\t});\n\t}, 0);\n\n\treturn true;\n}\n\n/**\n * Cancel in-progress retry.\n */\n\nfunction finishCancelledRetry(this: AgentSession): void {\n\tif (this._retryAttempt === 0) return;\n\tconst attempt = this._retryAttempt;\n\tthis._retryAttempt = 0;\n\tthis._emit({ type: \"auto_retry_end\", success: false, attempt, finalError: \"Retry cancelled\" });\n}\n\nexport function abortRetry(this: AgentSession): void {\n\tthis._retryAbortController?.abort();\n\tfinishCancelledRetry.call(this);\n\tthis._resolveRetry();\n}\n\n/**\n * Wait for any in-progress retry to complete.\n * Returns immediately if no retry is in progress.\n */\n\nexport async function waitForRetry(this: AgentSession): Promise<void> {\n\tif (!this._retryPromise) {\n\t\treturn;\n\t}\n\n\tawait this._retryPromise;\n\tawait this.agent.waitForIdle();\n}\n\n/** Whether auto-retry is currently in progress */\n\nexport function setAutoRetryEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setRetryEnabled(enabled));\n}\n\n// =========================================================================\n// Bash Execution\n// =========================================================================\n\n/**\n * Execute a bash command.\n * Adds result to agent context and session.\n * @param command The bash command to execute\n * @param onChunk Optional streaming callback for output\n * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)\n * @param options.operations Custom BashOperations for remote execution\n */\n\nexport const agentSessionRetryMethods = {\n\t_isRetryableError,\n\t_isFallbackableError,\n\t_isEmptyCompletion,\n\t_isSafetyRefusal,\n\t_handleRetryableError,\n\t_trySwitchToFallbackModel,\n\t_beginFallbackModelScope,\n\t_clearFallbackModelScope,\n\t_settleFallbackModelScope,\n\tabortRetry,\n\twaitForRetry,\n\tsetAutoRetryEnabled,\n};\n"]}
|
|
@@ -37,17 +37,15 @@ export declare function _rebuildSystemPrompt(this: AgentSession, toolNames: stri
|
|
|
37
37
|
export declare function _refreshBaseSystemPromptFromActiveTools(this: AgentSession): void;
|
|
38
38
|
/** Diff structured prompt state; executable tool changes are declared by the agent loop. */
|
|
39
39
|
export declare function _preparePromptAndToolLoadout(this: AgentSession, options: NormalizedBuildSystemPromptOptions, messages?: AgentMessage[]): SystemMessage | undefined;
|
|
40
|
+
export declare function preservesInitialToolLoadout(session: AgentSession): boolean;
|
|
40
41
|
/**
|
|
41
42
|
* Restore registered tools from the selected transcript, not another branch's live state.
|
|
42
43
|
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* authoritative for built-in tools, so only the other tools the transcript declared are added to it:
|
|
46
|
-
* the ones an extension or `tool_search` activated, such as MCP tools that are not registered until
|
|
47
|
-
* their server connects. Without it the transcript replaces the loadout.
|
|
44
|
+
* Explicit tool selections keep their built-in loadout while restoring dynamically registered tools.
|
|
45
|
+
* Default selections restore the recorded loadout with any CLI modifiers applied.
|
|
48
46
|
*/
|
|
49
47
|
export declare function _restoreToolsFromTranscript(this: AgentSession, options?: {
|
|
50
|
-
|
|
48
|
+
startup?: boolean;
|
|
51
49
|
}): void;
|
|
52
50
|
/**
|
|
53
51
|
* Send a prompt to the agent.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-state.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-state.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAA2B,KAAK,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AACxD,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,OAAO,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAGtE,OAAO,EAIN,KAAK,kCAAkC,EAEvC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AAED,wBAAgB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAEhF;AAED,4FAA4F;AAC5F,wBAAgB,4BAA4B,CAC3C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,kCAAkC,EAC3C,QAAQ,GAAE,YAAY,EAA8B,GAClD,aAAa,GAAG,SAAS,CAS3B;AAED,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,YAAY,GAAG,OAAO,CAM1E;AAED;;;;;GAKG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAkBrG;AAMD;;;;;;;;GAQG;AAEH,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;CAepC,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { getCurrentSystemMessage } from "@bastani/pi-ai";
|
|
2
2
|
import { getCallableTools } from "./agent-session-nested-tools.js";
|
|
3
|
+
import { applyToolModifiers } from "./settings-merge.js";
|
|
3
4
|
import { getSkillCatalog } from "./skill-catalog.js";
|
|
4
5
|
import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
|
|
5
6
|
import { applyToolLoadout, isToolDeclarationHidden } from "./tool-loadout.js";
|
|
@@ -152,29 +153,33 @@ export function _preparePromptAndToolLoadout(options, messages = this.agent.stat
|
|
|
152
153
|
const sections = diffSystemPromptSections(current?.sections ?? {}, buildSystemPromptSections(options));
|
|
153
154
|
return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
|
|
154
155
|
}
|
|
156
|
+
export function preservesInitialToolLoadout(session) {
|
|
157
|
+
return ((!session._usesDefaultTools && session._initialActiveToolNames !== undefined) ||
|
|
158
|
+
session._orchestrationContext?.kind === "workflow-stage" ||
|
|
159
|
+
(session._subagentPolicy?.depth ?? 0) >= 1);
|
|
160
|
+
}
|
|
155
161
|
/**
|
|
156
162
|
* Restore registered tools from the selected transcript, not another branch's live state.
|
|
157
163
|
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* authoritative for built-in tools, so only the other tools the transcript declared are added to it:
|
|
161
|
-
* the ones an extension or `tool_search` activated, such as MCP tools that are not registered until
|
|
162
|
-
* their server connects. Without it the transcript replaces the loadout.
|
|
164
|
+
* Explicit tool selections keep their built-in loadout while restoring dynamically registered tools.
|
|
165
|
+
* Default selections restore the recorded loadout with any CLI modifiers applied.
|
|
163
166
|
*/
|
|
164
167
|
export function _restoreToolsFromTranscript(options) {
|
|
165
168
|
this._pendingToolNames.clear();
|
|
166
169
|
const current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);
|
|
167
170
|
if (!current)
|
|
168
171
|
return;
|
|
169
|
-
const
|
|
170
|
-
|
|
172
|
+
const keepLoadout = options?.startup && preservesInitialToolLoadout(this);
|
|
173
|
+
const modifiers = options?.startup && this._usesDefaultTools ? this._defaultToolModifiers : [];
|
|
174
|
+
const declared = applyToolModifiers((current.toolsAdded ?? []).map((tool) => tool.name), modifiers);
|
|
175
|
+
if (!keepLoadout) {
|
|
171
176
|
this._pendingToolNames = new Set(declared);
|
|
172
177
|
this._setActiveTools(declared);
|
|
173
178
|
return;
|
|
174
179
|
}
|
|
175
180
|
const restored = declared.filter((name) => !this._baseToolDefinitions.has(name));
|
|
176
181
|
this._pendingToolNames = new Set(restored);
|
|
177
|
-
this._setActiveTools([...this.getActiveToolNames(), ...restored]);
|
|
182
|
+
this._setActiveTools(applyToolModifiers([...this.getActiveToolNames(), ...restored], modifiers));
|
|
178
183
|
}
|
|
179
184
|
// =========================================================================
|
|
180
185
|
// Prompting
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-state.js","sourceRoot":"","sources":["../../src/core/agent-session-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAsB,MAAM,gBAAgB,CAAC;AAI7E,O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;IAClB,oBAAoB;IACpB,WAAW;IACX,iBAAiB;IACjB,aAAa;IACb,oBAAoB;IACpB,eAAe;IACf,eAAe;IACf,uBAAuB;IACvB,0BAA0B;IAC1B,oBAAoB;IACpB,4BAA4B;IAC5B,2BAA2B;IAC3B,uCAAuC;CACvC,CAAC","sourcesContent":["import { getCurrentSystemMessage, type SystemMessage } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { getCallableTools } from \"./agent-session-nested-tools.js\";\nimport type { ToolDefinition, ToolInfo } from \"./extensions/index.js\";\nimport { getSkillCatalog } from \"./skill-catalog.ts\";\nimport {\n\tbuildSystemPrompt,\n\tbuildSystemPromptSections,\n\tdiffSystemPromptSections,\n\ttype NormalizedBuildSystemPromptOptions,\n\tnormalizeBuildSystemPromptOptions,\n} from \"./system-prompt.ts\";\nimport { applyToolLoadout, isToolDeclarationHidden } from \"./tool-loadout.js\";\nimport { selectedToolNames } from \"./tool-selection.ts\";\nimport {\n\tbuildToolStatusReport,\n\tdescribeToolSelection,\n\ttype ToolSelectionSource,\n\ttype ToolStatusReport,\n} from \"./tool-status.js\";\n\nexport function getActiveToolNames(this: AgentSession): string[] {\n\treturn this.agent.state.tools.map((t) => t.name);\n}\n\nexport function getCallableToolNames(this: AgentSession): string[] {\n\treturn getCallableTools(this).map((tool) => tool.name);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, and source metadata.\n */\n\nexport function getAllTools(this: AgentSession): ToolInfo[] {\n\treturn Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\t...(Object.hasOwn(definition, \"constrainedSampling\")\n\t\t\t? { constrainedSampling: definition.constrainedSampling }\n\t\t\t: {}),\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\texposure: definition.exposure ?? \"direct\",\n\t\tnamespace: definition.namespace,\n\t\tannotations: definition.annotations,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(this: AgentSession, name: string): ToolDefinition | undefined {\n\treturn this._toolDefinitions.get(name)?.definition;\n}\n\nfunction toolSelectionSource(session: AgentSession): ToolSelectionSource {\n\tif (session._usesDefaultTools) {\n\t\treturn session.settingsManager.getDefaultTools() === undefined ? \"built-in-defaults\" : \"default-tools-setting\";\n\t}\n\tif (session._allowedToolNames) return session._allowedToolNames.size === 0 ? \"no-tools\" : \"tools-allowlist\";\n\treturn (session._initialActiveToolNames?.length ?? 0) > 0 ? \"explicit-selection\" : \"no-built-in-tools\";\n}\n\n/**\n * Explain every registered tool (active or not, and why), where the tool selection came from,\n * and which selected names nothing registered. Format it with `formatToolStatus()`.\n */\nexport function getToolStatus(this: AgentSession): ToolStatusReport {\n\tconst source = toolSelectionSource(this);\n\tconst modifiers = [...this._defaultToolModifiers];\n\treturn buildToolStatusReport({\n\t\ttools: [...this._toolDefinitions.values()],\n\t\tactiveToolNames: this.getActiveToolNames(),\n\t\tselection: {\n\t\t\tsource,\n\t\t\tdescription: describeToolSelection(source, modifiers),\n\t\t\tnames: [...selectedToolNames(this)],\n\t\t\tmodifiers,\n\t\t},\n\t\tisExcluded: this._excludedTools,\n\t\tisAllowed: this._allowedTools,\n\t});\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\n\nexport function setActiveToolsByName(this: AgentSession, toolNames: string[]): void {\n\tconst previous = this.getActiveToolNames();\n\tthis._setActiveTools(toolNames);\n\tconst active = new Set(this.getActiveToolNames());\n\tif (previous.some((name) => !active.has(name))) this._pendingToolNames.clear();\n}\n\nexport function _setActiveTools(this: AgentSession, toolNames: string[]): void {\n\tconst tools = applyToolLoadout(this, toolNames);\n\tfor (const tool of tools) this._pendingToolNames.delete(tool.name);\n\tthis._rebuildSystemPrompt(tools.map((tool) => tool.name));\n}\n\n/** Whether compaction or branch summarization is currently running */\n\nexport function setScopedModels(\n\tthis: AgentSession,\n\tscopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>,\n): void {\n\tthis._scopedModels = scopedModels;\n}\n\n/** File-based prompt templates */\n\nexport function _normalizePromptSnippet(this: AgentSession, text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function _normalizePromptGuidelines(this: AgentSession, guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\nexport function _rebuildSystemPrompt(this: AgentSession, toolNames: string[]): void {\n\tconst validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tfor (const name of this._toolRegistry.keys()) {\n\t\tconst snippet = this._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = this._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = getSkillCatalog(this._resourceLoader).modelSkills();\n\tconst loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tthis._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({\n\t\tcwd: this._cwd,\n\t\tselectedModel: this.model,\n\t\tselectedThinkingLevel: this.thinkingLevel,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\thiddenTools: validToolNames.filter((name) => isToolDeclarationHidden(this, name)),\n\t\texcludedTools: this._excludedToolNames ? Array.from(this._excludedToolNames) : undefined,\n\t\ttoolSnippets,\n\t\ttoolGuidelines: Object.fromEntries(this._toolPromptGuidelines),\n\t});\n\tif (this._systemPromptTransform) {\n\t\tthis._baseSystemPromptOptions.forceSystemPrompt = this._systemPromptTransform(\n\t\t\tbuildSystemPrompt(this._baseSystemPromptOptions),\n\t\t);\n\t}\n}\n\nexport function _refreshBaseSystemPromptFromActiveTools(this: AgentSession): void {\n\tthis._rebuildSystemPrompt(this.getActiveToolNames());\n}\n\n/** Diff structured prompt state; executable tool changes are declared by the agent loop. */\nexport function _preparePromptAndToolLoadout(\n\tthis: AgentSession,\n\toptions: NormalizedBuildSystemPromptOptions,\n\tmessages: AgentMessage[] = this.agent.state.messages,\n): SystemMessage | undefined {\n\tconst current = getCurrentSystemMessage(messages);\n\tconst selected = [...new Set(options.selectedTools)].filter((name) => this._toolRegistry.has(name));\n\tconst recorded = (current?.toolsAdded ?? []).map((tool) => tool.name).filter((name) => selected.includes(name));\n\toptions.selectedTools = [...recorded, ...selected.filter((name) => !recorded.includes(name))];\n\toptions.selectedTools = applyToolLoadout(this, options.selectedTools).map((tool) => tool.name);\n\toptions.hiddenTools = options.selectedTools.filter((name) => isToolDeclarationHidden(this, name));\n\tconst sections = diffSystemPromptSections(current?.sections ?? {}, buildSystemPromptSections(options));\n\treturn sections ? { role: \"system\", content: \"\", sections, timestamp: Date.now() } : undefined;\n}\n\n/**\n * Restore registered tools from the selected transcript, not another branch's live state.\n *\n * `keepLoadout` is for a session whose creator already chose its loadout (every `createAgentSession`\n * does, from `--tools`, `--no-builtin-tools` and the `defaultTools` setting). That choice stays\n * authoritative for built-in tools, so only the other tools the transcript declared are added to it:\n * the ones an extension or `tool_search` activated, such as MCP tools that are not registered until\n * their server connects. Without it the transcript replaces the loadout.\n */\nexport function _restoreToolsFromTranscript(this: AgentSession, options?: { keepLoadout?: boolean }): void {\n\tthis._pendingToolNames.clear();\n\tconst current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);\n\tif (!current) return;\n\tconst declared = (current.toolsAdded ?? []).map((tool) => tool.name);\n\tif (!options?.keepLoadout) {\n\t\tthis._pendingToolNames = new Set(declared);\n\t\tthis._setActiveTools(declared);\n\t\treturn;\n\t}\n\tconst restored = declared.filter((name) => !this._baseToolDefinitions.has(name));\n\tthis._pendingToolNames = new Set(restored);\n\tthis._setActiveTools([...this.getActiveToolNames(), ...restored]);\n}\n\n// =========================================================================\n// Prompting\n// =========================================================================\n\n/**\n * Send a prompt to the agent.\n * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming\n * - Expands file-based prompt templates by default\n * - During streaming, queues via steer() or followUp() based on streamingBehavior option\n * - Validates model and API key before sending (when not streaming)\n * @throws Error if streaming and no streamingBehavior specified\n * @throws Error if no model selected or no API key available (when not streaming)\n */\n\nexport const agentSessionStateMethods = {\n\tgetActiveToolNames,\n\tgetCallableToolNames,\n\tgetAllTools,\n\tgetToolDefinition,\n\tgetToolStatus,\n\tsetActiveToolsByName,\n\t_setActiveTools,\n\tsetScopedModels,\n\t_normalizePromptSnippet,\n\t_normalizePromptGuidelines,\n\t_rebuildSystemPrompt,\n\t_preparePromptAndToolLoadout,\n\t_restoreToolsFromTranscript,\n\t_refreshBaseSystemPromptFromActiveTools,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-state.js","sourceRoot":"","sources":["../../src/core/agent-session-state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAsB,MAAM,gBAAgB,CAAC;AAI7E,OAAO,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAE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C,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAC/B,OAAO;IACR,CAAC;IACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;IACjF,IAAI,CAAC,iBAAiB,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC3C,IAAI,CAAC,eAAe,CAAC,kBAAkB,CAAC,CAAC,GAAG,IAAI,CAAC,kBAAkB,EAAE,EAAE,GAAG,QAAQ,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC;AAClG,CAAC;AAED,4EAA4E;AAC5E,YAAY;AACZ,4EAA4E;AAE5E;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,wBAAwB,GAAG;IACvC,kBAAkB;IAClB,oBAAoB;IACpB,WAAW;IACX,iBAAiB;IACjB,aAAa;IACb,oBAAoB;IACpB,eAAe;IACf,eAAe;IACf,uBAAuB;IACvB,0BAA0B;IAC1B,oBAAoB;IACpB,4BAA4B;IAC5B,2BAA2B;IAC3B,uCAAuC;CACvC,CAAC","sourcesContent":["import { getCurrentSystemMessage, type SystemMessage } from \"@bastani/pi-ai\";\nimport type { Api, Model } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { getCallableTools } from \"./agent-session-nested-tools.js\";\nimport type { ToolDefinition, ToolInfo } from \"./extensions/index.js\";\nimport { applyToolModifiers } from \"./settings-merge.js\";\nimport { getSkillCatalog } from \"./skill-catalog.ts\";\nimport {\n\tbuildSystemPrompt,\n\tbuildSystemPromptSections,\n\tdiffSystemPromptSections,\n\ttype NormalizedBuildSystemPromptOptions,\n\tnormalizeBuildSystemPromptOptions,\n} from \"./system-prompt.ts\";\nimport { applyToolLoadout, isToolDeclarationHidden } from \"./tool-loadout.js\";\nimport { selectedToolNames } from \"./tool-selection.ts\";\nimport {\n\tbuildToolStatusReport,\n\tdescribeToolSelection,\n\ttype ToolSelectionSource,\n\ttype ToolStatusReport,\n} from \"./tool-status.js\";\n\nexport function getActiveToolNames(this: AgentSession): string[] {\n\treturn this.agent.state.tools.map((t) => t.name);\n}\n\nexport function getCallableToolNames(this: AgentSession): string[] {\n\treturn getCallableTools(this).map((tool) => tool.name);\n}\n\n/**\n * Get all configured tools with name, description, parameter schema, and source metadata.\n */\n\nexport function getAllTools(this: AgentSession): ToolInfo[] {\n\treturn Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({\n\t\tname: definition.name,\n\t\tdescription: definition.description,\n\t\tparameters: definition.parameters,\n\t\t...(Object.hasOwn(definition, \"constrainedSampling\")\n\t\t\t? { constrainedSampling: definition.constrainedSampling }\n\t\t\t: {}),\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t\texposure: definition.exposure ?? \"direct\",\n\t\tnamespace: definition.namespace,\n\t\tannotations: definition.annotations,\n\t\tsourceInfo,\n\t}));\n}\n\nexport function getToolDefinition(this: AgentSession, name: string): ToolDefinition | undefined {\n\treturn this._toolDefinitions.get(name)?.definition;\n}\n\nfunction toolSelectionSource(session: AgentSession): ToolSelectionSource {\n\tif (session._usesDefaultTools) {\n\t\treturn session.settingsManager.getDefaultTools() === undefined ? \"built-in-defaults\" : \"default-tools-setting\";\n\t}\n\tif (session._allowedToolNames) return session._allowedToolNames.size === 0 ? \"no-tools\" : \"tools-allowlist\";\n\treturn (session._initialActiveToolNames?.length ?? 0) > 0 ? \"explicit-selection\" : \"no-built-in-tools\";\n}\n\n/**\n * Explain every registered tool (active or not, and why), where the tool selection came from,\n * and which selected names nothing registered. Format it with `formatToolStatus()`.\n */\nexport function getToolStatus(this: AgentSession): ToolStatusReport {\n\tconst source = toolSelectionSource(this);\n\tconst modifiers = [...this._defaultToolModifiers];\n\treturn buildToolStatusReport({\n\t\ttools: [...this._toolDefinitions.values()],\n\t\tactiveToolNames: this.getActiveToolNames(),\n\t\tselection: {\n\t\t\tsource,\n\t\t\tdescription: describeToolSelection(source, modifiers),\n\t\t\tnames: [...selectedToolNames(this)],\n\t\t\tmodifiers,\n\t\t},\n\t\tisExcluded: this._excludedTools,\n\t\tisAllowed: this._allowedTools,\n\t});\n}\n\n/**\n * Set active tools by name.\n * Only tools in the registry can be enabled. Unknown tool names are ignored.\n * Also rebuilds the system prompt to reflect the new tool set.\n * Changes take effect on the next agent turn.\n */\n\nexport function setActiveToolsByName(this: AgentSession, toolNames: string[]): void {\n\tconst previous = this.getActiveToolNames();\n\tthis._setActiveTools(toolNames);\n\tconst active = new Set(this.getActiveToolNames());\n\tif (previous.some((name) => !active.has(name))) this._pendingToolNames.clear();\n}\n\nexport function _setActiveTools(this: AgentSession, toolNames: string[]): void {\n\tconst tools = applyToolLoadout(this, toolNames);\n\tfor (const tool of tools) this._pendingToolNames.delete(tool.name);\n\tthis._rebuildSystemPrompt(tools.map((tool) => tool.name));\n}\n\n/** Whether compaction or branch summarization is currently running */\n\nexport function setScopedModels(\n\tthis: AgentSession,\n\tscopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>,\n): void {\n\tthis._scopedModels = scopedModels;\n}\n\n/** File-based prompt templates */\n\nexport function _normalizePromptSnippet(this: AgentSession, text: string | undefined): string | undefined {\n\tif (!text) return undefined;\n\tconst oneLine = text\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\treturn oneLine.length > 0 ? oneLine : undefined;\n}\n\nexport function _normalizePromptGuidelines(this: AgentSession, guidelines: string[] | undefined): string[] {\n\tif (!guidelines || guidelines.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst unique = new Set<string>();\n\tfor (const guideline of guidelines) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\tunique.add(normalized);\n\t\t}\n\t}\n\treturn Array.from(unique);\n}\n\nexport function _rebuildSystemPrompt(this: AgentSession, toolNames: string[]): void {\n\tconst validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));\n\tconst toolSnippets: Record<string, string> = {};\n\tfor (const name of this._toolRegistry.keys()) {\n\t\tconst snippet = this._toolPromptSnippets.get(name);\n\t\tif (snippet) {\n\t\t\ttoolSnippets[name] = snippet;\n\t\t}\n\t}\n\n\tconst loaderSystemPrompt = this._resourceLoader.getSystemPrompt();\n\tconst loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();\n\tconst appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join(\"\\n\\n\") : undefined;\n\tconst loadedSkills = getSkillCatalog(this._resourceLoader).modelSkills();\n\tconst loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;\n\n\tthis._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({\n\t\tcwd: this._cwd,\n\t\tselectedModel: this.model,\n\t\tselectedThinkingLevel: this.thinkingLevel,\n\t\tskills: loadedSkills,\n\t\tcontextFiles: loadedContextFiles,\n\t\tcustomPrompt: loaderSystemPrompt,\n\t\tappendSystemPrompt,\n\t\tselectedTools: validToolNames,\n\t\thiddenTools: validToolNames.filter((name) => isToolDeclarationHidden(this, name)),\n\t\texcludedTools: this._excludedToolNames ? Array.from(this._excludedToolNames) : undefined,\n\t\ttoolSnippets,\n\t\ttoolGuidelines: Object.fromEntries(this._toolPromptGuidelines),\n\t});\n\tif (this._systemPromptTransform) {\n\t\tthis._baseSystemPromptOptions.forceSystemPrompt = this._systemPromptTransform(\n\t\t\tbuildSystemPrompt(this._baseSystemPromptOptions),\n\t\t);\n\t}\n}\n\nexport function _refreshBaseSystemPromptFromActiveTools(this: AgentSession): void {\n\tthis._rebuildSystemPrompt(this.getActiveToolNames());\n}\n\n/** Diff structured prompt state; executable tool changes are declared by the agent loop. */\nexport function _preparePromptAndToolLoadout(\n\tthis: AgentSession,\n\toptions: NormalizedBuildSystemPromptOptions,\n\tmessages: AgentMessage[] = this.agent.state.messages,\n): SystemMessage | undefined {\n\tconst current = getCurrentSystemMessage(messages);\n\tconst selected = [...new Set(options.selectedTools)].filter((name) => this._toolRegistry.has(name));\n\tconst recorded = (current?.toolsAdded ?? []).map((tool) => tool.name).filter((name) => selected.includes(name));\n\toptions.selectedTools = [...recorded, ...selected.filter((name) => !recorded.includes(name))];\n\toptions.selectedTools = applyToolLoadout(this, options.selectedTools).map((tool) => tool.name);\n\toptions.hiddenTools = options.selectedTools.filter((name) => isToolDeclarationHidden(this, name));\n\tconst sections = diffSystemPromptSections(current?.sections ?? {}, buildSystemPromptSections(options));\n\treturn sections ? { role: \"system\", content: \"\", sections, timestamp: Date.now() } : undefined;\n}\n\nexport function preservesInitialToolLoadout(session: AgentSession): boolean {\n\treturn (\n\t\t(!session._usesDefaultTools && session._initialActiveToolNames !== undefined) ||\n\t\tsession._orchestrationContext?.kind === \"workflow-stage\" ||\n\t\t(session._subagentPolicy?.depth ?? 0) >= 1\n\t);\n}\n\n/**\n * Restore registered tools from the selected transcript, not another branch's live state.\n *\n * Explicit tool selections keep their built-in loadout while restoring dynamically registered tools.\n * Default selections restore the recorded loadout with any CLI modifiers applied.\n */\nexport function _restoreToolsFromTranscript(this: AgentSession, options?: { startup?: boolean }): void {\n\tthis._pendingToolNames.clear();\n\tconst current = getCurrentSystemMessage(this.sessionManager.buildSessionContext().messages);\n\tif (!current) return;\n\tconst keepLoadout = options?.startup && preservesInitialToolLoadout(this);\n\tconst modifiers = options?.startup && this._usesDefaultTools ? this._defaultToolModifiers : [];\n\tconst declared = applyToolModifiers(\n\t\t(current.toolsAdded ?? []).map((tool) => tool.name),\n\t\tmodifiers,\n\t);\n\tif (!keepLoadout) {\n\t\tthis._pendingToolNames = new Set(declared);\n\t\tthis._setActiveTools(declared);\n\t\treturn;\n\t}\n\tconst restored = declared.filter((name) => !this._baseToolDefinitions.has(name));\n\tthis._pendingToolNames = new Set(restored);\n\tthis._setActiveTools(applyToolModifiers([...this.getActiveToolNames(), ...restored], modifiers));\n}\n\n// =========================================================================\n// Prompting\n// =========================================================================\n\n/**\n * Send a prompt to the agent.\n * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming\n * - Expands file-based prompt templates by default\n * - During streaming, queues via steer() or followUp() based on streamingBehavior option\n * - Validates model and API key before sending (when not streaming)\n * @throws Error if streaming and no streamingBehavior specified\n * @throws Error if no model selected or no API key available (when not streaming)\n */\n\nexport const agentSessionStateMethods = {\n\tgetActiveToolNames,\n\tgetCallableToolNames,\n\tgetAllTools,\n\tgetToolDefinition,\n\tgetToolStatus,\n\tsetActiveToolsByName,\n\t_setActiveTools,\n\tsetScopedModels,\n\t_normalizePromptSnippet,\n\t_normalizePromptGuidelines,\n\t_rebuildSystemPrompt,\n\t_preparePromptAndToolLoadout,\n\t_restoreToolsFromTranscript,\n\t_refreshBaseSystemPromptFromActiveTools,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-tool-registry.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tool-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-tool-registry.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-tool-registry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAkB9F,wBAAgB,oBAAoB,CACnC,IAAI,EAAE,YAAY,EAClB,OAAO,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,wBAAwB,CAAC,EAAE,OAAO,CAAA;CAAE,GAC1E,IAAI,CA0HN;AAED,wBAAgB,aAAa,CAC5B,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE;IACR,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,UAAU,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,CAAC,CAAC;IAC3C,wBAAwB,CAAC,EAAE,OAAO,CAAC;IACnC,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB,GACC,IAAI,CAmHN;AAED,eAAO,MAAM,+BAA+B;;;CAG3C,CAAC"}
|
|
@@ -8,6 +8,7 @@ import { isRegisteredToolAllowed, activatesOnRegistration as toolActivatesOnRegi
|
|
|
8
8
|
import { createLocalBashOperations } from "./tools/bash.js";
|
|
9
9
|
import { buildMutationRequester } from "./tools/file-mutation-coordinator.js";
|
|
10
10
|
import { createAllToolDefinitions, getDefaultToolNames } from "./tools/index.js";
|
|
11
|
+
import { rejectMalformedToolArguments } from "./tools/malformed-tool-arguments.js";
|
|
11
12
|
import { createLocalPowerShellOperations } from "./tools/powershell.js";
|
|
12
13
|
import { resolveSessionTempDirPath } from "./tools/session-temp-dir.js";
|
|
13
14
|
import { scheduleToolExecution } from "./tools/tool-concurrency.js";
|
|
@@ -74,7 +75,8 @@ export function _refreshToolRegistry(options) {
|
|
|
74
75
|
? hostInputError("HumanInputCancelled")
|
|
75
76
|
: new Error("Operation aborted")
|
|
76
77
|
: undefined;
|
|
77
|
-
|
|
78
|
+
const guarded = rejectMalformedToolArguments(tool, () => this.agent.state.messages);
|
|
79
|
+
toolRegistry.set(tool.name, scheduleToolExecution(guarded, this._toolExecutionScheduler, abortError));
|
|
78
80
|
}
|
|
79
81
|
this._toolRegistry = toolRegistry;
|
|
80
82
|
const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isExposedTool(name) || selectedMcpNames.has(name));
|