@bastani/atomic 0.9.11 → 0.9.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/dist/builtin/intercom/CHANGELOG.md +12 -0
- package/dist/builtin/intercom/closed-workflow-stage-message.ts +1 -1
- package/dist/builtin/intercom/contact-supervisor-tool.ts +1 -1
- package/dist/builtin/intercom/index-heavy.ts +2 -2
- package/dist/builtin/intercom/intercom-tool.ts +2 -2
- package/dist/builtin/intercom/intercom-utils.ts +1 -1
- package/dist/builtin/intercom/lifecycle.ts +2 -2
- package/dist/builtin/intercom/overlay.ts +2 -2
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/intercom/reply-tracker.ts +1 -1
- package/dist/builtin/intercom/subagent-relay.ts +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +12 -0
- package/dist/builtin/mcp/apps-cancellation.ts +1 -1
- package/dist/builtin/mcp/commands.ts +7 -7
- package/dist/builtin/mcp/direct-tool-executor.ts +1 -1
- package/dist/builtin/mcp/direct-tools.ts +3 -3
- package/dist/builtin/mcp/host-html-template.ts +1 -1
- package/dist/builtin/mcp/index.ts +3 -3
- package/dist/builtin/mcp/init.ts +6 -6
- package/dist/builtin/mcp/mcp-auth-flow.ts +1 -1
- package/dist/builtin/mcp/mcp-callback-server.ts +1 -1
- package/dist/builtin/mcp/mcp-panel-state.ts +1 -1
- package/dist/builtin/mcp/mcp-panel.ts +1 -1
- package/dist/builtin/mcp/metadata-cache.ts +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/mcp/proxy-call.ts +2 -2
- package/dist/builtin/mcp/proxy-info-modes.ts +2 -2
- package/dist/builtin/mcp/sampling-handler.ts +1 -1
- package/dist/builtin/mcp/server-manager.ts +3 -3
- package/dist/builtin/mcp/startup-warmup.ts +5 -5
- package/dist/builtin/mcp/state.ts +1 -1
- package/dist/builtin/mcp/tool-call-timeout.ts +1 -1
- package/dist/builtin/mcp/tool-metadata.ts +2 -2
- package/dist/builtin/mcp/types.ts +1 -1
- package/dist/builtin/mcp/ui-server.ts +4 -4
- package/dist/builtin/mcp/ui-session.ts +3 -3
- package/dist/builtin/subagents/CHANGELOG.md +12 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/src/runs/background/result-delivery-processor.ts +5 -5
- package/dist/builtin/subagents/src/runs/background/result-file-claims.ts +1 -1
- package/dist/builtin/subagents/src/runs/background/result-status.ts +2 -2
- package/dist/builtin/subagents/src/runs/background/result-watcher-data.ts +2 -2
- package/dist/builtin/subagents/src/runs/background/result-watcher.ts +1 -1
- package/dist/builtin/subagents/src/runs/foreground/execution-detach-reservations.ts +1 -1
- package/dist/builtin/subagents/src/shared/artifacts.ts +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +12 -0
- package/dist/builtin/web-access/index-heavy.ts +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +24 -0
- package/dist/builtin/workflows/README.md +1 -1
- package/dist/builtin/workflows/builtin/goal-prompts.ts +4 -1
- package/dist/builtin/workflows/builtin/ralph-core.ts +7 -4
- package/dist/builtin/workflows/builtin/ralph-forked-prompts.ts +5 -2
- package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +2 -1
- package/dist/builtin/workflows/builtin/ralph-runner.ts +2 -1
- package/dist/builtin/workflows/builtin/shared-prompts.ts +34 -7
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/authoring/keep-context.ts +46 -0
- package/dist/builtin/workflows/src/authoring.d.ts +11 -0
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +35 -17
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +4 -0
- package/dist/builtin/workflows/src/sdk-surface.ts +1 -0
- package/dist/core/agent-session-methods.d.ts +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/async/session-manager.d.ts +1 -1
- package/dist/core/async/session-manager.js.map +1 -1
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts +2 -2
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction-parameters.d.ts +5 -0
- package/dist/core/compaction/compaction-parameters.d.ts.map +1 -1
- package/dist/core/compaction/compaction-parameters.js +6 -5
- package/dist/core/compaction/compaction-parameters.js.map +1 -1
- package/dist/core/compaction/compaction-runner.d.ts +4 -0
- package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/compaction-runner.js +5 -1
- package/dist/core/compaction/compaction-runner.js.map +1 -1
- package/dist/core/compaction/compaction-types.d.ts +7 -1
- package/dist/core/compaction/compaction-types.d.ts.map +1 -1
- package/dist/core/compaction/compaction-types.js.map +1 -1
- package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
- package/dist/core/compaction/deleted-ranges.js +2 -0
- package/dist/core/compaction/deleted-ranges.js.map +1 -1
- package/dist/core/compaction/fallback-planner.d.ts +1 -1
- package/dist/core/compaction/fallback-planner.js.map +1 -1
- package/dist/core/compaction/range-planner.d.ts +3 -3
- package/dist/core/compaction/range-planner.d.ts.map +1 -1
- package/dist/core/compaction/range-planner.js +12 -14
- package/dist/core/compaction/range-planner.js.map +1 -1
- package/dist/core/compaction/transcript-serialization.d.ts +12 -0
- package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
- package/dist/core/compaction/transcript-serialization.js +99 -1
- package/dist/core/compaction/transcript-serialization.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +3 -0
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +16 -0
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/tools/bash-async-execution.d.ts +1 -1
- package/dist/core/tools/bash-async-execution.js.map +1 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/oversized-tool-result.js.map +1 -1
- package/dist/extensions/index.d.ts +1 -1
- package/dist/extensions/index.js.map +1 -1
- package/dist/extensions/llama/huggingface-ui.d.ts +2 -2
- package/dist/extensions/llama/huggingface-ui.js.map +1 -1
- package/dist/extensions/llama/index.d.ts +1 -1
- package/dist/extensions/llama/index.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts +1 -1
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/modes/interactive-engine/remote-queue-pause.d.ts +1 -1
- package/dist/modes/interactive-engine/remote-queue-pause.js.map +1 -1
- package/docs/compaction.md +24 -0
- package/docs/workflows.md +56 -0
- package/npm-shrinkwrap.json +39 -39
- package/package.json +3 -3
|
@@ -4,6 +4,7 @@ export const WORKFLOW_TOOL_DESCRIPTION =
|
|
|
4
4
|
"discover with list/get/inputs/models, list session runs with status (no runId; statusFilter narrows the list), inspect status/stages/stage details, " +
|
|
5
5
|
"send prompt answers or steering only while the root workflow is nonterminal, pause/resume/interrupt/quit runs, and reload workflow resources. " +
|
|
6
6
|
"For large stage handoffs, write context to files/artifacts, pass paths via reads, and prompt downstream agents to 'Read the file at <path>...' instead of injecting large previous text. " +
|
|
7
|
+
"Wrap critical parts of run inputs and steering messages in <keepContext>...</keepContext> so compaction preserves them verbatim in the stages that inherit them; tag role constraints, prohibitions, must-hold criteria, and identifiers, not background or bulk reference material. " +
|
|
7
8
|
"For transcripts, prefer status/stages/stage to get sessionFile/transcriptPath, " +
|
|
8
9
|
"quote the exact path without rewriting separators (Windows backslashes are valid), " +
|
|
9
10
|
"then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview. " +
|
|
@@ -37,6 +38,8 @@ export const DEFAULT_PROMPT_GUIDANCE: string[] = [
|
|
|
37
38
|
- Only skip workflows for tiny, deterministic, low-risk answers or direct edits where stage tracking clearly costs more than it adds, typically a single-file/no-test/no-review change or a simple answer.`,
|
|
38
39
|
`**Workflow discovery and lifecycle**:
|
|
39
40
|
- For unfamiliar named workflows, discover with \`action: "list"\`, inspect with \`action: "get"\` or \`action: "inputs"\`, and run with \`action: "run"\`, \`workflow\`, and validated \`inputs\`; do not invent workflow names or input keys.
|
|
41
|
+
- Wrap critical parts of the \`inputs\` you pass — objective, prompt, acceptance criteria — in \`<keepContext>\` / \`</keepContext>\`. Tagged text survives compaction verbatim regardless of the compression ratio, and stages inherit it because workflows inject your inputs into their prompts. A long stage is compacted repeatedly, and compaction ranks lines individually: a verbose restated objective outlives the one line that bounds it, so a stage can end up executing a coherent but unbounded version of what you asked for. Decide this per launch rather than tagging everything — tag role constraints, prohibitions, must-hold criteria, and identifiers such as a target branch, worktree path, or issue number; leave background, quoted issue text, and reference material untagged and pass bulk through files and \`reads\`. Protected lines count against the keep target rather than raising it, so an over-tagged input makes the evidence stages need compress harder.
|
|
42
|
+
- Tag steering the same way. A \`send\` amendment is authoritative and stages must carry it forward, but it arrives late in an already-long session and is exactly one short message competing with the whole transcript; \`<keepContext>\` around the requirement keeps it from being compacted away before the stage acts on it.
|
|
40
43
|
- In interactive chat, named workflow launches run in the background. Run \`/workflow connect <run>\` to see agents working and chat with and steer each stage. Inspection and control calls (\`status\`, \`stages\`, \`stage\`, \`transcript\`, \`send\`, \`pause\`, \`resume\`, \`interrupt\`, \`quit\`) remain available while work runs.
|
|
41
44
|
- \`workflow send\` is nonterminal-only: once the authoritative root run has completed, failed, skipped, been cancelled or killed, or ended terminal-blocked, start a new workflow if tracked work remains. Proceed inline only when the remaining task is small, deterministic, and low risk. Use explicit \`/workflow attach <run> <stage>\` for user-driven post-mortem chat; it does not resume or modify workflow execution.
|
|
42
45
|
- Natural-language instructions to create or use a worktree do not enable runner isolation. A named workflow must declare and implement any worktree and feature-branch inputs it supports; inspect its inputs and pass a distinct path and branch for each concurrent item. Reusable \`baseBranch\` binding creates a missing target as a detached checkout from that base or reuses an existing same-repository worktree as-is; neither case checks out a separate feature-branch input.
|
|
@@ -55,6 +58,7 @@ export const DEFAULT_PROMPT_GUIDANCE: string[] = [
|
|
|
55
58
|
- Every workflow invocation automatically receives one stable, non-default Intercom group. Intercom-capable stages inherit it, nested workflows keep the top-level invocation group, and subagents inherit their launching stage's group. Do not mint or thread group names through ordinary workflow definitions. Use an explicit \`group\` only for an intentional override: a named group or \`group: true\` creates a subgroup, while \`group: "default"\` opts into the shared default group. Stages without Intercom access receive no group, and \`contact_supervisor\` still crosses group boundaries for authorized escalation.
|
|
56
59
|
- Prefer \`ctx.tool(name, args, fn)\` for workflow-owned TypeScript operations with side effects, such as filesystem writes, network mutations, and external API actions. It creates a tracked, non-attachable durable graph node before invoking \`fn\`; it may be used before, between, after, or without model stages. A completed \`ctx.tool\` call is durably checkpointed with its serializable result, so resume replays that result without rerunning \`fn\`. For checks that may fail during a bounded repair loop, opt into \`failureMode: "return"\`, branch on the typed outcome, and pass only the needed error fields to the repair stage or artifact yourself; Atomic does not inject failure evidence into later prompts. Cancellation and storage faults still throw. Keep pure computation and side-effect-free transformations as ordinary TypeScript. Do not wrap agent-stage internals or every function call indiscriminately; this rule applies to side effects orchestrated directly by the workflow definition.
|
|
57
60
|
- Pass large stage context through files/artifacts and \`reads\` with an explicit \`Read the file at <path>...\` prompt rather than large \`previous\` payloads or injected session history.
|
|
61
|
+
- Wrap critical stage-prompt content in \`<keepContext>\` / \`</keepContext>\`. Tagged content survives compression verbatim regardless of the compression ratio, and every line of the span including the tag lines is protected. A long-running stage will be compacted, and compaction ranks lines individually: an objective is verbose and restated while the constraint that narrows it is usually one line, so the constraint is the cheaper deletion and what survives reads as broader permission than intended. Tag role constraints that bound a stage to part of the work, acceptance criteria and immutable contracts, explicit prohibitions, and identifiers a stage must not lose such as a target branch, worktree path, or run ID. Do not tag bulk context: protected lines count against the keep target rather than raising it, so a large protected span makes the surrounding transcript compress harder — tag the constraint, not the material it applies to.
|
|
58
62
|
- Separate implementation/review acceptance from explicitly authorized final actions such as PR/MR/review creation, release tagging, deployment, or publication. Stop implementation loops once acceptance is proven and carry a remaining final action separately.
|
|
59
63
|
- A model stage sees its local prompt, artifacts, tools, and reads, not the graph name or surrounding implementation. State the concrete action, evidence, and success criteria directly.`,
|
|
60
64
|
];
|
|
@@ -12,7 +12,7 @@ import type { ModelRuntime } from "./model-runtime.ts";
|
|
|
12
12
|
import type { PathMetadata } from "./package-manager.ts";
|
|
13
13
|
import type { PromptTemplate } from "./prompt-templates.ts";
|
|
14
14
|
import type { ResourceLoader } from "./resource-loader.ts";
|
|
15
|
-
import type { BranchSummaryEntry, SessionManager } from "./session-manager.
|
|
15
|
+
import type { BranchSummaryEntry, SessionManager } from "./session-manager.ts";
|
|
16
16
|
import type { SettingsManager } from "./settings-manager.ts";
|
|
17
17
|
import type { BuildSystemPromptOptions } from "./system-prompt.ts";
|
|
18
18
|
import type { BashOperations } from "./tools/bash.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.js\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.ts\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.ts\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\t_reconnectToAgent(): void;\n\tdispose(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[], promptStarted?: () => void): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: Partial<VerbatimCompactionParameters>): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string): Promise<string>;\n\texportToJsonl(outputPath?: string): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_fallbackAttemptedKeys: Set<string>;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, AbortController>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_asyncJobManager: AsyncJobManager;\n\t_asyncJobManagerSessionId: symbol;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-methods.js","sourceRoot":"","sources":["../../src/core/agent-session-methods.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n\tAgent,\n\tAgentEvent,\n\tAgentMessage,\n\tAgentState,\n\tAgentTool,\n\tThinkingLevel,\n} from \"@earendil-works/pi-agent-core\";\nimport type { ProviderHeaders } from \"@earendil-works/pi-ai\";\nimport type { Api, AssistantMessage, ImageContent, Message, Model, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport type {\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tAgentSessionReloadOptions,\n\tClearQueueOptions,\n\tDrainedAgentQueues,\n\tExtensionBindings,\n\tInterruptQueueHold,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport type {\n\tCompactionUrgency,\n\tPlannerAuth,\n\tVerbatimCompactionParameters,\n\tVerbatimCompactionResult,\n} from \"./compaction/index.ts\";\nimport type {\n\tContextUsage,\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tReplacedSessionContext,\n\tSendMessageOptions,\n\tSendMessagesOptions,\n\tSessionStartEvent,\n\tToolDefinition,\n\tToolInfo,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { PathMetadata } from \"./package-manager.ts\";\nimport type { PromptTemplate } from \"./prompt-templates.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { BranchSummaryEntry, SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport type { BashOperations } from \"./tools/bash.ts\";\n\nexport interface VerbatimCompactionApplyOptions {\n\t/** Per-model planner credentials; a borrowed fallback uses its own, never the session model's. */\n\tresolvePlannerAuth: (model: Model<Api>) => Promise<PlannerAuth | undefined>;\n\tabortController: AbortController;\n\tbackupLabel: string;\n\tcompression_ratio?: number;\n\tpreserve_recent?: number;\n\tquery?: string;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\t/** Only `load_bearing` may reach the context-destroying fresh rung. */\n\turgency: CompactionUrgency;\n\t/**\n\t * Admit a compactable region below the planner minimum.\n\t *\n\t * Narrow on purpose. Overflow recovery sets it because a real provider\n\t * overflow is already known, and the post-tool preflight sets it only when its\n\t * projected context is genuinely over the provider hard input limit. A\n\t * threshold crossing that still fits must not clear context: the follow-up\n\t * request can be sent as-is.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\nexport interface ExtensionResourcePathEntry {\n\tpath: string;\n\textensionPath: string;\n}\n\nexport interface ExtensionResourcePathResult {\n\tpath: string;\n\tmetadata: PathMetadata;\n}\n\nexport interface RuntimeBuildOptions {\n\tactiveToolNames?: string[];\n\tflagValues?: Map<string, boolean | string>;\n\tincludeAllExtensionTools?: boolean;\n}\n\nexport interface AgentSessionQueuePauseControl {\n\treadonly queuedMessagesPaused: boolean;\n\tpauseQueuedMessages(): void;\n\t/** Release the hold without starting a turn; true means raw queued work was released. */\n\tresumeQueuedMessages(beforeRelease?: () => void): Promise<boolean>;\n}\n\nexport interface AgentSessionMethodSurface extends AgentSessionQueuePauseControl {\n\treadonly orchestrationContext: import(\"./extensions/index.ts\").OrchestrationContext | undefined;\n\treadonly modelRuntime: ModelRuntime;\n\treadonly state: AgentState;\n\treadonly model: Model<Api> | undefined;\n\treadonly thinkingLevel: ThinkingLevel;\n\treadonly isStreaming: boolean;\n\treadonly systemPrompt: string;\n\treadonly retryAttempt: number;\n\treadonly isCompacting: boolean;\n\treadonly compactionReason?: import(\"./agent-session-types.ts\").CompactionReason;\n\treadonly messages: AgentMessage[];\n\treadonly steeringMode: \"all\" | \"one-at-a-time\";\n\treadonly followUpMode: \"all\" | \"one-at-a-time\";\n\treadonly sessionFile: string | undefined;\n\treadonly sessionId: string;\n\treadonly sessionName: string | undefined;\n\treadonly scopedModels: ReadonlyArray<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\treadonly promptTemplates: ReadonlyArray<PromptTemplate>;\n\treadonly pendingMessageCount: number;\n\treadonly resourceLoader: ResourceLoader;\n\treadonly autoCompactionEnabled: boolean;\n\treadonly isRetrying: boolean;\n\treadonly autoRetryEnabled: boolean;\n\treadonly isBashRunning: boolean;\n\treadonly hasPendingBashMessages: boolean;\n\treadonly extensionRunner: ExtensionRunner;\n\n\t_handleAgentEvent(event: AgentEvent): Promise<void> | void;\n\t_getRequiredRequestAuth(\n\t\tmodel: Model<Api>,\n\t): Promise<{ apiKey?: string; headers?: ProviderHeaders; baseUrl?: string }>;\n\t_installAgentToolHooks(): void;\n\t_installAgentNextTurnRefresh(): void;\n\t_emit(event: AgentSessionEvent): void;\n\t_emitQueueUpdate(): void;\n\t_createRetryPromiseForAgentEnd(event: AgentEvent): void;\n\t_findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined;\n\t_processAgentEvent(event: AgentEvent): Promise<void>;\n\t_applyInterruptAbortMessage(event: AgentEvent): void;\n\t_applyProviderErrorGuidance(event: AgentEvent): void;\n\t_resolveRetry(): void;\n\t_getUserMessageText(message: Message): string;\n\t_findLastAssistantMessage(): AssistantMessage | undefined;\n\t_replaceMessageInPlace(target: AgentMessage, replacement: AgentMessage): void;\n\t_emitExtensionEvent(event: AgentEvent): Promise<void>;\n\tsubscribe(listener: AgentSessionEventListener): () => void;\n\t_disconnectFromAgent(): void;\n\t_reconnectToAgent(): void;\n\tdispose(): void;\n\n\tgetActiveToolNames(): string[];\n\tgetAllTools(): ToolInfo[];\n\tgetToolDefinition(name: string): ToolDefinition | undefined;\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tsetScopedModels(scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>): void;\n\t_normalizePromptSnippet(text: string | undefined): string | undefined;\n\t_normalizePromptGuidelines(guidelines: string[] | undefined): string[];\n\t_rebuildSystemPrompt(toolNames: string[]): string;\n\t_refreshBaseSystemPromptFromActiveTools(): void;\n\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t_runAgentPrompt(messages: AgentMessage | AgentMessage[], promptStarted?: () => void): Promise<void>;\n\t_runAgentContinue(): Promise<void>;\n\t_continueQueuedAgentMessages(): Promise<void>;\n\t_tryExecuteBuiltinSlashCommand(text: string): Promise<boolean>;\n\t_tryExecuteExtensionCommand(text: string): Promise<boolean>;\n\t_expandSkillCommand(text: string): string;\n\tsteer(text: string, images?: ImageContent[]): Promise<void>;\n\tfollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\tsendUserMessage(\n\t\tcontent: string | (TextContent | ImageContent)[],\n\t\toptions?: { deliverAs?: \"steer\" | \"followUp\" },\n\t): Promise<void>;\n\n\t_queueSteer(text: string, images?: ImageContent[]): Promise<void>;\n\t_queueFollowUp(text: string, images?: ImageContent[]): Promise<void>;\n\t_throwIfExtensionCommand(text: string): void;\n\tsendCustomMessage<T = unknown>(\n\t\tmessage: Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">,\n\t\toptions?: SendMessageOptions,\n\t): Promise<void>;\n\tsendCustomMessages<T = unknown>(\n\t\tmessages: Array<Pick<CustomMessage<T>, \"customType\" | \"content\" | \"display\" | \"details\">>,\n\t\toptions?: SendMessagesOptions,\n\t): Promise<void>;\n\t_commitAdmittedCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_commitAdmittedCustomMessages<T>(messages: CustomMessage<T>[], options?: SendMessagesOptions): Promise<void>;\n\t_appendCustomMessage<T>(message: CustomMessage<T>): void;\n\t_enqueueInterruptCustomMessage<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_sendInterruptCustomMessageNow<T>(message: CustomMessage<T>, options?: SendMessageOptions): Promise<void>;\n\t_ensureActiveInterruptQueueHold(): InterruptQueueHold;\n\t_restoreAndClearActiveInterruptQueueHold(): void;\n\t_queueAgentMessage(message: AgentMessage, delivery: \"steer\" | \"followUp\"): void;\n\t_drainQueuedAgentMessages(): DrainedAgentQueues;\n\t_restoreQueuedAgentMessages(queues: DrainedAgentQueues): void;\n\tclearQueue(options?: ClearQueueOptions): { steering: string[]; followUp: string[] };\n\tgetSteeringMessages(): readonly string[];\n\tgetFollowUpMessages(): readonly string[];\n\tabort(): Promise<void>;\n\tsetSteeringMode(mode: \"all\" | \"one-at-a-time\"): void;\n\tsetFollowUpMode(mode: \"all\" | \"one-at-a-time\"): void;\n\n\t_emitModelChanged(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): void;\n\t_emitModelSelect(\n\t\tnextModel: Model<Api>,\n\t\tpreviousModel: Model<Api> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\" | \"fallback\",\n\t): Promise<void>;\n\tsetModel(model: Model<Api>): Promise<void>;\n\tcycleModel(direction?: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\t_cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined>;\n\tsetThinkingLevel(level: ThinkingLevel): void;\n\tcycleThinkingLevel(): ThinkingLevel | undefined;\n\tgetAvailableThinkingLevels(): ThinkingLevel[];\n\tsupportsThinking(): boolean;\n\t_getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel;\n\t_clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel;\n\n\t_applyVerbatimCompaction(options: VerbatimCompactionApplyOptions): Promise<VerbatimCompactionResult | undefined>;\n\tcompact(options?: Partial<VerbatimCompactionParameters>): Promise<VerbatimCompactionResult>;\n\tabortCompaction(): void;\n\tabortBranchSummary(): void;\n\t_checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<void>;\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent(): void;\n\t_schedulePostAutoCompactionContinuationProbe(reason: \"overflow\" | \"threshold\", willRetry: boolean): void;\n\t_awaitPendingPostCompactionContinuation(): Promise<void>;\n\t_resumeAfterAutoCompaction(): Promise<void>;\n\t_resumeAfterLengthTruncation(): void;\n\t_runAutoCompaction(reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void>;\n\t_preflightPostToolContext(messages: AgentMessage[], signal?: AbortSignal): Promise<AgentMessage[]>;\n\t_finishPostToolCompactionPreflight(messages: AgentMessage[]): AgentMessage[];\n\tsetAutoCompactionEnabled(enabled: boolean): void;\n\n\tbindExtensions(bindings: ExtensionBindings): Promise<void>;\n\textendResourcesFromExtensions(reason: \"startup\" | \"reload\"): Promise<void>;\n\tbuildExtensionResourcePaths(entries: ExtensionResourcePathEntry[]): ExtensionResourcePathResult[];\n\tgetExtensionSourceLabel(extensionPath: string): string;\n\t_applyExtensionBindings(runner: ExtensionRunner): void;\n\t_refreshCurrentModelFromRegistry(): void;\n\trefreshCurrentModelFromRegistry(): void;\n\t_bindExtensionCore(runner: ExtensionRunner): void;\n\t_refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void;\n\t_buildRuntime(options: RuntimeBuildOptions): void;\n\treload(options?: AgentSessionReloadOptions): Promise<void>;\n\n\t_isRetryableError(message: AssistantMessage): boolean;\n\t_isEmptyCompletion(message: AssistantMessage): boolean;\n\t_isSafetyRefusal(message: AssistantMessage): boolean;\n\t_handleRetryableError(message: AssistantMessage): Promise<boolean>;\n\t_trySwitchToFallbackModel(message: AssistantMessage): Promise<boolean>;\n\tabortRetry(): void;\n\twaitForRetry(): Promise<void>;\n\tsetAutoRetryEnabled(enabled: boolean): void;\n\n\texecuteBash(\n\t\tcommand: string,\n\t\tonChunk?: (chunk: string, channel: \"stdout\" | \"stderr\") => void,\n\t\toptions?: {\n\t\t\texcludeFromContext?: boolean;\n\t\t\tid?: string;\n\t\t\toperations?: BashOperations;\n\t\t\tpty?: boolean;\n\t\t\temitEvent?: boolean;\n\t\t\trecordResult?: boolean;\n\t\t},\n\t): Promise<BashResult>;\n\trecordBashResult(\n\t\tcommand: string,\n\t\tresult: BashResult,\n\t\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n\t): void;\n\tabortBash(id?: string): void;\n\t_flushPendingBashMessages(): void;\n\n\tsetSessionName(name: string): void;\n\tnavigateTree(\n\t\ttargetId: string,\n\t\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n\t): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }>;\n\tgetUserMessagesForForking(): Array<{ entryId: string; text: string }>;\n\t_extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string;\n\n\tgetSessionStats(): SessionStats;\n\tgetContextUsage(): ContextUsage | undefined;\n\texportToHtml(outputPath?: string): Promise<string>;\n\texportToJsonl(outputPath?: string): string;\n\tgetLastAssistantText(): string | undefined;\n\tcreateReplacedSessionContext(): ReplacedSessionContext;\n\tsealWorkflowStageGeneration(): void;\n\tcloseWorkflowStageGeneration(): Promise<void>;\n\ttransferWorkflowStageDeliveriesTo(target: object): void;\n\thasExtensionHandlers(eventType: string): boolean;\n}\n\nexport interface AgentSessionPublicSurface\n\textends Pick<\n\t\tAgentSessionMethodSurface,\n\t\t| \"orchestrationContext\"\n\t\t| \"modelRuntime\"\n\t\t| \"state\"\n\t\t| \"model\"\n\t\t| \"thinkingLevel\"\n\t\t| \"isStreaming\"\n\t\t| \"systemPrompt\"\n\t\t| \"retryAttempt\"\n\t\t| \"isCompacting\"\n\t\t| \"compactionReason\"\n\t\t| \"messages\"\n\t\t| \"steeringMode\"\n\t\t| \"followUpMode\"\n\t\t| \"sessionFile\"\n\t\t| \"sessionId\"\n\t\t| \"sessionName\"\n\t\t| \"scopedModels\"\n\t\t| \"promptTemplates\"\n\t\t| \"pendingMessageCount\"\n\t\t| \"resourceLoader\"\n\t\t| \"autoCompactionEnabled\"\n\t\t| \"isRetrying\"\n\t\t| \"autoRetryEnabled\"\n\t\t| \"isBashRunning\"\n\t\t| \"hasPendingBashMessages\"\n\t\t| \"extensionRunner\"\n\t\t| \"queuedMessagesPaused\"\n\t\t| \"pauseQueuedMessages\"\n\t\t| \"resumeQueuedMessages\"\n\t\t| \"subscribe\"\n\t\t| \"dispose\"\n\t\t| \"getActiveToolNames\"\n\t\t| \"getAllTools\"\n\t\t| \"getToolDefinition\"\n\t\t| \"setActiveToolsByName\"\n\t\t| \"setScopedModels\"\n\t\t| \"prompt\"\n\t\t| \"steer\"\n\t\t| \"followUp\"\n\t\t| \"sendCustomMessage\"\n\t\t| \"sendUserMessage\"\n\t\t| \"clearQueue\"\n\t\t| \"getSteeringMessages\"\n\t\t| \"getFollowUpMessages\"\n\t\t| \"abort\"\n\t\t| \"setModel\"\n\t\t| \"cycleModel\"\n\t\t| \"setThinkingLevel\"\n\t\t| \"cycleThinkingLevel\"\n\t\t| \"getAvailableThinkingLevels\"\n\t\t| \"supportsThinking\"\n\t\t| \"setSteeringMode\"\n\t\t| \"setFollowUpMode\"\n\t\t| \"compact\"\n\t\t| \"abortCompaction\"\n\t\t| \"abortBranchSummary\"\n\t\t| \"setAutoCompactionEnabled\"\n\t\t| \"bindExtensions\"\n\t\t| \"refreshCurrentModelFromRegistry\"\n\t\t| \"reload\"\n\t\t| \"abortRetry\"\n\t\t| \"setAutoRetryEnabled\"\n\t\t| \"executeBash\"\n\t\t| \"recordBashResult\"\n\t\t| \"abortBash\"\n\t\t| \"setSessionName\"\n\t\t| \"navigateTree\"\n\t\t| \"getUserMessagesForForking\"\n\t\t| \"getSessionStats\"\n\t\t| \"getContextUsage\"\n\t\t| \"exportToHtml\"\n\t\t| \"exportToJsonl\"\n\t\t| \"getLastAssistantText\"\n\t\t| \"createReplacedSessionContext\"\n\t\t| \"hasExtensionHandlers\"\n\t> {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n}\n\nexport interface AgentSessionInternalSurface extends AgentSessionMethodSurface, AgentSessionPublicSurface {\n\t_scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\t_fallbackModels: string[];\n\t_fallbackAttemptedKeys: Set<string>;\n\n\t_unsubscribeAgent?: () => void;\n\t_eventListeners: AgentSessionEventListener[];\n\t_agentEventQueue: Promise<void>;\n\t_steeringMessages: string[];\n\t_followUpMessages: string[];\n\t_interruptDeliveryQueue: Promise<void>;\n\t_pendingPostCompactionContinuation: Promise<void> | undefined;\n\t_postCompactionContinuationToken: number;\n\t_lengthContinuationAttempts: number;\n\t_outputBudgetErrorContinuationAttempts: number;\n\t_postToolCompactionPreflightError: string | undefined;\n\t_pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined;\n\t_terminatingToolCallIds: Set<string>;\n\t_pendingInterruptDeliveries: number;\n\t_activeInterruptQueueHold: InterruptQueueHold | undefined;\n\t_queuedMessagesPaused: boolean;\n\t_queuedMessagesPauseAbortBoundary: Promise<void> | undefined;\n\t_workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined;\n\t_activeInterruptAbortMessage: string | undefined;\n\t_pendingNextTurnMessages: CustomMessage[];\n\t_protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}>;\n\t_compactionAbortController: AbortController | undefined;\n\t_manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined;\n\t_autoCompactionAbortController: AbortController | undefined;\n\t_compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined;\n\t_overflowRecoveryAttempted: boolean;\n\t_branchSummaryAbortController: AbortController | undefined;\n\t_retryAbortController: AbortController | undefined;\n\t_retryAttempt: number;\n\t_retryPromise: Promise<void> | undefined;\n\t_retryResolve: (() => void) | undefined;\n\t_bashAbortControllers: Map<string | symbol, AbortController>;\n\t_pendingBashMessages: BashExecutionMessage[];\n\t_extensionRunner: ExtensionRunner;\n\t_turnIndex: number;\n\t_resourceLoader: ResourceLoader;\n\t_customTools: ToolDefinition[];\n\t_baseToolDefinitions: Map<string, ToolDefinition>;\n\t_cwd: string;\n\t_extensionRunnerRef?: { current?: ExtensionRunner };\n\t_initialActiveToolNames?: string[];\n\t_allowedToolNames?: Set<string>;\n\t_excludedToolNames?: Set<string>;\n\t_baseToolsOverride?: Record<string, AgentTool>;\n\t_sessionStartEvent: SessionStartEvent;\n\t_orchestrationContext?: OrchestrationContext;\n\t_extensionUIContext?: ExtensionUIContext;\n\t_extensionMode: ExtensionMode;\n\t_extensionCommandContextActions?: ExtensionCommandContextActions;\n\t_extensionShutdownHandler?: () => void;\n\t_extensionErrorListener?: ExtensionErrorListener;\n\t_extensionErrorUnsubscriber?: () => void;\n\t_modelRuntime: ModelRuntime;\n\t_toolRegistry: Map<string, AgentTool>;\n\t_toolDefinitions: Map<string, ToolDefinitionEntry>;\n\t_toolPromptSnippets: Map<string, string>;\n\t_toolPromptGuidelines: Map<string, string[]>;\n\t_baseSystemPrompt: string;\n\t_baseSystemPromptOptions: BuildSystemPromptOptions;\n\t_systemPromptOverride?: string;\n\t_lastAssistantMessage: AssistantMessage | undefined;\n\t_asyncJobManager: AsyncJobManager;\n\t_asyncJobManagerSessionId: symbol;\n\t_workflowStageAdmission: import(\"./workflow-stage-admission.ts\").WorkflowStageAdmissionBoundary | undefined;\n}\n"]}
|
|
@@ -16,7 +16,7 @@ import type { ExtensionCommandContextActions, ExtensionErrorListener, ExtensionM
|
|
|
16
16
|
import type { BashExecutionMessage, CustomMessage } from "./messages.ts";
|
|
17
17
|
import type { ModelRuntime } from "./model-runtime.ts";
|
|
18
18
|
import type { ResourceLoader } from "./resource-loader.ts";
|
|
19
|
-
import type { SessionManager } from "./session-manager.
|
|
19
|
+
import type { SessionManager } from "./session-manager.ts";
|
|
20
20
|
import type { SettingsManager } from "./settings-manager.ts";
|
|
21
21
|
import type { BuildSystemPromptOptions } from "./system-prompt.ts";
|
|
22
22
|
import { WorkflowStageAdmissionBoundary } from "./workflow-stage-admission.ts";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session.js","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,sCAAsC,EAAE,MAAM,0CAA0C,CAAC;AAClG,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE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ACzB,6BAA6B,EAC7B,iCAAiC,EACjC,qCAAqC,EACrC,oCAAoC,EACpC,+BAA+B,EAC/B,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,yBAAyB,CACzB,CAAC","sourcesContent":["/**\n * AgentSession - Core abstraction for agent lifecycle and session management.\n *\n * The historical import path is preserved here as a facade. Responsibilities are\n * implemented in sibling modules by lifecycle area so each authored source file\n * stays focused.\n */\n\nimport type { Agent, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { installAgentSessionAccessors } from \"./agent-session-accessors.ts\";\nimport { agentSessionAutoCompactionMethods } from \"./agent-session-auto-compaction.ts\";\nimport { agentSessionBashMethods } from \"./agent-session-bash.ts\";\nimport { agentSessionCompactionMethods } from \"./agent-session-compaction.ts\";\nimport { agentSessionCustomMessageCommitMethods } from \"./agent-session-custom-message-commit.ts\";\nimport { agentSessionEventsMethods } from \"./agent-session-events.ts\";\nimport { agentSessionExportMethods } from \"./agent-session-export.ts\";\nimport { agentSessionExtensionBindingsMethods } from \"./agent-session-extension-bindings.ts\";\nimport { agentSessionMessageQueueMethods } from \"./agent-session-message-queue.ts\";\nimport type { AgentSessionInternalSurface, AgentSessionPublicSurface } from \"./agent-session-methods.ts\";\nimport { agentSessionModelsMethods } from \"./agent-session-models.ts\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPostToolCompactionMethods } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPromptMethods } from \"./agent-session-prompt.ts\";\nimport { agentSessionRetryMethods } from \"./agent-session-retry.ts\";\nimport { agentSessionStateMethods } from \"./agent-session-state.ts\";\nimport { agentSessionToolHooksMethods } from \"./agent-session-tool-hooks.ts\";\nimport { agentSessionToolRegistryMethods } from \"./agent-session-tool-registry.ts\";\nimport { agentSessionTreeMethods } from \"./agent-session-tree.ts\";\nimport type {\n\tAgentSessionConfig,\n\tAgentSessionEventListener,\n\tInterruptQueueHold,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\nimport { createSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.js\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\nexport type { ParsedSkillBlock } from \"./agent-session-skill-block.ts\";\nexport { parseSkillBlock } from \"./agent-session-skill-block.ts\";\nexport type {\n\tAgentSessionConfig,\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tCompactionReason,\n\tExtensionBindings,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n} from \"./agent-session-types.ts\";\n\nclass AgentSessionBase {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n\n\tprotected _scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tprotected _fallbackModels: string[];\n\tprotected _fallbackAttemptedKeys: Set<string> = new Set();\n\tprotected _unsubscribeAgent?: () => void;\n\tprotected _eventListeners: AgentSessionEventListener[] = [];\n\tprotected _agentEventQueue: Promise<void> = Promise.resolve();\n\tprotected _steeringMessages: string[] = [];\n\tprotected _followUpMessages: string[] = [];\n\tprotected _interruptDeliveryQueue: Promise<void> = Promise.resolve();\n\tprotected _pendingInterruptDeliveries = 0;\n\tprotected _activeInterruptQueueHold: InterruptQueueHold | undefined = undefined;\n\tprotected _queuedMessagesPaused = false;\n\tprotected _queuedMessagesPauseAbortBoundary: Promise<void> | undefined = undefined;\n\tprotected _workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined = undefined;\n\tprotected _activeInterruptAbortMessage: string | undefined = undefined;\n\tprotected _pendingNextTurnMessages: CustomMessage[] = [];\n\tprotected _protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}> = [];\n\tprotected _compactionAbortController: AbortController | undefined = undefined;\n\tprotected _compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined = undefined;\n\tprotected _manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined = undefined;\n\tprotected _autoCompactionAbortController: AbortController | undefined = undefined;\n\tprotected _overflowRecoveryAttempted = false;\n\tprotected _pendingPostCompactionContinuation: Promise<void> | undefined = undefined;\n\tprotected _postCompactionContinuationToken = 0;\n\tprotected _lengthContinuationAttempts = 0;\n\tprotected _outputBudgetErrorContinuationAttempts = 0;\n\tprotected _postToolCompactionPreflightError: string | undefined = undefined;\n\tprotected _pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined = undefined;\n\tprotected _terminatingToolCallIds = new Set<string>();\n\tprotected _branchSummaryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAttempt = 0;\n\tprotected _retryPromise: Promise<void> | undefined = undefined;\n\tprotected _retryResolve: (() => void) | undefined = undefined;\n\tprotected _bashAbortControllers = new Map<string | symbol, AbortController>();\n\tprotected _pendingBashMessages: BashExecutionMessage[] = [];\n\tprotected _extensionRunner!: ExtensionRunner;\n\tprotected _turnIndex = 0;\n\tprotected _resourceLoader: ResourceLoader;\n\tprotected _customTools: ToolDefinition[];\n\tprotected _baseToolDefinitions: Map<string, ToolDefinition> = new Map();\n\tprotected _cwd: string;\n\tprotected _extensionRunnerRef?: { current?: ExtensionRunner };\n\tprotected _initialActiveToolNames?: string[];\n\tprotected _allowedToolNames?: Set<string>;\n\tprotected _excludedToolNames?: Set<string>;\n\tprotected _baseToolsOverride?: Record<string, AgentTool>;\n\tprotected _sessionStartEvent: SessionStartEvent;\n\tprotected _orchestrationContext?: OrchestrationContext;\n\tprotected _extensionUIContext?: ExtensionUIContext;\n\tprotected _extensionMode: ExtensionMode = \"print\";\n\tprotected _extensionCommandContextActions?: ExtensionCommandContextActions;\n\tprotected _extensionShutdownHandler?: () => void;\n\tprotected _extensionErrorListener?: ExtensionErrorListener;\n\tprotected _extensionErrorUnsubscriber?: () => void;\n\tprotected _modelRuntime: ModelRuntime;\n\tprotected _toolRegistry: Map<string, AgentTool> = new Map();\n\tprotected _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();\n\tprotected _toolPromptSnippets: Map<string, string> = new Map();\n\tprotected _toolPromptGuidelines: Map<string, string[]> = new Map();\n\tprotected _baseSystemPrompt = \"\";\n\tprotected _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\tprotected _systemPromptOverride?: string;\n\tprotected _lastAssistantMessage: AssistantMessage | undefined = undefined;\n\tprotected _asyncJobManager: AsyncJobManager;\n\tprotected _asyncJobManagerSessionId: symbol;\n\tprotected _workflowStageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tconstructor(config: AgentSessionConfig) {\n\t\tthis.agent = config.agent;\n\t\tthis.sessionManager = config.sessionManager;\n\t\tthis.settingsManager = config.settingsManager;\n\t\tthis._scopedModels = config.scopedModels ?? [];\n\t\tthis._fallbackModels = config.fallbackModels ?? [];\n\t\tthis._resourceLoader = config.resourceLoader;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._cwd = config.cwd;\n\t\tthis._modelRuntime = config.modelRuntime;\n\t\tthis._extensionRunnerRef = config.extensionRunnerRef;\n\t\tthis._initialActiveToolNames = config.initialActiveToolNames;\n\t\tthis._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;\n\t\tthis._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;\n\t\tthis._baseToolsOverride = config.baseToolsOverride;\n\t\tthis._sessionStartEvent = config.sessionStartEvent ?? { type: \"session_start\", reason: \"startup\" };\n\t\tthis._orchestrationContext = config.orchestrationContext;\n\t\tconst stageContext =\n\t\t\tconfig.orchestrationContext?.kind === \"workflow-stage\" ? config.orchestrationContext : undefined;\n\t\tthis._workflowStageAdmission =\n\t\t\tstageContext?.messageAdmission?.boundary ?? (stageContext ? new WorkflowStageAdmissionBoundary() : undefined);\n\t\tif (this._workflowStageAdmission && stageContext && stageContext.messageAdmission === undefined) {\n\t\t\t(\n\t\t\t\tstageContext as {\n\t\t\t\t\tmessageAdmission?: {\n\t\t\t\t\t\tboundary: WorkflowStageAdmissionBoundary;\n\t\t\t\t\t\textensionState: Map<string, object>;\n\t\t\t\t\t\tisOpen(): boolean;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t).messageAdmission = {\n\t\t\t\tboundary: this._workflowStageAdmission,\n\t\t\t\textensionState: new Map(),\n\t\t\t\tisOpen: () => this._workflowStageAdmission?.isOpen() === true,\n\t\t\t};\n\t\t}\n\t\tconst internals = this as unknown as AgentSessionInternalSurface;\n\t\tconst asyncJobManagerHandle = createSessionAsyncJobManager(internals);\n\t\tthis._asyncJobManager = asyncJobManagerHandle.manager;\n\t\tthis._asyncJobManagerSessionId = asyncJobManagerHandle.sessionId;\n\t\tinternals._handleAgentEvent = internals._handleAgentEvent.bind(this);\n\t\tthis._unsubscribeAgent = this.agent.subscribe(internals._handleAgentEvent);\n\t\tinternals._installAgentToolHooks();\n\t\tinternals._installAgentNextTurnRefresh();\n\t\tinternals._buildRuntime({\n\t\t\tactiveToolNames: this._initialActiveToolNames,\n\t\t\tincludeAllExtensionTools: true,\n\t\t});\n\t}\n}\n\nexport interface AgentSession extends AgentSessionBase, AgentSessionPublicSurface {}\n\nexport const AgentSession = AgentSessionBase as unknown as {\n\tnew (config: AgentSessionConfig): AgentSession;\n\treadonly prototype: AgentSession;\n};\n\ninstallAgentSessionAccessors(AgentSession.prototype as unknown as AgentSessionInternalSurface);\nObject.assign(\n\tAgentSession.prototype,\n\tagentSessionToolHooksMethods,\n\tagentSessionEventsMethods,\n\tagentSessionStateMethods,\n\tagentSessionPromptMethods,\n\tagentSessionCustomMessageCommitMethods,\n\tagentSessionMessageQueueMethods,\n\tagentSessionModelsMethods,\n\tagentSessionCompactionMethods,\n\tagentSessionAutoCompactionMethods,\n\tagentSessionPostToolCompactionMethods,\n\tagentSessionExtensionBindingsMethods,\n\tagentSessionToolRegistryMethods,\n\tagentSessionRetryMethods,\n\tagentSessionBashMethods,\n\tagentSessionTreeMethods,\n\tagentSessionExportMethods,\n);\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session.js","sourceRoot":"","sources":["../../src/core/agent-session.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,OAAO,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,EAAE,sCAAsC,EAAE,MAAM,0CAA0C,CAAC;AAClG,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,oCAAoC,EAAE,MAAM,uCAAuC,CAAC;AAC7F,OAAO,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AAEnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,EAAE,qCAAqC,EAAE,MAAM,yCAAyC,CA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The historical import path is preserved here as a facade. Responsibilities are\n * implemented in sibling modules by lifecycle area so each authored source file\n * stays focused.\n */\n\nimport type { Agent, AgentTool, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport type { Api, AssistantMessage, Model } from \"@earendil-works/pi-ai/compat\";\nimport { installAgentSessionAccessors } from \"./agent-session-accessors.ts\";\nimport { agentSessionAutoCompactionMethods } from \"./agent-session-auto-compaction.ts\";\nimport { agentSessionBashMethods } from \"./agent-session-bash.ts\";\nimport { agentSessionCompactionMethods } from \"./agent-session-compaction.ts\";\nimport { agentSessionCustomMessageCommitMethods } from \"./agent-session-custom-message-commit.ts\";\nimport { agentSessionEventsMethods } from \"./agent-session-events.ts\";\nimport { agentSessionExportMethods } from \"./agent-session-export.ts\";\nimport { agentSessionExtensionBindingsMethods } from \"./agent-session-extension-bindings.ts\";\nimport { agentSessionMessageQueueMethods } from \"./agent-session-message-queue.ts\";\nimport type { AgentSessionInternalSurface, AgentSessionPublicSurface } from \"./agent-session-methods.ts\";\nimport { agentSessionModelsMethods } from \"./agent-session-models.ts\";\nimport type { PendingPostToolCompactionGuard } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPostToolCompactionMethods } from \"./agent-session-post-tool-compaction.ts\";\nimport { agentSessionPromptMethods } from \"./agent-session-prompt.ts\";\nimport { agentSessionRetryMethods } from \"./agent-session-retry.ts\";\nimport { agentSessionStateMethods } from \"./agent-session-state.ts\";\nimport { agentSessionToolHooksMethods } from \"./agent-session-tool-hooks.ts\";\nimport { agentSessionToolRegistryMethods } from \"./agent-session-tool-registry.ts\";\nimport { agentSessionTreeMethods } from \"./agent-session-tree.ts\";\nimport type {\n\tAgentSessionConfig,\n\tAgentSessionEventListener,\n\tInterruptQueueHold,\n\tToolDefinitionEntry,\n} from \"./agent-session-types.ts\";\nimport type { AsyncJobManager } from \"./async/job-manager.js\";\nimport { createSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { VerbatimCompactionResult } from \"./compaction/index.ts\";\nimport type {\n\tExtensionCommandContextActions,\n\tExtensionErrorListener,\n\tExtensionMode,\n\tExtensionRunner,\n\tExtensionUIContext,\n\tOrchestrationContext,\n\tSessionStartEvent,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nimport type { BashExecutionMessage, CustomMessage } from \"./messages.ts\";\nimport type { ModelRuntime } from \"./model-runtime.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport type { SessionManager } from \"./session-manager.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"./system-prompt.ts\";\nimport { WorkflowStageAdmissionBoundary } from \"./workflow-stage-admission.ts\";\n\nexport type { ParsedSkillBlock } from \"./agent-session-skill-block.ts\";\nexport { parseSkillBlock } from \"./agent-session-skill-block.ts\";\nexport type {\n\tAgentSessionConfig,\n\tAgentSessionEvent,\n\tAgentSessionEventListener,\n\tCompactionReason,\n\tExtensionBindings,\n\tModelCycleResult,\n\tPromptOptions,\n\tSessionStats,\n} from \"./agent-session-types.ts\";\n\nclass AgentSessionBase {\n\treadonly agent: Agent;\n\treadonly sessionManager: SessionManager;\n\treadonly settingsManager: SettingsManager;\n\n\tprotected _scopedModels: Array<{ model: Model<Api>; thinkingLevel?: ThinkingLevel }>;\n\tprotected _fallbackModels: string[];\n\tprotected _fallbackAttemptedKeys: Set<string> = new Set();\n\tprotected _unsubscribeAgent?: () => void;\n\tprotected _eventListeners: AgentSessionEventListener[] = [];\n\tprotected _agentEventQueue: Promise<void> = Promise.resolve();\n\tprotected _steeringMessages: string[] = [];\n\tprotected _followUpMessages: string[] = [];\n\tprotected _interruptDeliveryQueue: Promise<void> = Promise.resolve();\n\tprotected _pendingInterruptDeliveries = 0;\n\tprotected _activeInterruptQueueHold: InterruptQueueHold | undefined = undefined;\n\tprotected _queuedMessagesPaused = false;\n\tprotected _queuedMessagesPauseAbortBoundary: Promise<void> | undefined = undefined;\n\tprotected _workflowStageDeliveryForwardTarget: AgentSessionInternalSurface | undefined = undefined;\n\tprotected _activeInterruptAbortMessage: string | undefined = undefined;\n\tprotected _pendingNextTurnMessages: CustomMessage[] = [];\n\tprotected _protectedStreamingCustomMessages: Array<{\n\t\tmessage: CustomMessage;\n\t\tdelivery: \"steer\" | \"followUp\";\n\t\tphase: \"queued\" | \"consumed-unpersisted\" | \"persistence-failed\";\n\t}> = [];\n\tprotected _compactionAbortController: AbortController | undefined = undefined;\n\tprotected _compactionReason: import(\"./agent-session-types.ts\").CompactionReason | undefined = undefined;\n\tprotected _manualCompactionPromise: Promise<VerbatimCompactionResult> | undefined = undefined;\n\tprotected _autoCompactionAbortController: AbortController | undefined = undefined;\n\tprotected _overflowRecoveryAttempted = false;\n\tprotected _pendingPostCompactionContinuation: Promise<void> | undefined = undefined;\n\tprotected _postCompactionContinuationToken = 0;\n\tprotected _lengthContinuationAttempts = 0;\n\tprotected _outputBudgetErrorContinuationAttempts = 0;\n\tprotected _postToolCompactionPreflightError: string | undefined = undefined;\n\tprotected _pendingPostToolCompactionGuard: PendingPostToolCompactionGuard | undefined = undefined;\n\tprotected _terminatingToolCallIds = new Set<string>();\n\tprotected _branchSummaryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAbortController: AbortController | undefined = undefined;\n\tprotected _retryAttempt = 0;\n\tprotected _retryPromise: Promise<void> | undefined = undefined;\n\tprotected _retryResolve: (() => void) | undefined = undefined;\n\tprotected _bashAbortControllers = new Map<string | symbol, AbortController>();\n\tprotected _pendingBashMessages: BashExecutionMessage[] = [];\n\tprotected _extensionRunner!: ExtensionRunner;\n\tprotected _turnIndex = 0;\n\tprotected _resourceLoader: ResourceLoader;\n\tprotected _customTools: ToolDefinition[];\n\tprotected _baseToolDefinitions: Map<string, ToolDefinition> = new Map();\n\tprotected _cwd: string;\n\tprotected _extensionRunnerRef?: { current?: ExtensionRunner };\n\tprotected _initialActiveToolNames?: string[];\n\tprotected _allowedToolNames?: Set<string>;\n\tprotected _excludedToolNames?: Set<string>;\n\tprotected _baseToolsOverride?: Record<string, AgentTool>;\n\tprotected _sessionStartEvent: SessionStartEvent;\n\tprotected _orchestrationContext?: OrchestrationContext;\n\tprotected _extensionUIContext?: ExtensionUIContext;\n\tprotected _extensionMode: ExtensionMode = \"print\";\n\tprotected _extensionCommandContextActions?: ExtensionCommandContextActions;\n\tprotected _extensionShutdownHandler?: () => void;\n\tprotected _extensionErrorListener?: ExtensionErrorListener;\n\tprotected _extensionErrorUnsubscriber?: () => void;\n\tprotected _modelRuntime: ModelRuntime;\n\tprotected _toolRegistry: Map<string, AgentTool> = new Map();\n\tprotected _toolDefinitions: Map<string, ToolDefinitionEntry> = new Map();\n\tprotected _toolPromptSnippets: Map<string, string> = new Map();\n\tprotected _toolPromptGuidelines: Map<string, string[]> = new Map();\n\tprotected _baseSystemPrompt = \"\";\n\tprotected _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\tprotected _systemPromptOverride?: string;\n\tprotected _lastAssistantMessage: AssistantMessage | undefined = undefined;\n\tprotected _asyncJobManager: AsyncJobManager;\n\tprotected _asyncJobManagerSessionId: symbol;\n\tprotected _workflowStageAdmission: WorkflowStageAdmissionBoundary | undefined;\n\tconstructor(config: AgentSessionConfig) {\n\t\tthis.agent = config.agent;\n\t\tthis.sessionManager = config.sessionManager;\n\t\tthis.settingsManager = config.settingsManager;\n\t\tthis._scopedModels = config.scopedModels ?? [];\n\t\tthis._fallbackModels = config.fallbackModels ?? [];\n\t\tthis._resourceLoader = config.resourceLoader;\n\t\tthis._customTools = config.customTools ?? [];\n\t\tthis._cwd = config.cwd;\n\t\tthis._modelRuntime = config.modelRuntime;\n\t\tthis._extensionRunnerRef = config.extensionRunnerRef;\n\t\tthis._initialActiveToolNames = config.initialActiveToolNames;\n\t\tthis._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;\n\t\tthis._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;\n\t\tthis._baseToolsOverride = config.baseToolsOverride;\n\t\tthis._sessionStartEvent = config.sessionStartEvent ?? { type: \"session_start\", reason: \"startup\" };\n\t\tthis._orchestrationContext = config.orchestrationContext;\n\t\tconst stageContext =\n\t\t\tconfig.orchestrationContext?.kind === \"workflow-stage\" ? config.orchestrationContext : undefined;\n\t\tthis._workflowStageAdmission =\n\t\t\tstageContext?.messageAdmission?.boundary ?? (stageContext ? new WorkflowStageAdmissionBoundary() : undefined);\n\t\tif (this._workflowStageAdmission && stageContext && stageContext.messageAdmission === undefined) {\n\t\t\t(\n\t\t\t\tstageContext as {\n\t\t\t\t\tmessageAdmission?: {\n\t\t\t\t\t\tboundary: WorkflowStageAdmissionBoundary;\n\t\t\t\t\t\textensionState: Map<string, object>;\n\t\t\t\t\t\tisOpen(): boolean;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t).messageAdmission = {\n\t\t\t\tboundary: this._workflowStageAdmission,\n\t\t\t\textensionState: new Map(),\n\t\t\t\tisOpen: () => this._workflowStageAdmission?.isOpen() === true,\n\t\t\t};\n\t\t}\n\t\tconst internals = this as unknown as AgentSessionInternalSurface;\n\t\tconst asyncJobManagerHandle = createSessionAsyncJobManager(internals);\n\t\tthis._asyncJobManager = asyncJobManagerHandle.manager;\n\t\tthis._asyncJobManagerSessionId = asyncJobManagerHandle.sessionId;\n\t\tinternals._handleAgentEvent = internals._handleAgentEvent.bind(this);\n\t\tthis._unsubscribeAgent = this.agent.subscribe(internals._handleAgentEvent);\n\t\tinternals._installAgentToolHooks();\n\t\tinternals._installAgentNextTurnRefresh();\n\t\tinternals._buildRuntime({\n\t\t\tactiveToolNames: this._initialActiveToolNames,\n\t\t\tincludeAllExtensionTools: true,\n\t\t});\n\t}\n}\n\nexport interface AgentSession extends AgentSessionBase, AgentSessionPublicSurface {}\n\nexport const AgentSession = AgentSessionBase as unknown as {\n\tnew (config: AgentSessionConfig): AgentSession;\n\treadonly prototype: AgentSession;\n};\n\ninstallAgentSessionAccessors(AgentSession.prototype as unknown as AgentSessionInternalSurface);\nObject.assign(\n\tAgentSession.prototype,\n\tagentSessionToolHooksMethods,\n\tagentSessionEventsMethods,\n\tagentSessionStateMethods,\n\tagentSessionPromptMethods,\n\tagentSessionCustomMessageCommitMethods,\n\tagentSessionMessageQueueMethods,\n\tagentSessionModelsMethods,\n\tagentSessionCompactionMethods,\n\tagentSessionAutoCompactionMethods,\n\tagentSessionPostToolCompactionMethods,\n\tagentSessionExtensionBindingsMethods,\n\tagentSessionToolRegistryMethods,\n\tagentSessionRetryMethods,\n\tagentSessionBashMethods,\n\tagentSessionTreeMethods,\n\tagentSessionExportMethods,\n);\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { SendMessageOptions } from "../extensions/index.
|
|
1
|
+
import type { SendMessageOptions } from "../extensions/index.ts";
|
|
2
2
|
import { AsyncJobManager } from "./job-manager.js";
|
|
3
3
|
import type { AsyncJobDeliveryHandler, AsyncJobDeliveryMessage } from "./types.js";
|
|
4
4
|
export interface SessionAsyncJobManagerHandle {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-manager.js","sourceRoot":"","sources":["../../../src/core/async/session-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAYnD,MAAM,UAAU,iCAAiC,CAChD,OAA6B,EAC7B,OAAyB,EACzB,SAAkB;IAElB,OAAO,KAAK,EAAE,OAAgC,EAAE,EAAE;QACjD,MAAM,OAAO,GAAG,GAAG,EAAE,CACpB,OAAO,EAAE,QAAQ,KAAK,IAAI;YAC1B,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,IAAI;YAC7D,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,EAAE,iBAAiB,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC;QAC7E,IAAI,OAAO,EAAE;YAAE,OAAO;QACtB,MAAM,OAAO,CAAC,iBAAiB,CAAC,OAAO,EAAE;YACxC,SAAS,EAAE,UAAU;YACrB,WAAW,EAAE,IAAI;YACjB,iBAAiB,EAAE,aAAa,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE;SACvD,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAED,MAAM,UAAU,4BAA4B,CAAC,OAA6B;IACzE,MAAM,QAAQ,GAAG,eAAe,CAAC,QAAQ,EAAE,CAAC;IAC5C,IAAI,QAAQ;QAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,QAAQ,CAAC,eAAe,EAAE,EAAE,CAAC;IAC/F,IAAI,OAAwB,CAAC;IAC7B,OAAO,GAAG,IAAI,eAAe,CAAC;QAC7B,aAAa,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,iCAAiC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC;KACxF,CAAC,CAAC;IACH,eAAe,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,eAAe,EAAE,EAAE,CAAC;AACtE,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC5C,OAAoC,EACpC,SAA6B;IAE7B,IAAI,CAAC,OAAO,IAAI,CAAC,SAAS;QAAE,OAAO;IACnC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;IAClC,IAAI,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC,QAAQ,EAAE,KAAK,OAAO;QAAE,eAAe,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;AACxG,CAAC","sourcesContent":["import type { SendMessageOptions } from \"../extensions/index.
|
|
1
|
+
{"version":3,"file":"session-manager.js","sourceRoot":"","sources":["../../../src/core/async/session-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAYnD,MAAM,UAAU,iCAAiC,CAChD,OAA6B,EAC7B,OAAyB,E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;QAAE,OAAO;IACnC,OAAO,CAAC,cAAc,CAAC,SAAS,CAAC,CAAC;IAClC,IAAI,OAAO,CAAC,QAAQ,IAAI,eAAe,CAAC,QAAQ,EAAE,KAAK,OAAO;QAAE,eAAe,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;AACxG,CAAC","sourcesContent":["import type { SendMessageOptions } from \"../extensions/index.ts\";\nimport { AsyncJobManager } from \"./job-manager.js\";\nimport type { AsyncJobDeliveryHandler, AsyncJobDeliveryMessage } from \"./types.js\";\n\nexport interface SessionAsyncJobManagerHandle {\n\tmanager: AsyncJobManager;\n\towns: boolean;\n\tsessionId: symbol;\n}\ninterface AsyncDeliverySession {\n\tsendCustomMessage(message: AsyncJobDeliveryMessage, options?: SendMessageOptions): Promise<void>;\n}\n\nexport function createSessionAsyncDeliveryHandler(\n\tsession: AsyncDeliverySession,\n\tmanager?: AsyncJobManager,\n\tsessionId?: symbol,\n): AsyncJobDeliveryHandler {\n\treturn async (message: AsyncJobDeliveryMessage) => {\n\t\tconst isStale = () =>\n\t\t\tmanager?.disposed === true ||\n\t\t\tmanager?.isDeliverySuppressed(message.details.jobId) === true ||\n\t\t\t(sessionId !== undefined && manager?.isSessionDisposed(sessionId) === true);\n\t\tif (isStale()) return;\n\t\tawait session.sendCustomMessage(message, {\n\t\t\tdeliverAs: \"followUp\",\n\t\t\ttriggerTurn: true,\n\t\t\tstageAdmissionKey: `async-job:${message.details.jobId}`,\n\t\t});\n\t};\n}\n\nexport function createSessionAsyncJobManager(session: AsyncDeliverySession): SessionAsyncJobManagerHandle {\n\tconst existing = AsyncJobManager.instance();\n\tif (existing) return { manager: existing, owns: false, sessionId: existing.registerSession() };\n\tlet manager: AsyncJobManager;\n\tmanager = new AsyncJobManager({\n\t\tonJobComplete: (message) => createSessionAsyncDeliveryHandler(session, manager)(message),\n\t});\n\tAsyncJobManager.setInstance(manager);\n\treturn { manager, owns: true, sessionId: manager.registerSession() };\n}\n\nexport function disposeSessionAsyncJobManager(\n\tmanager: AsyncJobManager | undefined,\n\tsessionId: symbol | undefined,\n): void {\n\tif (!manager || !sessionId) return;\n\tmanager.releaseSession(sessionId);\n\tif (manager.disposed && AsyncJobManager.instance() === manager) AsyncJobManager.setInstance(undefined);\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAIN,kBAAkB,EAClB,MAAM,GACN,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqEpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB;IAEhB,2CAA2C;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;IAChD,CAAC;IAED,2DAA2D;IAC3D,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACvE,MAAM,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,QAAQ,CAAC,C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AAE,OAAO,SAAS,CAAC;YACrC,OAAO;gBACN,UAAU,EAAE,OAAgB;gBAC5B,YAAY,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aACpE,CAAC;QACH,CAAC;IACF,CAAC,CAAC,EAAE,CAAC;IAEL,8BAA8B;IAC9B,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,UAAU,KAAK,SAAS,EAAE,CAAC;QACpD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC1B,CAAC;IACD,IAAI,QAAQ,CAAC,UAAU,KAAK,OAAO,EAAE,CAAC;QACrC,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,YAAY,IAAI,sBAAsB,EAAE,CAAC;IACnE,CAAC;IAED,IAAI,OAAO,GAAG,QAAQ,CAAC,OAAO;SAC5B,MAAM,CAAC,CAAC,CAAC,EAAuC,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,MAAM,CAAC;SACrE,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;SAClB,IAAI,CAAC,IAAI,CAAC,CAAC;IAEb,+DAA+D;IAC/D,OAAO,GAAG,uBAAuB,GAAG,OAAO,CAAC;IAE5C,2CAA2C;IAC3C,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC/D,OAAO,IAAI,oBAAoB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;IAE1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS;QACT,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@earendil-works/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@earendil-works/pi-ai/compat\";\nimport { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.ts\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts, with legacy compaction entries kept inert.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\tcase \"context_compaction\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tconst filteredEntries = entries;\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of filteredEntries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"branch-summarization.js","sourceRoot":"","sources":["../../../src/core/compaction/branch-summarization.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAIN,kBAAkB,EAClB,MAAM,GACN,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,0BAA0B,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACN,gBAAgB,EAChB,aAAa,EACb,yBAAyB,EAEzB,oBAAoB,EACpB,2BAA2B,EAC3B,qBAAqB,GACrB,MAAM,YAAY,CAAC;AAqEpB,+EAA+E;AAC/E,mBAAmB;AACnB,+EAA+E;AAE/E;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,8BAA8B,CAC7C,OAA+B,EAC/B,SAAwB,EACxB,QAAgB;IAEhB,2CAA2C;IAC3C,IAAI,CAAC,SAAS,EAAE,CAAC;QAChB,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,gBAAgB,EAAE,IAAI,EAAE,CAAC;IA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E1D,OAAO;QACN,OAAO,EAAE,OAAO,IAAI,sBAAsB;QAC1C,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,SAAS;QACT,aAAa;KACb,CAAC;AACH,CAAC","sourcesContent":["/**\n * Branch summarization for tree navigation.\n *\n * When navigating to a different point in the session tree, this generates\n * a summary of the branch being left so context isn't lost.\n */\n\nimport type { AgentMessage, StreamFn, ThinkingLevel } from \"@earendil-works/pi-agent-core\";\nimport {\n\ttype ProviderHeaders,\n\ttype RetryCallbacks,\n\ttype RetryPolicy,\n\tretryAssistantCall,\n\tuuidv7,\n} from \"@earendil-works/pi-ai\";\nimport type { Api, Model, SimpleStreamOptions, Usage } from \"@earendil-works/pi-ai/compat\";\nimport { completeSimple } from \"@earendil-works/pi-ai/compat\";\nimport { convertToLlm, createBranchSummaryMessage, createCustomMessage } from \"../messages.ts\";\nimport type { ReadonlySessionManager, SessionEntry } from \"../session-manager.ts\";\nimport { estimateTokens } from \"./compaction.ts\";\nimport { resolvePlannerRequest } from \"./range-planner.js\";\nimport {\n\tcomputeFileLists,\n\tcreateFileOps,\n\textractFileOpsFromMessage,\n\ttype FileOperations,\n\tformatFileOperations,\n\tSUMMARIZATION_SYSTEM_PROMPT,\n\tserializeConversation,\n} from \"./utils.ts\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\tusage?: Usage;\n\taborted?: boolean;\n\terror?: string;\n}\n\n/** Details stored in BranchSummaryEntry.details for file tracking */\nexport interface BranchSummaryDetails {\n\treadFiles: string[];\n\tmodifiedFiles: string[];\n}\n\nexport type { FileOperations } from \"./utils.ts\";\n\nexport interface BranchPreparation {\n\t/** Messages extracted for summarization, in chronological order */\n\tmessages: AgentMessage[];\n\t/** File operations extracted from tool calls */\n\tfileOps: FileOperations;\n\t/** Total estimated tokens in messages */\n\ttotalTokens: number;\n}\n\nexport interface CollectEntriesResult {\n\t/** Entries to summarize, in chronological order */\n\tentries: SessionEntry[];\n\t/** Common ancestor between old and new position, if any */\n\tcommonAncestorId: string | null;\n}\n\nexport interface GenerateBranchSummaryOptions {\n\t/** Model to use for summarization */\n\tmodel: Model<Api>;\n\t/** API key for the model; omitted for header-only bearer authentication. */\n\tapiKey?: string;\n\t/** Request headers for the model */\n\theaders?: ProviderHeaders;\n\t/** Credential-specific request endpoint for the model */\n\tbaseUrl?: string;\n\t/** Abort signal for cancellation */\n\tsignal: AbortSignal;\n\t/** Optional custom instructions for summarization */\n\tcustomInstructions?: string;\n\t/** If true, customInstructions replaces the default prompt instead of being appended */\n\treplaceInstructions?: boolean;\n\t/** Tokens reserved for prompt + LLM response (default 16384) */\n\treserveTokens?: number;\n\t/**\n\t * Session reasoning level, inherited by the summarization request.\n\t * No output cap is sent, so thinking has no artificial budget to exhaust.\n\t */\n\tthinkingLevel?: ThinkingLevel;\n\t/** Optional session stream function. Used to preserve SDK request behavior without mutating agent state. */\n\tstreamFn?: StreamFn;\n\t/** Retry policy for transient summarization failures. */\n\tretry?: RetryPolicy;\n\t/** Retry lifecycle callbacks. */\n\tcallbacks?: RetryCallbacks;\n}\n\n// ============================================================================\n// Entry Collection\n// ============================================================================\n\n/**\n * Collect entries that should be summarized when navigating from one position to another.\n *\n * Walks from oldLeafId back to the common ancestor with targetId, collecting entries\n * along the way. Does NOT stop at legacy compaction entries, but those entries are\n * inert and are not fed into branch summarization prompts.\n *\n * @param session - Session manager (read-only access)\n * @param oldLeafId - Current position (where we're navigating from)\n * @param targetId - Target position (where we're navigating to)\n * @returns Entries to summarize and the common ancestor\n */\nexport function collectEntriesForBranchSummary(\n\tsession: ReadonlySessionManager,\n\toldLeafId: string | null,\n\ttargetId: string,\n): CollectEntriesResult {\n\t// If no old position, nothing to summarize\n\tif (!oldLeafId) {\n\t\treturn { entries: [], commonAncestorId: null };\n\t}\n\n\t// Find common ancestor (deepest node that's on both paths)\n\tconst oldPath = new Set(session.getBranch(oldLeafId).map((e) => e.id));\n\tconst targetPath = session.getBranch(targetId);\n\n\t// targetPath is root-first, so iterate backwards to find deepest common ancestor\n\tlet commonAncestorId: string | null = null;\n\tfor (let i = targetPath.length - 1; i >= 0; i--) {\n\t\tif (oldPath.has(targetPath[i].id)) {\n\t\t\tcommonAncestorId = targetPath[i].id;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t// Collect entries from old leaf back to common ancestor\n\tconst entries: SessionEntry[] = [];\n\tlet current: string | null = oldLeafId;\n\n\twhile (current && current !== commonAncestorId) {\n\t\tconst entry = session.getEntry(current);\n\t\tif (!entry) break;\n\t\tentries.push(entry);\n\t\tcurrent = entry.parentId;\n\t}\n\n\t// Reverse to get chronological order\n\tentries.reverse();\n\n\treturn { entries, commonAncestorId };\n}\n\n// ============================================================================\n// Entry to Message Conversion\n// ============================================================================\n\n/**\n * Extract AgentMessage from a session entry.\n * Similar to getMessageFromEntry in compaction.ts, with legacy compaction entries kept inert.\n */\nfunction getMessageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tswitch (entry.type) {\n\t\tcase \"message\":\n\t\t\t// Skip tool results - context is in assistant's tool call\n\t\t\tif (entry.message.role === \"toolResult\") return undefined;\n\t\t\treturn entry.message;\n\n\t\tcase \"custom_message\":\n\t\t\treturn createCustomMessage(\n\t\t\t\tentry.customType,\n\t\t\t\tentry.content,\n\t\t\t\tentry.display,\n\t\t\t\tentry.details,\n\t\t\t\tentry.timestamp,\n\t\t\t\tentry.excludeFromContext,\n\t\t\t);\n\n\t\tcase \"branch_summary\":\n\t\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\n\t\tcase \"compaction\":\n\t\t\treturn undefined;\n\n\t\t// These don't contribute to conversation content\n\t\tcase \"thinking_level_change\":\n\t\tcase \"model_change\":\n\t\tcase \"custom\":\n\t\tcase \"label\":\n\t\tcase \"session_info\":\n\t\tcase \"context_compaction\":\n\t\t\treturn undefined;\n\t}\n}\n\n/**\n * Prepare entries for summarization with token budget.\n *\n * Walks entries from NEWEST to OLDEST, adding messages until we hit the token budget.\n * This ensures we keep the most recent context when the branch is too long.\n *\n * Also collects file operations from:\n * - Tool calls in assistant messages\n * - Existing branch_summary entries' details (for cumulative tracking)\n *\n * @param entries - Entries in chronological order\n * @param tokenBudget - Maximum tokens to include (0 = no limit)\n */\nexport function prepareBranchEntries(entries: SessionEntry[], tokenBudget: number = 0): BranchPreparation {\n\tconst messages: AgentMessage[] = [];\n\tconst fileOps = createFileOps();\n\tconst filteredEntries = entries;\n\tlet totalTokens = 0;\n\n\t// First pass: collect file ops from ALL entries (even if they don't fit in token budget)\n\t// This ensures we capture cumulative file tracking from nested branch summaries\n\t// Only extract from pi-generated summaries (fromHook !== true), not extension-generated ones\n\tfor (const entry of filteredEntries) {\n\t\tif (entry.type === \"branch_summary\" && !entry.fromHook && entry.details) {\n\t\t\tconst details = entry.details as BranchSummaryDetails;\n\t\t\tif (Array.isArray(details.readFiles)) {\n\t\t\t\tfor (const f of details.readFiles) fileOps.read.add(f);\n\t\t\t}\n\t\t\tif (Array.isArray(details.modifiedFiles)) {\n\t\t\t\t// Modified files go into both edited and written for proper deduplication\n\t\t\t\tfor (const f of details.modifiedFiles) {\n\t\t\t\t\tfileOps.edited.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: walk from newest to oldest, adding messages until token budget\n\tfor (let i = filteredEntries.length - 1; i >= 0; i--) {\n\t\tconst entry = filteredEntries[i];\n\t\tconst message = getMessageFromEntry(entry);\n\t\tif (!message) continue;\n\n\t\t// Extract file ops from assistant messages (tool calls)\n\t\textractFileOpsFromMessage(message, fileOps);\n\n\t\tconst tokens = estimateTokens(message);\n\n\t\t// Check budget before adding\n\t\tif (tokenBudget > 0 && totalTokens + tokens > tokenBudget) {\n\t\t\t// If this is a branch summary entry, try to fit it anyway as it's important context\n\t\t\tif (entry.type === \"branch_summary\") {\n\t\t\t\tif (totalTokens < tokenBudget * 0.9) {\n\t\t\t\t\tmessages.unshift(message);\n\t\t\t\t\ttotalTokens += tokens;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Stop - we've hit the budget\n\t\t\tbreak;\n\t\t}\n\n\t\tmessages.unshift(message);\n\t\ttotalTokens += tokens;\n\t}\n\n\treturn { messages, fileOps, totalTokens };\n}\n\n// ============================================================================\n// Summary Generation\n// ============================================================================\n\nconst BRANCH_SUMMARY_PREAMBLE = `The user explored a different conversation branch before returning here.\nSummary of that exploration:\n\n`;\n\nconst BRANCH_SUMMARY_PROMPT = `Create a structured summary of this conversation branch for context when returning later.\n\nUse this EXACT format:\n\n## Goal\n[What was the user trying to accomplish in this branch?]\n\n## Constraints & Preferences\n- [Any constraints, preferences, or requirements mentioned]\n- [Or \"(none)\" if none were mentioned]\n\n## Progress\n### Done\n- [x] [Completed tasks/changes]\n\n### In Progress\n- [ ] [Work that was started but not finished]\n\n### Blocked\n- [Issues preventing progress, if any]\n\n## Key Decisions\n- **[Decision]**: [Brief rationale]\n\n## Next Steps\n1. [What should happen next to continue this work]\n\nKeep each section concise. Preserve exact file paths, function names, and error messages.`;\n\n/**\n * Generate a summary of abandoned branch entries.\n *\n * @param entries - Session entries to summarize (chronological order)\n * @param options - Generation options\n */\nexport async function generateBranchSummary(\n\tentries: SessionEntry[],\n\toptions: GenerateBranchSummaryOptions,\n): Promise<BranchSummaryResult> {\n\tconst {\n\t\tmodel,\n\t\tapiKey,\n\t\theaders,\n\t\tbaseUrl,\n\t\tsignal,\n\t\tcustomInstructions,\n\t\treplaceInstructions,\n\t\treserveTokens = 16384,\n\t\tthinkingLevel,\n\t\tstreamFn,\n\t\tretry,\n\t\tcallbacks,\n\t} = options;\n\n\t// Token budget = context window minus reserved space for prompt + response\n\tconst contextWindow = model.contextWindow || 128000;\n\tconst tokenBudget = contextWindow - reserveTokens;\n\n\tconst { messages, fileOps } = prepareBranchEntries(entries, tokenBudget);\n\n\tif (messages.length === 0) {\n\t\treturn { summary: \"No content to summarize\" };\n\t}\n\n\t// Transform to LLM-compatible messages, then serialize to text\n\t// Serialization prevents the model from treating it as a conversation to continue\n\tconst llmMessages = convertToLlm(messages);\n\tconst conversationText = serializeConversation(llmMessages);\n\n\t// Build prompt\n\tlet instructions: string;\n\tif (replaceInstructions && customInstructions) {\n\t\tinstructions = customInstructions;\n\t} else if (customInstructions) {\n\t\tinstructions = `${BRANCH_SUMMARY_PROMPT}\\n\\nAdditional focus: ${customInstructions}`;\n\t} else {\n\t\tinstructions = BRANCH_SUMMARY_PROMPT;\n\t}\n\tconst promptText = `<conversation>\\n${conversationText}\\n</conversation>\\n\\n${instructions}`;\n\n\tconst summarizationMessages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [{ type: \"text\" as const, text: promptText }],\n\t\t\ttimestamp: Date.now(),\n\t\t},\n\t];\n\n\t// Call LLM for summarization. Prefer the session stream function so SDK\n\t// request behavior stays consistent without mutating agent state.\n\tconst context = { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, messages: summarizationMessages };\n\tconst requestModel = baseUrl === undefined || baseUrl === model.baseUrl ? model : { ...model, baseUrl };\n\t// Same budget rule as the compaction planner: no output cap is sent, so\n\t// pi-ai's context clamp is the only bound and the inherited reasoning level\n\t// has no artificial budget to exhaust. `reserveTokens` keeps its input-side\n\t// meaning above, unchanged.\n\tconst budget = resolvePlannerRequest(requestModel, thinkingLevel);\n\tconst requestOptions: SimpleStreamOptions = {\n\t\tapiKey,\n\t\theaders,\n\t\tsignal,\n\t\tcacheRetention: \"none\",\n\t\tsessionId: uuidv7(),\n\t\t...(budget.reasoning && budget.reasoning !== \"off\" ? { reasoning: budget.reasoning } : {}),\n\t};\n\tconst response = await (async () => {\n\t\ttry {\n\t\t\treturn await retryAssistantCall(\n\t\t\t\tasync () =>\n\t\t\t\t\tstreamFn\n\t\t\t\t\t\t? (await streamFn(requestModel, context, requestOptions)).result()\n\t\t\t\t\t\t: completeSimple(requestModel, context, requestOptions),\n\t\t\t\tretry,\n\t\t\t\tsignal,\n\t\t\t\tcallbacks,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (signal.aborted) return undefined;\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\" as const,\n\t\t\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\t\t};\n\t\t}\n\t})();\n\n\t// Check if aborted or errored\n\tif (!response || response.stopReason === \"aborted\") {\n\t\treturn { aborted: true };\n\t}\n\tif (response.stopReason === \"error\") {\n\t\treturn { error: response.errorMessage || \"Summarization failed\" };\n\t}\n\n\tlet summary = response.content\n\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\n\t// Prepend preamble to provide context about the branch summary\n\tsummary = BRANCH_SUMMARY_PREAMBLE + summary;\n\n\t// Compute file lists and append to summary\n\tconst { readFiles, modifiedFiles } = computeFileLists(fileOps);\n\tsummary += formatFileOperations(readFiles, modifiedFiles);\n\n\treturn {\n\t\tsummary: summary || \"No summary generated\",\n\t\tusage: response.usage,\n\t\treadFiles,\n\t\tmodifiedFiles,\n\t};\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SessionEntry } from "../session-manager-types.
|
|
2
|
-
import { type CompactionSettings } from "./compaction.
|
|
1
|
+
import type { SessionEntry } from "../session-manager-types.ts";
|
|
2
|
+
import { type CompactionSettings } from "./compaction.ts";
|
|
3
3
|
import { type VerbatimCompactionParameters, type VerbatimCompactionPreparation } from "./compaction-types.js";
|
|
4
4
|
/** Return the independently estimated cost of the protected tail. */
|
|
5
5
|
export declare function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wBAAwB,GACxB,MAAM,gBAAg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SAC7E,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,MAAM,MAAM,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;IAChD,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,4BAA4B;QAAE,OAAO,SAAS,CAAC;IAEtG,MAAM,WAAW,GAAkC;QAClD,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM;QACjF,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.js\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.js\";\nimport { buildSessionContext } from \"../session-manager-history.js\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.js\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.js\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/** Return the independently estimated cost of the protected tail. */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\treturn (\n\t\tkeptTailTokensByPreparation.get(preparation) ??\n\t\tMath.max(0, preparation.tokensBefore - preparation.region.tokenEstimate)\n\t);\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compaction-boundary.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-boundary.ts"],"names":[],"mappings":"AACA,OAAO,EACN,YAAY,EACZ,0BAA0B,EAC1B,mBAAmB,EACnB,mBAAmB,EACnB,wB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MAAM,GAAG,CAAC,CAAC;SAC7E,IAAI,CAAC,IAAI,CAAC,CAAC;IACb,MAAM,MAAM,GAAG,oBAAoB,CAAC,UAAU,CAAC,CAAC;IAChD,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,MAAM,CAAC,KAAK,CAAC,MAAM,GAAG,4BAA4B;QAAE,OAAO,SAAS,CAAC;IAEtG,MAAM,WAAW,GAAkC;QAClD,gBAAgB,EAAE,YAAY,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,IAAI,IAAI;QACnD,MAAM;QACN,cAAc,EAAE,cAAc,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,oBAAoB,EAAE,YAAY,CAAC,MAAM;QACzC,YAAY,EAAE,qBAAqB,CAAC,mBAAmB,CAAC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,MAAM;QACjF,UAAU;QACV,QAAQ;KACR,CAAC;IACF,2BAA2B,CAAC,GAAG,CAC9B,WAAW,EACX,YAAY,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,CAAC,GAAG,GAAG,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CACzE,CAAC;IACF,OAAO,WAAW,CAAC;AACpB,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport {\n\tconvertToLlm,\n\tcreateBranchSummaryMessage,\n\tcreateCustomMessage,\n\tmessageIsLlmVisible,\n\tmessageStartsLlmUserTurn,\n} from \"../messages.ts\";\nimport { normalizeDerivedSessionEntries } from \"../session-entry-normalization.ts\";\nimport { buildSessionContext } from \"../session-manager-history.ts\";\nimport type { CompactionEntry, SessionEntry } from \"../session-manager-types.ts\";\nimport { type CompactionSettings, estimateContextTokens, estimateTokens } from \"./compaction.ts\";\nimport {\n\tCOMPACTION_AUTO_QUERY,\n\tnormalizeCompactionParameters,\n\tnormalizeCompactionQuery,\n} from \"./compaction-parameters.js\";\nimport {\n\tMIN_COMPACTABLE_REGION_LINES,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionParameters,\n\ttype VerbatimCompactionPreparation,\n} from \"./compaction-types.js\";\nimport { createNumberedRegion, serializeConversationForCompaction } from \"./transcript-serialization.js\";\n\ninterface VisibleEntry {\n\tentry: SessionEntry;\n\tindex: number;\n\tmessage: AgentMessage;\n}\n\nconst keptTailTokensByPreparation = new WeakMap<VerbatimCompactionPreparation, number>();\n\n/** Return the independently estimated cost of the protected tail. */\nexport function getKeptTailTokenEstimate(preparation: VerbatimCompactionPreparation): number {\n\treturn (\n\t\tkeptTailTokensByPreparation.get(preparation) ??\n\t\tMath.max(0, preparation.tokensBefore - preparation.region.tokenEstimate)\n\t);\n}\n\nfunction messageFromEntry(entry: SessionEntry): AgentMessage | undefined {\n\tif (entry.type === \"message\") return entry.message;\n\tif (entry.type === \"custom_message\") {\n\t\treturn createCustomMessage(\n\t\t\tentry.customType,\n\t\t\tentry.content,\n\t\t\tentry.display,\n\t\t\tentry.details,\n\t\t\tentry.timestamp,\n\t\t\tentry.excludeFromContext,\n\t\t);\n\t}\n\tif (entry.type === \"branch_summary\" && typeof entry.summary === \"string\") {\n\t\treturn createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp);\n\t}\n\treturn undefined;\n}\n\nfunction activeBoundary(entry: SessionEntry): entry is CompactionEntry<VerbatimCompactionDetails> {\n\tif (entry.type !== \"compaction\") return false;\n\tconst details = (entry as CompactionEntry<{ strategy?: string }>).details;\n\treturn details?.strategy === VERBATIM_COMPACTION_STRATEGY;\n}\n\nfunction visibleEntries(entries: SessionEntry[], start = 0): VisibleEntry[] {\n\tconst visible: VisibleEntry[] = [];\n\tfor (let index = start; index < entries.length; index++) {\n\t\tconst entry = entries[index];\n\t\tconst message = messageFromEntry(entry);\n\t\tif (message && messageIsLlmVisible(message)) visible.push({ entry, index, message });\n\t}\n\treturn visible;\n}\n\nfunction messageText(message: AgentMessage): string {\n\tconst converted = convertToLlm([message]);\n\tif (converted.length === 0) return \"\";\n\treturn converted\n\t\t.flatMap((item) =>\n\t\t\ttypeof item.content === \"string\"\n\t\t\t\t? [item.content]\n\t\t\t\t: item.content.filter((block) => block.type === \"text\").map((block) => block.text),\n\t\t)\n\t\t.join(\"\\n\");\n}\n\nexport function autoDetectCompactionQuery(entries: readonly SessionEntry[]): string {\n\tconst normalized = normalizeDerivedSessionEntries(entries);\n\tfor (let index = normalized.length - 1; index >= 0; index--) {\n\t\tconst message = messageFromEntry(normalized[index]);\n\t\tif (!message || !messageStartsLlmUserTurn(message)) continue;\n\t\tconst text = messageText(message).trim();\n\t\tif (text) return normalizeCompactionQuery(text, COMPACTION_AUTO_QUERY);\n\t}\n\treturn COMPACTION_AUTO_QUERY;\n}\n\nfunction latestActiveBoundary(\n\tentries: SessionEntry[],\n): { entry: CompactionEntry<VerbatimCompactionDetails>; index: number } | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (activeBoundary(entry)) return { entry, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Planner eligibility, kept separate from boundary preparation.\n *\n * `MIN_COMPACTABLE_REGION_LINES` exists to stop repeated pointless *planned*\n * compaction. A load-bearing caller has a different problem: one oversized tool\n * result can blow the context window while producing fewer than 20 compactable\n * lines, and refusing to prepare a boundary there makes the \"always completes\"\n * guarantee hollow — the fresh rung and its tail-drop rule become unreachable.\n */\nexport interface CompactionBoundaryControl {\n\t/**\n\t * Prepare a boundary even when the region is below the planner minimum.\n\t * Only `load_bearing` callers set this; the runner routes such a region\n\t * straight to the fresh rung without invoking a planner.\n\t */\n\tallowSmallRegion?: boolean;\n}\n\n/** Prepare the complete compactable transcript and its exact context-visible message tail. */\nexport function prepareCompactionBoundary(\n\tpathEntries: SessionEntry[],\n\tsettings: CompactionSettings,\n\toptions: Partial<VerbatimCompactionParameters> = {},\n\tcontrol: CompactionBoundaryControl = {},\n): VerbatimCompactionPreparation | undefined {\n\tconst entries = normalizeDerivedSessionEntries(pathEntries);\n\tconst previous = latestActiveBoundary(entries);\n\tlet regionStart = 0;\n\tif (previous) {\n\t\tconst keptIndex =\n\t\t\tprevious.entry.firstKeptEntryId === null\n\t\t\t\t? -1\n\t\t\t\t: entries.findIndex((entry) => entry.id === previous.entry.firstKeptEntryId);\n\t\tregionStart = keptIndex >= 0 ? keptIndex : previous.index + 1;\n\t}\n\n\tconst visible = visibleEntries(entries, regionStart);\n\tconst parameters = normalizeCompactionParameters({ ...settings, ...options }, autoDetectCompactionQuery(entries));\n\tconst tailStart = Math.max(0, visible.length - parameters.preserve_recent);\n\tconst regionMessages = visible.slice(0, tailStart);\n\tconst tailMessages = visible.slice(tailStart);\n\n\tconst serialized = serializeConversationForCompaction(convertToLlm(regionMessages.map((item) => item.message)));\n\tconst regionText = [previous?.entry.summary, serialized]\n\t\t.filter((text): text is string => typeof text === \"string\" && text.length > 0)\n\t\t.join(\"\\n\");\n\tconst region = createNumberedRegion(regionText);\n\tif (!control.allowSmallRegion && region.lines.length < MIN_COMPACTABLE_REGION_LINES) return undefined;\n\n\tconst preparation: VerbatimCompactionPreparation = {\n\t\tfirstKeptEntryId: tailMessages[0]?.entry.id ?? null,\n\t\tregion,\n\t\tregionEntryIds: regionMessages.map((item) => item.entry.id),\n\t\tkeptTailMessageCount: tailMessages.length,\n\t\ttokensBefore: estimateContextTokens(buildSessionContext(entries).messages).tokens,\n\t\tparameters,\n\t\tsettings,\n\t};\n\tkeptTailTokensByPreparation.set(\n\t\tpreparation,\n\t\ttailMessages.reduce((sum, item) => sum + estimateTokens(item.message), 0),\n\t);\n\treturn preparation;\n}\n"]}
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { type VerbatimCompactionParameters } from "./compaction-types.js";
|
|
2
2
|
export declare const COMPACTION_AUTO_QUERY = "the latest user request";
|
|
3
|
+
/**
|
|
4
|
+
* The query is the planner's relevance focus, so it is kept whole. Truncating it made prompt
|
|
5
|
+
* order the retention policy: for a long structured prompt only the leading section survived,
|
|
6
|
+
* and any constraint stated later could not influence what the planner kept.
|
|
7
|
+
*/
|
|
3
8
|
export declare function normalizeCompactionQuery(value: string | undefined, fallback: string): string;
|
|
4
9
|
export declare function normalizeCompactionParameters(input?: Partial<VerbatimCompactionParameters>, fallbackQuery?: string): VerbatimCompactionParameters;
|
|
5
10
|
//# sourceMappingURL=compaction-parameters.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-parameters.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,4BAA4B,EACjC,MAAM,uBAAuB,CAAC;AAE/B,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"compaction-parameters.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,4BAA4B,EACjC,MAAM,uBAAuB,CAAC;AAE/B,eAAO,MAAM,qBAAqB,4BAA4B,CAAC;AAc/D;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE5F;AAED,wBAAgB,6BAA6B,CAC5C,KAAK,GAAE,OAAO,CAAC,4BAA4B,CAAM,EACjD,aAAa,SAAwB,GACnC,4BAA4B,CAM9B"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { DEFAULT_COMPRESSION_RATIO, DEFAULT_PRESERVE_RECENT, } from "./compaction-types.js";
|
|
2
2
|
export const COMPACTION_AUTO_QUERY = "the latest user request";
|
|
3
|
-
const QUERY_MAX_CHARS = 1000;
|
|
4
3
|
function normalizeCompressionRatio(value) {
|
|
5
4
|
return typeof value === "number" && Number.isFinite(value) && value > 0 && value < 1
|
|
6
5
|
? value
|
|
@@ -11,11 +10,13 @@ function normalizePreserveRecent(value) {
|
|
|
11
10
|
? Math.max(0, Math.floor(value))
|
|
12
11
|
: DEFAULT_PRESERVE_RECENT;
|
|
13
12
|
}
|
|
13
|
+
/**
|
|
14
|
+
* The query is the planner's relevance focus, so it is kept whole. Truncating it made prompt
|
|
15
|
+
* order the retention policy: for a long structured prompt only the leading section survived,
|
|
16
|
+
* and any constraint stated later could not influence what the planner kept.
|
|
17
|
+
*/
|
|
14
18
|
export function normalizeCompactionQuery(value, fallback) {
|
|
15
|
-
|
|
16
|
-
if (query.length <= QUERY_MAX_CHARS)
|
|
17
|
-
return query;
|
|
18
|
-
return `${query.slice(0, QUERY_MAX_CHARS)}\n[... ${query.length - QUERY_MAX_CHARS} more characters omitted from compaction query]`;
|
|
19
|
+
return value?.trim() || fallback.trim() || COMPACTION_AUTO_QUERY;
|
|
19
20
|
}
|
|
20
21
|
export function normalizeCompactionParameters(input = {}, fallbackQuery = COMPACTION_AUTO_QUERY) {
|
|
21
22
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-parameters.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,yBAAyB,EACzB,uBAAuB,GAEvB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,CAAC,MAAM,qBAAqB,GAAG,yBAAyB,CAAC;
|
|
1
|
+
{"version":3,"file":"compaction-parameters.js","sourceRoot":"","sources":["../../../src/core/compaction/compaction-parameters.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,yBAAyB,EACzB,uBAAuB,GAEvB,MAAM,uBAAuB,CAAC;AAE/B,MAAM,CAAC,MAAM,qBAAqB,GAAG,yBAAyB,CAAC;AAE/D,SAAS,yBAAyB,CAAC,KAAyB;IAC3D,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC;QACnF,CAAC,CAAC,KAAK;QACP,CAAC,CAAC,yBAAyB,CAAC;AAC9B,CAAC;AAED,SAAS,uBAAuB,CAAC,KAAyB;IACzD,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC;QACzD,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAChC,CAAC,CAAC,uBAAuB,CAAC;AAC5B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,KAAyB,EAAE,QAAgB;IACnF,OAAO,KAAK,EAAE,IAAI,EAAE,IAAI,QAAQ,CAAC,IAAI,EAAE,IAAI,qBAAqB,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC5C,KAAK,GAA0C,EAAE,EACjD,aAAa,GAAG,qBAAqB;IAErC,OAAO;QACN,iBAAiB,EAAE,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,CAAC;QACrE,eAAe,EAAE,uBAAuB,CAAC,KAAK,CAAC,eAAe,CAAC;QAC/D,KAAK,EAAE,wBAAwB,CAAC,KAAK,CAAC,KAAK,EAAE,aAAa,CAAC;KAC3D,CAAC;AACH,CAAC","sourcesContent":["import {\n\tDEFAULT_COMPRESSION_RATIO,\n\tDEFAULT_PRESERVE_RECENT,\n\ttype VerbatimCompactionParameters,\n} from \"./compaction-types.js\";\n\nexport const COMPACTION_AUTO_QUERY = \"the latest user request\";\n\nfunction normalizeCompressionRatio(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 && value < 1\n\t\t? value\n\t\t: DEFAULT_COMPRESSION_RATIO;\n}\n\nfunction normalizePreserveRecent(value: number | undefined): number {\n\treturn typeof value === \"number\" && Number.isFinite(value)\n\t\t? Math.max(0, Math.floor(value))\n\t\t: DEFAULT_PRESERVE_RECENT;\n}\n\n/**\n * The query is the planner's relevance focus, so it is kept whole. Truncating it made prompt\n * order the retention policy: for a long structured prompt only the leading section survived,\n * and any constraint stated later could not influence what the planner kept.\n */\nexport function normalizeCompactionQuery(value: string | undefined, fallback: string): string {\n\treturn value?.trim() || fallback.trim() || COMPACTION_AUTO_QUERY;\n}\n\nexport function normalizeCompactionParameters(\n\tinput: Partial<VerbatimCompactionParameters> = {},\n\tfallbackQuery = COMPACTION_AUTO_QUERY,\n): VerbatimCompactionParameters {\n\treturn {\n\t\tcompression_ratio: normalizeCompressionRatio(input.compression_ratio),\n\t\tpreserve_recent: normalizePreserveRecent(input.preserve_recent),\n\t\tquery: normalizeCompactionQuery(input.query, fallbackQuery),\n\t};\n}\n"]}
|
|
@@ -31,6 +31,10 @@ export type CompactionRungResult = CompactedTranscript & {
|
|
|
31
31
|
/**
|
|
32
32
|
* Calculate the single global line threshold from the prepared setting.
|
|
33
33
|
*
|
|
34
|
+
* Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5
|
|
35
|
+
* ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the
|
|
36
|
+
* compression ratio a real bound on output size, so protection can never enlarge the result.
|
|
37
|
+
*
|
|
34
38
|
* This is the untrimmed target. Overflow trimming does NOT reuse it:
|
|
35
39
|
* `planWithTrimming` recomputes the threshold against each trimmed view, so the
|
|
36
40
|
* planner is always asked to keep a proportion of the lines it actually
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compaction-runner.d.ts","sourceRoot":"","sources":["../../../src/core/compaction/compaction-runner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,8BAA8B,CAAC;AAE/D,OAAO,KAAK,EAEX,mBAAmB,EAC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O,EAAE,oBAAoB,GAC3B,OAAO,CAAC,oBAAoB,CAAC,CAmE/B"}
|
|
@@ -8,6 +8,10 @@ import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-tr
|
|
|
8
8
|
/**
|
|
9
9
|
* Calculate the single global line threshold from the prepared setting.
|
|
10
10
|
*
|
|
11
|
+
* Protected lines count *against* this target rather than raising it: keeping 40% under a 0.5
|
|
12
|
+
* ratio leaves the remaining 60% to compress harder to hit the same total. That keeps the
|
|
13
|
+
* compression ratio a real bound on output size, so protection can never enlarge the result.
|
|
14
|
+
*
|
|
11
15
|
* This is the untrimmed target. Overflow trimming does NOT reuse it:
|
|
12
16
|
* `planWithTrimming` recomputes the threshold against each trimmed view, so the
|
|
13
17
|
* planner is always asked to keep a proportion of the lines it actually
|
|
@@ -18,7 +22,7 @@ import { nextTrimOffset, rebaseTrimmedRanges, trimRegionHead } from "./region-tr
|
|
|
18
22
|
*/
|
|
19
23
|
export function targetKeepLines(preparation) {
|
|
20
24
|
const region = preparation.region;
|
|
21
|
-
return Math.
|
|
25
|
+
return Math.round(region.lines.length * preparation.parameters.compression_ratio);
|
|
22
26
|
}
|
|
23
27
|
function hardInputLimitFor(model) {
|
|
24
28
|
return model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;
|