@bastani/atomic 0.9.4-alpha.3 → 0.9.4-alpha.5
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 +13 -0
- package/dist/builtin/cursor/CHANGELOG.md +12 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +12 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/CHANGELOG.md +12 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +12 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +12 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +12 -0
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +8 -1
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +1 -0
- 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-prompt.d.ts +2 -0
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +6 -0
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +4 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/copilot-model-catalog.d.ts +18 -5
- package/dist/core/copilot-model-catalog.d.ts.map +1 -1
- package/dist/core/copilot-model-catalog.js +64 -5
- package/dist/core/copilot-model-catalog.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +2 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +11 -5
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/model-registry-builtins.d.ts.map +1 -1
- package/dist/core/model-registry-builtins.js +10 -2
- package/dist/core/model-registry-builtins.js.map +1 -1
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +4 -3
- package/dist/core/model-registry.js.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.d.ts.map +1 -1
- package/dist/modes/interactive/components/chat-session-host-events.js +8 -0
- package/dist/modes/interactive/components/chat-session-host-events.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +5 -0
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-model-routing.js +1 -4
- package/dist/modes/interactive/interactive-model-routing.js.map +1 -1
- package/docs/compaction.md +2 -0
- package/docs/providers.md +1 -0
- package/npm-shrinkwrap.json +23 -23
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { Agent, AgentEvent, AgentMessage, AgentState, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tContextCompactionParameters,\n\tContextCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tContextWindowReplayRequest,\n\tContextWindowReplaySource,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { SendMessageOptions } from \"./extensions/index.ts\";\n\nexport interface ContextCompactionApplyOptions {\n\tresolvePlannerAuth: () => Promise<{ apiKey: string; headers?: Record<string, string> } | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n}\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: { source: string; scope: \"temporary\"; origin: \"top-level\"; baseDir?: string };\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n}\n\nexport interface ContextWindowReplayResult {\n\tmodel: Model<Api>;\n\tcontextWindow: number;\n\twouldWarn: boolean;\n}\n\nexport interface AgentSessionMethodSurface {\n\treadonly orchestrationContext: import(\"./extensions/index.ts\").OrchestrationContext | undefined;\n\treadonly modelRegistry: ModelRegistry;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): void;\n\t_getRequiredRequestAuth(model: Model<Api>): Promise<{ apiKey: string; headers?: Record<string, string> }>;\n\t_installAgentToolHooks(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\t_reconnectToAgent(): void;\n\tdispose(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[]): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(nextModel: Model<Api>, previousModel: Model<Api> | undefined, source: \"set\" | \"cycle\" | \"restore\"): void;\n\t_emitModelSelect(nextModel: Model<Api>, previousModel: Model<Api> | undefined, source: \"set\" | \"cycle\" | \"restore\"): Promise<void>;\n\tsetModel(model: Model<Api>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\tgetAvailableContextWindows(): number[];\n\tsupportsContextWindowSelection(): boolean;\n\tsetContextWindow(contextWindow: number, options?: { persistDefault?: boolean }): void;\n\t_withContextWindowForModelSwitch(model: Model<Api>): Model<Api>;\n\t_shouldCarryCurrentContextWindowForModelSwitch(currentModel: Model<Api>, settingsDefaultContextWindow: number | undefined): boolean;\n\t_getSettingsContextWindowRequestForModel(model: Model<Api>): ContextWindowReplayRequest | undefined;\n\t_getContextWindowReplayForModel(model: Model<Api>, requestedContextWindow: number | undefined, source: ContextWindowReplaySource | undefined): ContextWindowReplayResult;\n\t_getDefaultContextWindowReplayForModel(model: Model<Api>, wouldWarn: boolean): ContextWindowReplayResult;\n\t_getResumeContextWindowReplayForModel(model: Model<Api>): ContextWindowReplayResult;\n\t_applyContextWindowReplay(contextWindow: number | undefined): void;\n\t_appendContextWindowChangeIfChanged(previousModel: Model<Api> | undefined, nextModel: Model<Api>): void;\n\n\t_applyContextVerbatimCompaction(options: ContextCompactionApplyOptions): Promise<ContextCompactionResult | undefined>;\n\tcompact(options?: Partial<ContextCompactionParameters>): Promise<ContextCompactionResult>;\n\tcontextCompact(): Promise<ContextCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_isCopilotServerCapBelowSelectedContextWindow(assistantMessage: AssistantMessage): boolean;\n\t_dropTrailingOverflowAssistantErrorIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_resumeAfterAutoCompaction(): void;\n\t_runAutoCompaction(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\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\t_bindExtensionCore(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_normalizePersistedGeminiToolArgs(message: AssistantMessage): void;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(command: string, onChunk?: (chunk: string) => void, options?: { excludeFromContext?: boolean; operations?: BashOperations }): Promise<BashResult>;\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void;\n\tabortBash(): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string): Promise<string>;\n\texportToJsonl(outputPath?: string): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface extends Pick<AgentSessionMethodSurface,\n\t| \"orchestrationContext\"\n\t| \"modelRegistry\"\n\t| \"state\"\n\t| \"model\"\n\t| \"thinkingLevel\"\n\t| \"isStreaming\"\n\t| \"systemPrompt\"\n\t| \"retryAttempt\"\n\t| \"isCompacting\"\n\t| \"messages\"\n\t| \"steeringMode\"\n\t| \"followUpMode\"\n\t| \"sessionFile\"\n\t| \"sessionId\"\n\t| \"sessionName\"\n\t| \"scopedModels\"\n\t| \"promptTemplates\"\n\t| \"pendingMessageCount\"\n\t| \"resourceLoader\"\n\t| \"autoCompactionEnabled\"\n\t| \"isRetrying\"\n\t| \"autoRetryEnabled\"\n\t| \"isBashRunning\"\n\t| \"hasPendingBashMessages\"\n\t| \"extensionRunner\"\n\t| \"subscribe\"\n\t| \"dispose\"\n\t| \"getActiveToolNames\"\n\t| \"getAllTools\"\n\t| \"getToolDefinition\"\n\t| \"setActiveToolsByName\"\n\t| \"setScopedModels\"\n\t| \"prompt\"\n\t| \"steer\"\n\t| \"followUp\"\n\t| \"sendCustomMessage\"\n\t| \"sendUserMessage\"\n\t| \"clearQueue\"\n\t| \"getSteeringMessages\"\n\t| \"getFollowUpMessages\"\n\t| \"abort\"\n\t| \"setModel\"\n\t| \"cycleModel\"\n\t| \"setThinkingLevel\"\n\t| \"cycleThinkingLevel\"\n\t| \"getAvailableThinkingLevels\"\n\t| \"supportsThinking\"\n\t| \"getAvailableContextWindows\"\n\t| \"supportsContextWindowSelection\"\n\t| \"setContextWindow\"\n\t| \"setSteeringMode\"\n\t| \"setFollowUpMode\"\n\t| \"compact\"\n\t| \"contextCompact\"\n\t| \"abortCompaction\"\n\t| \"abortBranchSummary\"\n\t| \"setAutoCompactionEnabled\"\n\t| \"bindExtensions\"\n\t| \"reload\"\n\t| \"abortRetry\"\n\t| \"setAutoRetryEnabled\"\n\t| \"executeBash\"\n\t| \"recordBashResult\"\n\t| \"abortBash\"\n\t| \"setSessionName\"\n\t| \"navigateTree\"\n\t| \"getUserMessagesForForking\"\n\t| \"getSessionStats\"\n\t| \"getContextUsage\"\n\t| \"exportToHtml\"\n\t| \"exportToJsonl\"\n\t| \"getLastAssistantText\"\n\t| \"createReplacedSessionContext\"\n\t| \"hasExtensionHandlers\"\n> {\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_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_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_compactionAbortController: AbortController | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortController: AbortController | undefined;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRegistry: ModelRegistry;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n}\n\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type { Agent, AgentEvent, AgentMessage, AgentState, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tContextCompactionParameters,\n\tContextCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tContextWindowReplayRequest,\n\tContextWindowReplaySource,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { SendMessageOptions } from \"./extensions/index.ts\";\n\nexport interface ContextCompactionApplyOptions {\n\tresolvePlannerAuth: () => Promise<{ apiKey: string; headers?: Record<string, string> } | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n}\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: { source: string; scope: \"temporary\"; origin: \"top-level\"; baseDir?: string };\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n}\n\nexport interface ContextWindowReplayResult {\n\tmodel: Model<Api>;\n\tcontextWindow: number;\n\twouldWarn: boolean;\n}\n\nexport interface AgentSessionMethodSurface {\n\treadonly orchestrationContext: import(\"./extensions/index.ts\").OrchestrationContext | undefined;\n\treadonly modelRegistry: ModelRegistry;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): void;\n\t_getRequiredRequestAuth(model: Model<Api>): Promise<{ apiKey: string; headers?: Record<string, string> }>;\n\t_installAgentToolHooks(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\t_reconnectToAgent(): void;\n\tdispose(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[]): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(nextModel: Model<Api>, previousModel: Model<Api> | undefined, source: \"set\" | \"cycle\" | \"restore\"): void;\n\t_emitModelSelect(nextModel: Model<Api>, previousModel: Model<Api> | undefined, source: \"set\" | \"cycle\" | \"restore\"): Promise<void>;\n\tsetModel(model: Model<Api>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\tgetAvailableContextWindows(): number[];\n\tsupportsContextWindowSelection(): boolean;\n\tsetContextWindow(contextWindow: number, options?: { persistDefault?: boolean }): void;\n\t_withContextWindowForModelSwitch(model: Model<Api>): Model<Api>;\n\t_shouldCarryCurrentContextWindowForModelSwitch(currentModel: Model<Api>, settingsDefaultContextWindow: number | undefined): boolean;\n\t_getSettingsContextWindowRequestForModel(model: Model<Api>): ContextWindowReplayRequest | undefined;\n\t_getContextWindowReplayForModel(model: Model<Api>, requestedContextWindow: number | undefined, source: ContextWindowReplaySource | undefined): ContextWindowReplayResult;\n\t_getDefaultContextWindowReplayForModel(model: Model<Api>, wouldWarn: boolean): ContextWindowReplayResult;\n\t_getResumeContextWindowReplayForModel(model: Model<Api>): ContextWindowReplayResult;\n\t_applyContextWindowReplay(contextWindow: number | undefined): void;\n\t_appendContextWindowChangeIfChanged(previousModel: Model<Api> | undefined, nextModel: Model<Api>): void;\n\n\t_applyContextVerbatimCompaction(options: ContextCompactionApplyOptions): Promise<ContextCompactionResult | undefined>;\n\tcompact(options?: Partial<ContextCompactionParameters>): Promise<ContextCompactionResult>;\n\tcontextCompact(): Promise<ContextCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_isCopilotServerCapBelowSelectedContextWindow(assistantMessage: AssistantMessage): boolean;\n\t_dropTrailingOverflowAssistantErrorIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_resumeAfterAutoCompaction(): void;\n\t_runAutoCompaction(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\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\t_bindExtensionCore(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_normalizePersistedGeminiToolArgs(message: AssistantMessage): void;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(command: string, onChunk?: (chunk: string) => void, options?: { excludeFromContext?: boolean; operations?: BashOperations }): Promise<BashResult>;\n\trecordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void;\n\tabortBash(): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(targetId: string, options?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string }): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string): Promise<string>;\n\texportToJsonl(outputPath?: string): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface extends Pick<AgentSessionMethodSurface,\n\t| \"orchestrationContext\"\n\t| \"modelRegistry\"\n\t| \"state\"\n\t| \"model\"\n\t| \"thinkingLevel\"\n\t| \"isStreaming\"\n\t| \"systemPrompt\"\n\t| \"retryAttempt\"\n\t| \"isCompacting\"\n\t| \"messages\"\n\t| \"steeringMode\"\n\t| \"followUpMode\"\n\t| \"sessionFile\"\n\t| \"sessionId\"\n\t| \"sessionName\"\n\t| \"scopedModels\"\n\t| \"promptTemplates\"\n\t| \"pendingMessageCount\"\n\t| \"resourceLoader\"\n\t| \"autoCompactionEnabled\"\n\t| \"isRetrying\"\n\t| \"autoRetryEnabled\"\n\t| \"isBashRunning\"\n\t| \"hasPendingBashMessages\"\n\t| \"extensionRunner\"\n\t| \"subscribe\"\n\t| \"dispose\"\n\t| \"getActiveToolNames\"\n\t| \"getAllTools\"\n\t| \"getToolDefinition\"\n\t| \"setActiveToolsByName\"\n\t| \"setScopedModels\"\n\t| \"prompt\"\n\t| \"steer\"\n\t| \"followUp\"\n\t| \"sendCustomMessage\"\n\t| \"sendUserMessage\"\n\t| \"clearQueue\"\n\t| \"getSteeringMessages\"\n\t| \"getFollowUpMessages\"\n\t| \"abort\"\n\t| \"setModel\"\n\t| \"cycleModel\"\n\t| \"setThinkingLevel\"\n\t| \"cycleThinkingLevel\"\n\t| \"getAvailableThinkingLevels\"\n\t| \"supportsThinking\"\n\t| \"getAvailableContextWindows\"\n\t| \"supportsContextWindowSelection\"\n\t| \"setContextWindow\"\n\t| \"setSteeringMode\"\n\t| \"setFollowUpMode\"\n\t| \"compact\"\n\t| \"contextCompact\"\n\t| \"abortCompaction\"\n\t| \"abortBranchSummary\"\n\t| \"setAutoCompactionEnabled\"\n\t| \"bindExtensions\"\n\t| \"reload\"\n\t| \"abortRetry\"\n\t| \"setAutoRetryEnabled\"\n\t| \"executeBash\"\n\t| \"recordBashResult\"\n\t| \"abortBash\"\n\t| \"setSessionName\"\n\t| \"navigateTree\"\n\t| \"getUserMessagesForForking\"\n\t| \"getSessionStats\"\n\t| \"getContextUsage\"\n\t| \"exportToHtml\"\n\t| \"exportToJsonl\"\n\t| \"getLastAssistantText\"\n\t| \"createReplacedSessionContext\"\n\t| \"hasExtensionHandlers\"\n> {\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_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_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_compactionAbortController: AbortController | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortController: AbortController | undefined;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRegistry: ModelRegistry;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n}\n\n"]}
|
|
@@ -4,6 +4,7 @@ import type { AgentSessionInternalSurface as AgentSession } from "./agent-sessio
|
|
|
4
4
|
import type { PromptOptions } from "./agent-session-types.ts";
|
|
5
5
|
export declare function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void>;
|
|
6
6
|
export declare function _runAgentPrompt(this: AgentSession, messages: AgentMessage | AgentMessage[]): Promise<void>;
|
|
7
|
+
export declare function _runAgentContinue(this: AgentSession): Promise<void>;
|
|
7
8
|
export declare function _continueQueuedAgentMessages(this: AgentSession): Promise<void>;
|
|
8
9
|
/**
|
|
9
10
|
* Try to execute a built-in slash command. Returns true if command was found and executed.
|
|
@@ -50,6 +51,7 @@ export declare function sendUserMessage(this: AgentSession, content: string | (T
|
|
|
50
51
|
export declare const agentSessionPromptMethods: {
|
|
51
52
|
prompt: typeof prompt;
|
|
52
53
|
_runAgentPrompt: typeof _runAgentPrompt;
|
|
54
|
+
_runAgentContinue: typeof _runAgentContinue;
|
|
53
55
|
_continueQueuedAgentMessages: typeof _continueQueuedAgentMessages;
|
|
54
56
|
_tryExecuteBuiltinSlashCommand: typeof _tryExecuteBuiltinSlashCommand;
|
|
55
57
|
_tryExecuteExtensionCommand: typeof _tryExecuteExtensionCommand;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-prompt.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAK9E,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,wBAAsB,MAAM,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,E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BAAyB;;;;;;;;;;CAUrC,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatAuthStorageLoadFailedMessage, formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tlet messages: AgentMessage[] | undefined;\n\n\ttry {\n\t\t// Handle slash commands first (execute immediately, even during streaming).\n\t\t// Builtin and extension commands manage their own LLM interaction via custom messages.\n\t\tif (expandPromptTemplates && text.startsWith(\"/\")) {\n\t\t\tconst handledBuiltin = await this._tryExecuteBuiltinSlashCommand(text);\n\t\t\tif (handledBuiltin) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst handledExtension = await this._tryExecuteExtensionCommand(text);\n\t\t\tif (handledExtension) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRegistry.hasConfiguredAuth(this.model)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst authLoadError = this._modelRegistry.authStorage.getLoadError();\n\t\t\tif (authLoadError) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformatAuthStorageLoadFailedMessage(this.model.provider, authLoadError),\n\t\t\t\t\t{ cause: authLoadError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt) {\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tawait this._runAgentPrompt(messages);\n}\n\n\nexport async function _runAgentPrompt(this: AgentSession, messages: AgentMessage | AgentMessage[]): Promise<void> {\n\tawait this.agent.prompt(messages);\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait command.handler(args, ctx);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession, \n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t});\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}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EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAWpG;AAED;;;;;;GAMG;AAEH,wBAAsB,QAAQ,CAAC,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAWvG;AAED;;GAEG;AAEH,wBAAsB,eAAe,CAAC,IAAI,EAAE,YAAY,EACvD,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,EAChD,OAAO,CAAC,EAAE;IAAE,SAAS,CAAC,EAAE,OAAO,GAAG,UAAU,CAAA;CAAE,GAC5C,OAAO,CAAC,IAAI,CAAC,CA4Bf;AAED;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB;;;;;;;;;;;CAWrC,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatAuthStorageLoadFailedMessage, formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tlet messages: AgentMessage[] | undefined;\n\n\ttry {\n\t\t// Handle slash commands first (execute immediately, even during streaming).\n\t\t// Builtin and extension commands manage their own LLM interaction via custom messages.\n\t\tif (expandPromptTemplates && text.startsWith(\"/\")) {\n\t\t\tconst handledBuiltin = await this._tryExecuteBuiltinSlashCommand(text);\n\t\t\tif (handledBuiltin) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst handledExtension = await this._tryExecuteExtensionCommand(text);\n\t\t\tif (handledExtension) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRegistry.hasConfiguredAuth(this.model)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst authLoadError = this._modelRegistry.authStorage.getLoadError();\n\t\t\tif (authLoadError) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformatAuthStorageLoadFailedMessage(this.model.provider, authLoadError),\n\t\t\t\t\t{ cause: authLoadError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt) {\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tawait this._runAgentPrompt(messages);\n}\n\n\nexport async function _runAgentPrompt(this: AgentSession, messages: AgentMessage | AgentMessage[]): Promise<void> {\n\tawait this.agent.prompt(messages);\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait command.handler(args, ctx);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession, \n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t});\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
|
|
@@ -148,6 +148,11 @@ export async function _runAgentPrompt(messages) {
|
|
|
148
148
|
await this.waitForRetry();
|
|
149
149
|
await this._continueQueuedAgentMessages();
|
|
150
150
|
}
|
|
151
|
+
export async function _runAgentContinue() {
|
|
152
|
+
await this.agent.continue();
|
|
153
|
+
await this.waitForRetry();
|
|
154
|
+
await this._continueQueuedAgentMessages();
|
|
155
|
+
}
|
|
151
156
|
export async function _continueQueuedAgentMessages() {
|
|
152
157
|
await this._agentEventQueue;
|
|
153
158
|
while (this.agent.hasQueuedMessages()) {
|
|
@@ -319,6 +324,7 @@ export async function sendUserMessage(content, options) {
|
|
|
319
324
|
export const agentSessionPromptMethods = {
|
|
320
325
|
prompt,
|
|
321
326
|
_runAgentPrompt,
|
|
327
|
+
_runAgentContinue,
|
|
322
328
|
_continueQueuedAgentMessages,
|
|
323
329
|
_tryExecuteBuiltinSlashCommand,
|
|
324
330
|
_tryExecuteExtensionCommand,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"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earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatAuthStorageLoadFailedMessage, formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tlet messages: AgentMessage[] | undefined;\n\n\ttry {\n\t\t// Handle slash commands first (execute immediately, even during streaming).\n\t\t// Builtin and extension commands manage their own LLM interaction via custom messages.\n\t\tif (expandPromptTemplates && text.startsWith(\"/\")) {\n\t\t\tconst handledBuiltin = await this._tryExecuteBuiltinSlashCommand(text);\n\t\t\tif (handledBuiltin) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst handledExtension = await this._tryExecuteExtensionCommand(text);\n\t\t\tif (handledExtension) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRegistry.hasConfiguredAuth(this.model)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst authLoadError = this._modelRegistry.authStorage.getLoadError();\n\t\t\tif (authLoadError) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformatAuthStorageLoadFailedMessage(this.model.provider, authLoadError),\n\t\t\t\t\t{ cause: authLoadError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt) {\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tawait this._runAgentPrompt(messages);\n}\n\n\nexport async function _runAgentPrompt(this: AgentSession, messages: AgentMessage | AgentMessage[]): Promise<void> {\n\tawait this.agent.prompt(messages);\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait command.handler(args, ctx);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession, \n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t});\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-prompt.js","sourceRoot":"","sources":["../../src/core/agent-session-prompt.ts"],"names":[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IAC5B,8BAA8B;IAC9B,2BAA2B;IAC3B,mBAAmB;IACnB,KAAK;IACL,QAAQ;IACR,eAAe;CACf,CAAC","sourcesContent":["import { readFileSync } from \"node:fs\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { ATOMIC_GUIDE_COMMAND_NAME, ATOMIC_GUIDE_HELP_CHOICES, atomicGuideModeForChoice, getAtomicGuideMessage, isAtomicGuideHelpChoice, normalizeAtomicGuideMode } from \"./atomic-guide-command.ts\";\nimport { formatAuthStorageLoadFailedMessage, formatNoApiKeyFoundMessage, formatNoModelSelectedMessage, formatUnresolvedModelMessage } from \"./auth-guidance.ts\";\nimport { expandPromptTemplate } from \"./prompt-templates.ts\";\nimport { stripFrontmatter } from \"../utils/frontmatter.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { PromptOptions } from \"./agent-session-types.ts\";\n\nexport async function prompt(this: AgentSession, text: string, options?: PromptOptions): Promise<void> {\n\tconst expandPromptTemplates = options?.expandPromptTemplates ?? true;\n\tconst preflightResult = options?.preflightResult;\n\tlet messages: AgentMessage[] | undefined;\n\n\ttry {\n\t\t// Handle slash commands first (execute immediately, even during streaming).\n\t\t// Builtin and extension commands manage their own LLM interaction via custom messages.\n\t\tif (expandPromptTemplates && text.startsWith(\"/\")) {\n\t\t\tconst handledBuiltin = await this._tryExecuteBuiltinSlashCommand(text);\n\t\t\tif (handledBuiltin) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst handledExtension = await this._tryExecuteExtensionCommand(text);\n\t\t\tif (handledExtension) {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Emit input event for extension interception (before skill/template expansion)\n\t\tlet currentText = text;\n\t\tlet currentImages = options?.images;\n\t\tif (this._extensionRunner.hasHandlers(\"input\")) {\n\t\t\tconst inputResult = await this._extensionRunner.emitInput(\n\t\t\t\tcurrentText,\n\t\t\t\tcurrentImages,\n\t\t\t\toptions?.source ?? \"interactive\",\n\t\t\t\tthis.isStreaming ? options?.streamingBehavior : undefined,\n\t\t\t);\n\t\t\tif (inputResult.action === \"handled\") {\n\t\t\t\tpreflightResult?.(true);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (inputResult.action === \"transform\") {\n\t\t\t\tcurrentText = inputResult.text;\n\t\t\t\tcurrentImages = inputResult.images ?? currentImages;\n\t\t\t}\n\t\t}\n\n\t\t// Expand skill commands (/skill:name args) and prompt templates (/template args)\n\t\tlet expandedText = currentText;\n\t\tif (expandPromptTemplates) {\n\t\t\texpandedText = this._expandSkillCommand(expandedText);\n\t\t\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\t\t}\n\n\t\t// If streaming, queue via steer() or followUp() based on option\n\t\tif (this.isStreaming) {\n\t\t\tif (!options?.streamingBehavior) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (options.streamingBehavior === \"followUp\") {\n\t\t\t\tawait this._queueFollowUp(expandedText, currentImages);\n\t\t\t} else {\n\t\t\t\tawait this._queueSteer(expandedText, currentImages);\n\t\t\t}\n\t\t\tpreflightResult?.(true);\n\t\t\treturn;\n\t\t}\n\n\t\t// Flush any pending bash messages before the new prompt\n\t\tthis._flushPendingBashMessages();\n\n\t\t// Validate model\n\t\tif (!this.model) {\n\t\t\tthrow new Error(formatNoModelSelectedMessage());\n\t\t}\n\n\t\t// Defensive guard: a model that never resolved to a real provider\n\t\t// (for example an unknown/unresolved model id that reached this path\n\t\t// as a bare string) has no `provider`, which would otherwise fail deep\n\t\t// in auth resolution as the confusing \"No API key found for undefined\".\n\t\t// Surface a clear, accurate \"unknown model\" error instead.\n\t\tconst resolvedProvider = (this.model as { provider?: unknown }).provider;\n\t\tif (typeof resolvedProvider !== \"string\" || resolvedProvider.length === 0) {\n\t\t\tthrow new Error(formatUnresolvedModelMessage(this.model));\n\t\t}\n\n\t\tif (!this._modelRegistry.hasConfiguredAuth(this.model)) {\n\t\t\t// A failed credential-store load (for example auth.json briefly locked\n\t\t\t// by a concurrent process, or invalid JSON) leaves an empty in-memory\n\t\t\t// credential set. That would otherwise be misreported here as\n\t\t\t// \"No API key found\" even though the credentials exist on disk. Surface\n\t\t\t// the real load failure instead so configured providers are not falsely\n\t\t\t// reported as unauthenticated (issue #1431).\n\t\t\tconst authLoadError = this._modelRegistry.authStorage.getLoadError();\n\t\t\tif (authLoadError) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\tformatAuthStorageLoadFailedMessage(this.model.provider, authLoadError),\n\t\t\t\t\t{ cause: authLoadError },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst isOAuth = this._modelRegistry.isUsingOAuth(this.model);\n\t\t\tif (isOAuth) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Authentication failed for \"${this.model.provider}\". ` +\n\t\t\t\t\t\t`Credentials may have expired or network is unavailable. ` +\n\t\t\t\t\t\t`Run '/login ${this.model.provider}' to re-authenticate.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow new Error(formatNoApiKeyFoundMessage(this.model.provider));\n\t\t}\n\n\t\t// Check if we need to compact before sending (catches aborted responses)\n\t\tconst lastAssistant = this._findLastAssistantMessage();\n\t\tif (lastAssistant) {\n\t\t\tawait this._checkCompaction(lastAssistant, false);\n\t\t}\n\n\t\t// Build messages array (custom message if any, then user message)\n\t\tmessages = [];\n\n\t\t// Add user message\n\t\tconst userContent: (TextContent | ImageContent)[] = [{ type: \"text\", text: expandedText }];\n\t\tif (currentImages) {\n\t\t\tuserContent.push(...currentImages);\n\t\t}\n\t\tmessages.push({\n\t\t\trole: \"user\",\n\t\t\tcontent: userContent,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\n\t\t// Inject any pending \"nextTurn\" messages as context alongside the user message\n\t\tfor (const msg of this._pendingNextTurnMessages) {\n\t\t\tmessages.push(msg);\n\t\t}\n\t\tthis._pendingNextTurnMessages = [];\n\n\t\t// Emit before_agent_start extension event\n\t\tconst result = await this._extensionRunner.emitBeforeAgentStart(\n\t\t\texpandedText,\n\t\t\tcurrentImages,\n\t\t\tthis._baseSystemPrompt,\n\t\t\tthis._baseSystemPromptOptions,\n\t\t);\n\t\t// Add all custom messages from extensions\n\t\tif (result?.messages) {\n\t\t\tfor (const msg of result.messages) {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"custom\",\n\t\t\t\t\tcustomType: msg.customType,\n\t\t\t\t\tcontent: msg.content,\n\t\t\t\t\tdisplay: msg.display,\n\t\t\t\t\tdetails: msg.details,\n\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t// Apply extension-modified system prompt, or reset to base\n\t\tif (result?.systemPrompt) {\n\t\t\tthis.agent.state.systemPrompt = result.systemPrompt;\n\t\t} else {\n\t\t\t// Ensure we're using the base prompt (in case previous turn had modifications)\n\t\t\tthis.agent.state.systemPrompt = this._baseSystemPrompt;\n\t\t}\n\t} catch (error) {\n\t\tpreflightResult?.(false);\n\t\tthrow error;\n\t}\n\n\tpreflightResult?.(true);\n\tawait this._runAgentPrompt(messages);\n}\n\n\nexport async function _runAgentPrompt(this: AgentSession, messages: AgentMessage | AgentMessage[]): Promise<void> {\n\tawait this.agent.prompt(messages);\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\nexport async function _runAgentContinue(this: AgentSession): Promise<void> {\n\tawait this.agent.continue();\n\tawait this.waitForRetry();\n\tawait this._continueQueuedAgentMessages();\n}\n\n\nexport async function _continueQueuedAgentMessages(this: AgentSession): Promise<void> {\n\tawait this._agentEventQueue;\n\n\twhile (this.agent.hasQueuedMessages()) {\n\t\tawait this.agent.continue();\n\t\tawait this.waitForRetry();\n\t\tawait this._agentEventQueue;\n\t}\n}\n\n/**\n * Try to execute a built-in slash command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteBuiltinSlashCommand(this: AgentSession, text: string): Promise<boolean> {\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tif (commandName !== ATOMIC_GUIDE_COMMAND_NAME) return false;\n\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\tconst mode = normalizeAtomicGuideMode(args);\n\tif (mode === \"help\" && this._extensionUIContext) {\n\t\tconst choice = await this._extensionUIContext.select(\"Atomic. Select where to start:\", [\n\t\t\t...ATOMIC_GUIDE_HELP_CHOICES,\n\t\t]);\n\t\tif (!choice || !isAtomicGuideHelpChoice(choice)) return true;\n\t\tawait this.sendCustomMessage(\n\t\t\t{\n\t\t\t\tcustomType: \"atomic\",\n\t\t\t\tcontent: getAtomicGuideMessage(atomicGuideModeForChoice(choice), this._cwd),\n\t\t\t\tdisplay: true,\n\t\t\t},\n\t\t\t{ triggerTurn: false },\n\t\t);\n\t\treturn true;\n\t}\n\n\tawait this.sendCustomMessage(\n\t\t{\n\t\t\tcustomType: \"atomic\",\n\t\t\tcontent: getAtomicGuideMessage(mode, this._cwd),\n\t\t\tdisplay: true,\n\t\t},\n\t\t{ triggerTurn: false },\n\t);\n\treturn true;\n}\n\n/**\n * Try to execute an extension command. Returns true if command was found and executed.\n */\n\nexport async function _tryExecuteExtensionCommand(this: AgentSession, text: string): Promise<boolean> {\n\t// Parse command name and args\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1);\n\n\tconst command = this._extensionRunner.getCommand(commandName);\n\tif (!command) return false;\n\n\t// Get command context from extension runner (includes session control methods)\n\tconst ctx = this._extensionRunner.createCommandContext();\n\n\ttry {\n\t\tawait command.handler(args, ctx);\n\t\treturn true;\n\t} catch (err) {\n\t\t// Emit error via extension runner\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: `command:${commandName}`,\n\t\t\tevent: \"command\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn true;\n\t}\n}\n\n/**\n * Expand skill commands (/skill:name args) to their full content.\n * Returns the expanded text, or the original text if not a skill command or skill not found.\n * Emits errors via extension runner if file read fails.\n */\n\nexport function _expandSkillCommand(this: AgentSession, text: string): string {\n\tif (!text.startsWith(\"/skill:\")) return text;\n\n\tconst spaceIndex = text.indexOf(\" \");\n\tconst skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);\n\tconst args = spaceIndex === -1 ? \"\" : text.slice(spaceIndex + 1).trim();\n\n\tconst skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);\n\tif (!skill) return text; // Unknown skill, pass through\n\n\ttry {\n\t\tconst content = readFileSync(skill.filePath, \"utf-8\");\n\t\tconst body = stripFrontmatter(content).trim();\n\t\tconst skillBlock = `<skill name=\"${skill.name}\" location=\"${skill.filePath}\">\\nReferences are relative to ${skill.baseDir}.\\n\\n${body}\\n</skill>`;\n\t\treturn args ? `${skillBlock}\\n\\n${args}` : skillBlock;\n\t} catch (err) {\n\t\t// Emit error like extension commands do\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: skill.filePath,\n\t\t\tevent: \"skill_expansion\",\n\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t});\n\t\treturn text; // Return original on error\n\t}\n}\n\n/**\n * Queue a steering message while the agent is running.\n * Delivered after the current assistant turn finishes executing its tool calls,\n * before the next LLM call.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function steer(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueSteer(expandedText, images);\n}\n\n/**\n * Queue a follow-up message to be processed after the agent finishes.\n * Delivered only when agent has no more tool calls or steering messages.\n * Expands skill commands and prompt templates. Errors on extension commands.\n * @param images Optional image attachments to include with the message\n * @throws Error if text is an extension command\n */\n\nexport async function followUp(this: AgentSession, text: string, images?: ImageContent[]): Promise<void> {\n\t// Check for extension commands (cannot be queued)\n\tif (text.startsWith(\"/\")) {\n\t\tthis._throwIfExtensionCommand(text);\n\t}\n\n\t// Expand skill commands and prompt templates\n\tlet expandedText = this._expandSkillCommand(text);\n\texpandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);\n\n\tawait this._queueFollowUp(expandedText, images);\n}\n\n/**\n * Internal: Queue a steering message (already expanded, no extension command check).\n */\n\nexport async function sendUserMessage(this: AgentSession, \n\tcontent: string | (TextContent | ImageContent)[],\n\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n): Promise<void> {\n\t// Normalize content to text string + optional images\n\tlet text: string;\n\tlet images: ImageContent[] | undefined;\n\n\tif (typeof content === \"string\") {\n\t\ttext = content;\n\t} else {\n\t\tconst textParts: string[] = [];\n\t\timages = [];\n\t\tfor (const part of content) {\n\t\t\tif (part.type === \"text\") {\n\t\t\t\ttextParts.push(part.text);\n\t\t\t} else {\n\t\t\t\timages.push(part);\n\t\t\t}\n\t\t}\n\t\ttext = textParts.join(\"\\n\");\n\t\tif (images.length === 0) images = undefined;\n\t}\n\n\t// Use prompt() with expandPromptTemplates: false to skip command handling and template expansion\n\tawait this.prompt(text, {\n\t\texpandPromptTemplates: false,\n\t\tstreamingBehavior: options?.deliverAs,\n\t\timages,\n\t\tsource: \"extension\",\n\t});\n}\n\n/**\n * Clear all queued messages and return them.\n * Useful for restoring to editor when user aborts.\n * @returns Object with steering and followUp arrays\n */\n\nexport const agentSessionPromptMethods = {\n\tprompt,\n\t_runAgentPrompt,\n\t_runAgentContinue,\n\t_continueQueuedAgentMessages,\n\t_tryExecuteBuiltinSlashCommand,\n\t_tryExecuteExtensionCommand,\n\t_expandSkillCommand,\n\tsteer,\n\tfollowUp,\n\tsendUserMessage,\n};\n"]}
|
|
@@ -46,6 +46,10 @@ export type AgentSessionEvent = AgentEvent | {
|
|
|
46
46
|
aborted: boolean;
|
|
47
47
|
willRetry: false;
|
|
48
48
|
errorMessage?: string;
|
|
49
|
+
} | {
|
|
50
|
+
type: "agent_continue_error";
|
|
51
|
+
source: "post_compaction";
|
|
52
|
+
errorMessage: string;
|
|
49
53
|
} | {
|
|
50
54
|
type: "auto_retry_start";
|
|
51
55
|
attempt: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-types.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,KAAK,EACL,UAAU,EACV,YAAY,EACZ,SAAS,EACT,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EACX,YAAY,EACZ,8BAA8B,EAC9B,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7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aAAa,GAAG,OAAO,CAE5E;AAED,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,CAAC","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nimport type { ContextCompactionResult } from \"./compaction/index.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\" }\n\t| { type: \"context_compaction_start\"; reason: \"manual\" }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"context_window_changed\"; contextWindow: number }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t }\n\t| {\n\t\t\ttype: \"context_compaction_end\";\n\t\t\treason: \"manual\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: false;\n\t\t\terrorMessage?: string;\n\t }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport type ContextWindowReplaySource = \"session\" | \"model-settings\" | \"global-settings\";\n\nexport interface ContextWindowReplayRequest {\n\tcontextWindow: number;\n\tsource: ContextWindowReplaySource;\n}\n\nexport const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = {\n\tallowCopilotLongContextFallback: true,\n} as const;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase().replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-types.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,KAAK,EACL,UAAU,EACV,YAAY,EACZ,SAAS,EACT,aAAa,EACb,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,GAAG,EAAE,gBAAgB,EAAE,YAAY,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAC5G,OAAO,KAAK,EACX,YAAY,EACZ,8BAA8B,EAC9B,sBAAsB,EACtB,aAAa,EACb,kBAAkB,EAClB,WAAW,EACX,oBAAoB,EACpB,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,UAAU,EAA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AM,eAAe,EAAE,aAAa,EAAgD,CAAC;AAE5F,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAE5E;AAED,MAAM,MAAM,yBAAyB,GAAG,gBAAgB,CAAC","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nimport type { ContextCompactionResult } from \"./compaction/index.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\" }\n\t| { type: \"context_compaction_start\"; reason: \"manual\" }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"context_window_changed\"; contextWindow: number }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t }\n\t| {\n\t\t\ttype: \"context_compaction_end\";\n\t\t\treason: \"manual\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: false;\n\t\t\terrorMessage?: string;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport type ContextWindowReplaySource = \"session\" | \"model-settings\" | \"global-settings\";\n\nexport interface ContextWindowReplayRequest {\n\tcontextWindow: number;\n\tsource: ContextWindowReplaySource;\n}\n\nexport const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = {\n\tallowCopilotLongContextFallback: true,\n} as const;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase().replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-types.js","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent-session-types.js","sourceRoot":"","sources":["../../src/core/agent-session-types.ts"],"names":[],"mappings":"AA2EA,MAAM,CAAC,MAAM,wCAAwC,GAAG;IACvD,+BAA+B,EAAE,IAAI;CAC5B,CAAC;AAsBX,MAAM,UAAU,sBAAsB,CAAC,KAA2C;IACjF,IAAI,CAAC,KAAK;QAAE,OAAO,EAAE,CAAC;IACtB,MAAM,OAAO,GAAmB,EAAE,CAAC;IACnC,OAAO,KAAK,CAAC,QAAQ,EAAE,EAAE,CAAC;QACzB,OAAO,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,OAAO,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,8BAA8B,CAAC,KAAyB;IACvE,MAAM,OAAO,GAAG,KAAK,EAAE,IAAI,EAAE,CAAC;IA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,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, ImageContent, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionUIContext,\n\tInputSource,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tShutdownHandler,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { CustomMessage } from \"./messages.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { SourceInfo } from \"./source-info.ts\";\nimport type { ContextCompactionResult } from \"./compaction/index.ts\";\n\nexport type AgentSessionEvent =\n\t| AgentEvent\n\t| {\n\t\t\ttype: \"queue_update\";\n\t\t\tsteering: readonly string[];\n\t\t\tfollowUp: readonly string[];\n\t }\n\t| { type: \"compaction_start\"; reason: \"manual\" | \"threshold\" | \"overflow\" }\n\t| { type: \"context_compaction_start\"; reason: \"manual\" }\n\t| { type: \"session_info_changed\"; name: string | undefined }\n\t| {\n\t\t\ttype: \"model_changed\";\n\t\t\tmodel: Model<Api>;\n\t\t\tpreviousModel: Model<Api> | undefined;\n\t\t\tsource: \"set\" | \"cycle\" | \"restore\";\n\t }\n\t| { type: \"thinking_level_changed\"; level: ThinkingLevel }\n\t| { type: \"context_window_changed\"; contextWindow: number }\n\t| {\n\t\t\ttype: \"compaction_end\";\n\t\t\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: boolean;\n\t\t\terrorMessage?: string;\n\t }\n\t| {\n\t\t\ttype: \"context_compaction_end\";\n\t\t\treason: \"manual\";\n\t\t\tresult: ContextCompactionResult | undefined;\n\t\t\taborted: boolean;\n\t\t\twillRetry: false;\n\t\t\terrorMessage?: string;\n\t }\n\t| { type: \"agent_continue_error\"; source: \"post_compaction\"; errorMessage: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nexport type AgentSessionEventListener = (event: AgentSessionEvent) => void;\n\nexport type ContextWindowReplaySource = \"session\" | \"model-settings\" | \"global-settings\";\n\nexport interface ContextWindowReplayRequest {\n\tcontextWindow: number;\n\tsource: ContextWindowReplaySource;\n}\n\nexport const COPILOT_CONTEXT_WINDOW_SELECTION_OPTIONS = {\n\tallowCopilotLongContextFallback: true,\n} as const;\n\nexport interface PendingAgentMessageQueue {\n\thasItems(): boolean;\n\tdrain(): AgentMessage[];\n}\n\nexport interface AgentQueueAccess {\n\treadonly steeringQueue?: PendingAgentMessageQueue;\n\treadonly followUpQueue?: PendingAgentMessageQueue;\n}\n\nexport interface DrainedAgentQueues {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport interface InterruptQueueHold {\n\treadonly steering: AgentMessage[];\n\treadonly followUp: AgentMessage[];\n}\n\nexport function drainAgentMessageQueue(queue: PendingAgentMessageQueue | undefined): AgentMessage[] {\n\tif (!queue) return [];\n\tconst drained: AgentMessage[] = [];\n\twhile (queue.hasItems()) {\n\t\tdrained.push(...queue.drain());\n\t}\n\treturn drained;\n}\n\nexport function normalizeInterruptAbortMessage(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim();\n\treturn trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nexport function isGenericAbortText(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase().replace(/[.!]+$/, \"\");\n\treturn (\n\t\tnormalized === \"operation aborted\" ||\n\t\tnormalized === \"the operation was aborted\" ||\n\t\tnormalized === \"request was aborted\" ||\n\t\tnormalized === \"this operation was aborted\" ||\n\t\tnormalized === \"extension custom ui aborted\"\n\t);\n}\n\nexport function isSingleGenericAbortTextContent(content: unknown): boolean {\n\treturn (\n\t\tArray.isArray(content) &&\n\t\tcontent.length === 1 &&\n\t\ttypeof content[0] === \"object\" &&\n\t\tcontent[0] !== null &&\n\t\t(content[0] as { type?: unknown }).type === \"text\" &&\n\t\ttypeof (content[0] as { text?: unknown }).text === \"string\" &&\n\t\tisGenericAbortText((content[0] as { text: string }).text)\n\t);\n}\n\nexport function replacementAbortContent(text: string): TextContent[] {\n\treturn [{ type: \"text\", text }];\n}\n\nexport interface AgentSessionConfig {\n\tagent: Agent;\n\tsessionManager: SessionManager;\n\tsettingsManager: SettingsManager;\n\tcwd: string;\n\tscopedModels?: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tresourceLoader: ResourceLoader;\n\tcustomTools?: ToolDefinition[];\n\tmodelRegistry: ModelRegistry;\n\tinitialActiveToolNames?: string[];\n\tallowedToolNames?: string[];\n\texcludedToolNames?: string[];\n\tbaseToolsOverride?: Record<string, AgentTool>;\n\textensionRunnerRef?: { current?: import(\"./extensions/index.ts\").ExtensionRunner };\n\tsessionStartEvent?: SessionStartEvent;\n\torchestrationContext?: OrchestrationContext;\n}\n\nexport interface ExtensionBindings {\n\tuiContext?: ExtensionUIContext;\n\tmode?: ExtensionMode;\n\tcommandContextActions?: ExtensionCommandContextActions;\n\tshutdownHandler?: ShutdownHandler;\n\tonError?: ExtensionErrorListener;\n}\n\nexport interface PromptOptions {\n\texpandPromptTemplates?: boolean;\n\timages?: ImageContent[];\n\tstreamingBehavior?: \"steer\" | \"followUp\";\n\tsource?: InputSource;\n\tpreflightResult?: (success: boolean) => void;\n}\n\nexport interface ModelCycleResult {\n\tmodel: Model<Api>;\n\tthinkingLevel: ThinkingLevel;\n\tisScoped: boolean;\n}\n\nexport interface SessionStats {\n\tsessionFile: string | undefined;\n\tsessionId: string;\n\tuserMessages: number;\n\tassistantMessages: number;\n\ttoolCalls: number;\n\ttoolResults: number;\n\ttotalMessages: number;\n\ttokens: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\ttotal: number;\n\t};\n\tcost: number;\n\tcontextUsage?: ContextUsage;\n}\n\nexport interface ToolDefinitionEntry {\n\tdefinition: ToolDefinition;\n\tsourceInfo: SourceInfo;\n}\n\nexport const THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\nexport function customMessageExcludesContext(message: CustomMessage): boolean {\n\treturn (message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext === true;\n}\n\nexport type AssistantMessageWithError = AssistantMessage;\n"]}
|
|
@@ -57,8 +57,18 @@ export declare const COPILOT_CATALOG_API_VERSION = "2026-06-01";
|
|
|
57
57
|
* for Copilot token refresh and model-policy calls, plus the dated API version.
|
|
58
58
|
*/
|
|
59
59
|
export declare const COPILOT_CATALOG_HEADERS: Readonly<Record<string, string>>;
|
|
60
|
-
/** Default
|
|
60
|
+
/** Default Copilot CAPI base URL for OAuth tokens when no route can be resolved. */
|
|
61
61
|
export declare const DEFAULT_COPILOT_API_BASE_URL = "https://api.individual.githubcopilot.com";
|
|
62
|
+
/** GitHub Copilot public routing hub for PAT-based `COPILOT_GITHUB_TOKEN` auth. */
|
|
63
|
+
export declare const COPILOT_PUBLIC_API_BASE_URL = "https://api.githubcopilot.com";
|
|
64
|
+
/** Enterprise Copilot CAPI host for GHES/non-github.com server URLs. */
|
|
65
|
+
export declare const COPILOT_ENTERPRISE_API_BASE_URL = "https://api.enterprise.githubcopilot.com";
|
|
66
|
+
export declare const COPILOT_GITHUB_TOKEN_ENV = "COPILOT_GITHUB_TOKEN";
|
|
67
|
+
export declare const COPILOT_API_TARGET_ENV = "COPILOT_API_TARGET";
|
|
68
|
+
export declare const GITHUB_COPILOT_BASE_URL_ENV = "GITHUB_COPILOT_BASE_URL";
|
|
69
|
+
export declare const GITHUB_SERVER_URL_ENV = "GITHUB_SERVER_URL";
|
|
70
|
+
type CopilotEnvironment = Record<string, string | undefined>;
|
|
71
|
+
export declare function copilotTokenFromEnvironment(env?: CopilotEnvironment): string | undefined;
|
|
62
72
|
/** Disk-cache freshness window, matching the Copilot CLI's list-models cache TTL. */
|
|
63
73
|
export declare const COPILOT_CATALOG_CACHE_TTL_MS: number;
|
|
64
74
|
/** Current on-disk cache schema version. */
|
|
@@ -67,11 +77,13 @@ export declare const COPILOT_CATALOG_CACHE_VERSION: 3;
|
|
|
67
77
|
* Resolve the Copilot CAPI base URL.
|
|
68
78
|
*
|
|
69
79
|
* Copilot access tokens embed a `proxy-ep=proxy.<host>` segment; the API host is the same host with
|
|
70
|
-
* `proxy.` swapped for `api.`.
|
|
71
|
-
*
|
|
72
|
-
*
|
|
80
|
+
* `proxy.` swapped for `api.`. Env-token routing resolves explicit `COPILOT_API_TARGET` /
|
|
81
|
+
* `GITHUB_COPILOT_BASE_URL` overrides, then `GITHUB_SERVER_URL` (`*.ghe.com` ->
|
|
82
|
+
* `copilot-api.<tenant>.ghe.com`, other non-github.com -> `api.enterprise.githubcopilot.com`),
|
|
83
|
+
* then the public Copilot routing hub `api.githubcopilot.com` for `COPILOT_GITHUB_TOKEN`. Stored
|
|
84
|
+
* OAuth credentials still fall back to the generated individual host when no token route is known.
|
|
73
85
|
*/
|
|
74
|
-
export declare function copilotApiBaseUrlFromToken(token: string | undefined, enterpriseDomain?: string): string;
|
|
86
|
+
export declare function copilotApiBaseUrlFromToken(token: string | undefined, enterpriseDomain?: string, env?: CopilotEnvironment): string;
|
|
75
87
|
/** Raw token limits parsed from a CAPI model entry. */
|
|
76
88
|
export interface CopilotModelLimits {
|
|
77
89
|
/** `capabilities.limits.max_prompt_tokens` — maximum prompt/input budget (the hard input cap). */
|
|
@@ -147,4 +159,5 @@ export declare function copilotCatalogCachePath(agentDir: string): string;
|
|
|
147
159
|
* was applied. No-op (returns false) without a token or a host-matching cached catalog.
|
|
148
160
|
*/
|
|
149
161
|
export declare function seedActiveCopilotModelCatalogFromCache(accessToken: string | undefined, cachePath: string, now?: number): boolean;
|
|
162
|
+
export {};
|
|
150
163
|
//# sourceMappingURL=copilot-model-catalog.d.ts.map
|