@bastani/atomic 0.9.20-alpha.5 → 0.9.20-alpha.6
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 +41 -0
- package/README.md +37 -0
- package/dist/builtin/intercom/CHANGELOG.md +10 -0
- package/dist/builtin/intercom/broker/broker.ts +110 -39
- package/dist/builtin/intercom/broker/client.ts +8 -1
- package/dist/builtin/intercom/index.bundle.mjs +61 -2
- package/dist/builtin/intercom/live-route-refusal.ts +69 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/intercom/recoverable-disconnect.ts +16 -4
- package/dist/builtin/intercom/skills/intercom/SKILL.md +11 -11
- package/dist/builtin/intercom/types.ts +3 -1
- package/dist/builtin/mcp/package.json +2 -2
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +3 -3
- package/dist/builtin/subagents/skills/cua-driver/BROWSER.md +494 -0
- package/dist/builtin/subagents/skills/cua-driver/EMBEDDING.md +578 -0
- package/dist/builtin/subagents/skills/cua-driver/LINUX.md +364 -0
- package/dist/builtin/subagents/skills/cua-driver/MACOS.md +509 -0
- package/dist/builtin/subagents/skills/cua-driver/README.md +113 -0
- package/dist/builtin/subagents/skills/cua-driver/RECORDING.md +162 -0
- package/dist/builtin/subagents/skills/cua-driver/SKILL.md +1105 -0
- package/dist/builtin/subagents/skills/cua-driver/WINDOWS.md +866 -0
- package/dist/builtin/web-access/package.json +2 -2
- package/dist/builtin/workflows/CHANGELOG.md +13 -0
- package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
- package/dist/builtin/workflows/builtin/{chunk-7f381xnq.js → chunk-2hzrv5y8.js} +140 -21
- package/dist/builtin/workflows/builtin/{chunk-e83tc6nr.js → chunk-3tx8ry44.js} +3 -2
- package/dist/builtin/workflows/builtin/{chunk-00ywx588.js → chunk-5724b0cf.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-ne6vh5ct.js → chunk-7n51c5gh.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-x2nftpgj.js → chunk-9z3ztr2a.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-zj5162bh.js → chunk-deq63d9p.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-7h7s5xdj.js → chunk-dxjxtgmp.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-tvcydq13.js → chunk-ffdrv23t.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-pfm1kgqz.js → chunk-hmt5w62g.js} +12 -4
- package/dist/builtin/workflows/builtin/{chunk-tdqvdrg1.js → chunk-jngsbbpm.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-55p5dxjk.js → chunk-njmf5ze7.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-evfb0312.js → chunk-vn0wb31x.js} +1 -1
- package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
- package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +12 -12
- package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
- package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/steering-context.js +1 -1
- package/dist/builtin/workflows/builtin/tournament.js +3 -3
- package/dist/builtin/workflows/package.json +2 -2
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +199 -36
- package/dist/builtin/workflows/src/index.js +1418 -1271
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +15 -4
- package/dist/cli/args.js.map +1 -1
- package/dist/cli/file-processor.d.ts +1 -1
- package/dist/cli/file-processor.d.ts.map +1 -1
- package/dist/cli/file-processor.js.map +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +40 -12
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-bash.d.ts.map +1 -1
- package/dist/core/agent-session-bash.js +9 -8
- package/dist/core/agent-session-bash.js.map +1 -1
- package/dist/core/agent-session-boundaries.d.ts +68 -0
- package/dist/core/agent-session-boundaries.d.ts.map +1 -0
- package/dist/core/agent-session-boundaries.js +334 -0
- package/dist/core/agent-session-boundaries.js.map +1 -0
- package/dist/core/agent-session-compaction.js +1 -1
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +27 -13
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-export.d.ts.map +1 -1
- package/dist/core/agent-session-export.js +16 -20
- package/dist/core/agent-session-export.js.map +1 -1
- package/dist/core/agent-session-message-queue.d.ts.map +1 -1
- package/dist/core/agent-session-message-queue.js +3 -2
- package/dist/core/agent-session-message-queue.js.map +1 -1
- package/dist/core/agent-session-methods.d.ts +30 -4
- package/dist/core/agent-session-methods.d.ts.map +1 -1
- package/dist/core/agent-session-methods.js.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
- package/dist/core/agent-session-persistent-custom-messages.js +2 -1
- package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
- package/dist/core/agent-session-prompt.d.ts.map +1 -1
- package/dist/core/agent-session-prompt.js +93 -25
- package/dist/core/agent-session-prompt.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +4 -9
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-runtime.js +1 -1
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session-tool-hooks.d.ts.map +1 -1
- package/dist/core/agent-session-tool-hooks.js +15 -5
- package/dist/core/agent-session-tool-hooks.js.map +1 -1
- package/dist/core/agent-session-tree.d.ts.map +1 -1
- package/dist/core/agent-session-tree.js +2 -3
- package/dist/core/agent-session-tree.js.map +1 -1
- package/dist/core/agent-session-types.d.ts +6 -0
- package/dist/core/agent-session-types.d.ts.map +1 -1
- package/dist/core/agent-session-types.js.map +1 -1
- package/dist/core/agent-session.d.ts +15 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +17 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +1 -0
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
- package/dist/core/compaction/compaction-boundary.js +11 -6
- package/dist/core/compaction/compaction-boundary.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +3 -1
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +37 -0
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/crash-log.d.ts +6 -0
- package/dist/core/crash-log.d.ts.map +1 -0
- package/dist/core/crash-log.js +69 -0
- package/dist/core/crash-log.js.map +1 -0
- package/dist/core/execution-model-router.d.ts +1 -0
- package/dist/core/execution-model-router.d.ts.map +1 -1
- package/dist/core/execution-model-router.js +15 -12
- package/dist/core/execution-model-router.js.map +1 -1
- package/dist/core/export-html/template-js/tree-filter-render.js +6 -1
- package/dist/core/export-html/template.js +6 -1
- package/dist/core/extensions/agent-events.d.ts +69 -3
- package/dist/core/extensions/agent-events.d.ts.map +1 -1
- package/dist/core/extensions/agent-events.js.map +1 -1
- package/dist/core/extensions/api-types.d.ts +5 -3
- package/dist/core/extensions/api-types.d.ts.map +1 -1
- package/dist/core/extensions/api-types.js.map +1 -1
- package/dist/core/extensions/event-results.d.ts +3 -0
- package/dist/core/extensions/event-results.d.ts.map +1 -1
- package/dist/core/extensions/event-results.js.map +1 -1
- package/dist/core/extensions/event-types.d.ts +2 -2
- package/dist/core/extensions/event-types.d.ts.map +1 -1
- package/dist/core/extensions/event-types.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/provider-types.d.ts +2 -0
- package/dist/core/extensions/provider-types.d.ts.map +1 -1
- package/dist/core/extensions/provider-types.js.map +1 -1
- package/dist/core/extensions/runner-events.d.ts +16 -2
- package/dist/core/extensions/runner-events.d.ts.map +1 -1
- package/dist/core/extensions/runner-events.js +98 -5
- package/dist/core/extensions/runner-events.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +3 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +4 -1
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/index.d.ts +1 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js.map +1 -1
- package/dist/core/messages.d.ts +10 -0
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +57 -0
- package/dist/core/messages.js.map +1 -1
- package/dist/core/model-config.d.ts +52 -0
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +16 -0
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-resolver-defaults.d.ts.map +1 -1
- package/dist/core/model-resolver-defaults.js +2 -1
- package/dist/core/model-resolver-defaults.js.map +1 -1
- package/dist/core/prompt-templates-async.d.ts +2 -2
- package/dist/core/prompt-templates-async.d.ts.map +1 -1
- package/dist/core/prompt-templates-async.js +57 -29
- package/dist/core/prompt-templates-async.js.map +1 -1
- package/dist/core/prompt-templates.d.ts +6 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +61 -35
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/provider-composer-internal.d.ts +1 -0
- package/dist/core/provider-composer-internal.d.ts.map +1 -1
- package/dist/core/provider-composer-internal.js +19 -0
- package/dist/core/provider-composer-internal.js.map +1 -1
- package/dist/core/resource-loader-assets.d.ts.map +1 -1
- package/dist/core/resource-loader-assets.js +6 -6
- package/dist/core/resource-loader-assets.js.map +1 -1
- package/dist/core/sdk.js +3 -2
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-core.d.ts +10 -3
- package/dist/core/session-manager-core.d.ts.map +1 -1
- package/dist/core/session-manager-core.js +65 -7
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-entries.d.ts +4 -1
- package/dist/core/session-manager-entries.d.ts.map +1 -1
- package/dist/core/session-manager-entries.js +8 -0
- package/dist/core/session-manager-entries.js.map +1 -1
- package/dist/core/session-manager-history.d.ts +16 -1
- package/dist/core/session-manager-history.d.ts.map +1 -1
- package/dist/core/session-manager-history.js +105 -42
- package/dist/core/session-manager-history.js.map +1 -1
- package/dist/core/session-manager-types.d.ts +30 -3
- package/dist/core/session-manager-types.d.ts.map +1 -1
- package/dist/core/session-manager-types.js.map +1 -1
- package/dist/core/session-manager.d.ts +2 -2
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +1 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/structured-output/index.d.ts +0 -1
- package/dist/core/structured-output/index.d.ts.map +1 -1
- package/dist/core/structured-output/index.js +3 -15
- package/dist/core/structured-output/index.js.map +1 -1
- package/dist/core/structured-output/jev-client.d.ts +4 -8
- package/dist/core/structured-output/jev-client.d.ts.map +1 -1
- package/dist/core/structured-output/jev-client.js +36 -32
- package/dist/core/structured-output/jev-client.js.map +1 -1
- package/dist/core/structured-output/jev.d.ts.map +1 -1
- package/dist/core/structured-output/jev.js +4 -12
- package/dist/core/structured-output/jev.js.map +1 -1
- package/dist/core/structured-output/types.d.ts +0 -2
- package/dist/core/structured-output/types.d.ts.map +1 -1
- package/dist/core/structured-output/types.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/read.d.ts +4 -0
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +5 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/index-extensions.d.ts +1 -1
- package/dist/index-extensions.d.ts.map +1 -1
- package/dist/index-extensions.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/main-app-mode.d.ts +1 -1
- package/dist/main-app-mode.d.ts.map +1 -1
- package/dist/main-app-mode.js +3 -2
- package/dist/main-app-mode.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.js +6 -0
- package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-model.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-model.js +1 -0
- package/dist/modes/interactive/components/tree-selector-model.js.map +1 -1
- package/dist/modes/interactive/interactive-agent-events.js +17 -1
- package/dist/modes/interactive/interactive-agent-events.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode-helpers.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-helpers.js +16 -0
- package/dist/modes/interactive/interactive-mode-helpers.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode-surface.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-surface.js.map +1 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js +13 -1
- package/dist/modes/interactive/interactive-process-lifecycle.js.map +1 -1
- package/dist/modes/interactive/interactive-session-runtime.js +5 -1
- package/dist/modes/interactive/interactive-session-runtime.js.map +1 -1
- package/dist/utils/mime.js +1 -1
- package/dist/utils/mime.js.map +1 -1
- package/dist/utils/tool-result-images.d.ts +3 -1
- package/dist/utils/tool-result-images.d.ts.map +1 -1
- package/dist/utils/tool-result-images.js +4 -1
- package/dist/utils/tool-result-images.js.map +1 -1
- package/docs/compaction.md +5 -1
- package/docs/computer-use.md +105 -56
- package/docs/extensions/events.md +75 -7
- package/docs/extensions.md +6 -2
- package/docs/getting-started/first-session.md +1 -0
- package/docs/intercom/operations.md +13 -1
- package/docs/intercom.md +1 -1
- package/docs/models/evals.md +68 -82
- package/docs/models/reference.md +30 -2
- package/docs/packages.md +2 -0
- package/docs/prompt-templates.md +1 -0
- package/docs/providers.md +8 -2
- package/docs/sdk/reference.md +1 -2
- package/docs/sdk/structured-decisions.md +10 -9
- package/docs/sdk.md +13 -2
- package/docs/session-format.md +17 -2
- package/docs/settings.md +1 -1
- package/docs/skills.md +3 -1
- package/docs/subagents/reference.md +4 -4
- package/docs/subagents.md +1 -1
- package/docs/workflows/api-reference.md +2 -0
- package/docs/workflows/authoring.md +191 -0
- package/docs/workflows/operations.md +9 -3
- package/docs/workflows/verification.md +21 -8
- package/npm-shrinkwrap.json +69 -69
- package/package.json +8 -8
|
@@ -69,13 +69,16 @@ export function recordBashResult(command, result, options) {
|
|
|
69
69
|
// Queue for later - will be flushed on agent_end
|
|
70
70
|
this._pendingBashMessages.push(bashMessage);
|
|
71
71
|
}
|
|
72
|
+
else if (options?.persist !== false) {
|
|
73
|
+
// Persist first, then refresh the finalized context from the canonical projection.
|
|
74
|
+
this.sessionManager.appendMessage(bashMessage);
|
|
75
|
+
this._refreshFinalizedContext();
|
|
76
|
+
}
|
|
72
77
|
else {
|
|
73
|
-
// Add to agent state immediately
|
|
74
|
-
this.agent.state.messages.push(bashMessage);
|
|
75
78
|
// Avoid writing a source-owned result into a shared manager that an
|
|
76
|
-
// in-memory fork changed while this execution was active.
|
|
77
|
-
|
|
78
|
-
|
|
79
|
+
// in-memory fork changed while this execution was active. The result stays
|
|
80
|
+
// visible to this run only, so it must be added to agent state directly.
|
|
81
|
+
this.agent.state.messages.push(bashMessage);
|
|
79
82
|
}
|
|
80
83
|
}
|
|
81
84
|
/** Cancel one correlated bash request, or all active requests for legacy callers. */
|
|
@@ -97,12 +100,10 @@ export function _flushPendingBashMessages() {
|
|
|
97
100
|
if (this._pendingBashMessages.length === 0)
|
|
98
101
|
return;
|
|
99
102
|
for (const bashMessage of this._pendingBashMessages) {
|
|
100
|
-
// Add to agent state
|
|
101
|
-
this.agent.state.messages.push(bashMessage);
|
|
102
|
-
// Save to session
|
|
103
103
|
this.sessionManager.appendMessage(bashMessage);
|
|
104
104
|
}
|
|
105
105
|
this._pendingBashMessages = [];
|
|
106
|
+
this._refreshFinalizedContext();
|
|
106
107
|
}
|
|
107
108
|
// =========================================================================
|
|
108
109
|
// Session Management
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-bash.js","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EAAE,yBAAyB,EAAE,MAAM,oBAAoB,CAAC;AAE/D,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AACzF,OAAO,EAA+C,yBAAyB,EAAE,MAAM,iBAAiB,CAAC;AACzG,OAAO,EAAE,2BAA2B,EAAE,8BAA8B,EAAE,MAAM,qCAAqC,CAAC;AAClH,OAAO,EAAE,+BAA+B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAExE,MAAM,UAAU,WAAW,CAAqB,GAAG,IAA6C;IAC/F,IAAI,IAAI,CAAC,SAAS,IAAI,wBAAwB,CAAC,GAAG,CAAC,IAAI,CAAC;QACvD,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,mBAAmB,CAAC,EAAE,EAAE,IAAI,EAAE,eAAe,EAAE,CAAC,CAAC,CAAC;IACjG,OAAO,gBAAgB,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,oBAAoB,CAAC,IAAI,C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CAAC,cAAc,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;IAChD,CAAC;IAED,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;AAChC,CAAC;AAED,4EAA4E;AAC5E,qBAAqB;AACrB,4EAA4E;AAE5E;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,WAAW;IACX,gBAAgB;IAChB,SAAS;IACT,yBAAyB;CACzB,CAAC","sourcesContent":["import { getShellEnv } from \"../utils/shell.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport { executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { BashExecutionMessage } from \"./messages.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { type BashOperations, type BashOutputChannel, createLocalBashOperations } from \"./tools/bash.js\";\nimport { applyBashSessionEnvironment, snapshotBashSessionEnvironment } from \"./tools/bash-session-environment.ts\";\nimport { createLocalPowerShellOperations } from \"./tools/powershell.ts\";\nimport { resolveSessionTempDirPath } from \"./tools/session-temp-dir.ts\";\n\nexport function executeBash(this: AgentSession, ...args: Parameters<typeof executeBashOperation>): Promise<BashResult> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\treturn Promise.reject(Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" }));\n\treturn trackSessionWork(this, () => executeBashOperation.call(this, ...args));\n}\n\nasync function executeBashOperation(\n\tthis: AgentSession,\n\tcommand: string,\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void,\n\toptions?: {\n\t\texcludeFromContext?: boolean;\n\t\tid?: string;\n\t\toperations?: BashOperations;\n\t\tpty?: boolean;\n\t\temitEvent?: boolean;\n\t\trecordResult?: boolean;\n\t},\n): Promise<BashResult> {\n\tconst requestKey = options?.id ?? Symbol(\"bash-request\");\n\tconst abortController = new AbortController();\n\tconst controllers = this._bashAbortControllers.get(requestKey) ?? new Set<AbortController>();\n\tcontrollers.add(abortController);\n\tthis._bashAbortControllers.set(requestKey, controllers);\n\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\tconst prefix = this.settingsManager.getShellCommandPrefix();\n\tconst shellPath = this.settingsManager.getShellPath();\n\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\tconst env = { ...getShellEnv() };\n\tapplyBashSessionEnvironment(env, snapshotBashSessionEnvironment(this, true));\n\n\ttry {\n\t\tconst result = await executeBashWithOperations(\n\t\t\tresolvedCommand,\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\toptions?.operations ??\n\t\t\t\t(process.platform === \"win32\"\n\t\t\t\t\t? createLocalPowerShellOperations()\n\t\t\t\t\t: createLocalBashOperations({ shellPath })),\n\t\t\t{\n\t\t\t\tonChunk: (delta, channel) => {\n\t\t\t\t\tonChunk?.(delta, channel);\n\t\t\t\t\tif (options?.emitEvent !== false) {\n\t\t\t\t\t\tthis._emit({ type: \"bash_execution_update\", id: options?.id, channel, delta });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenv,\n\t\t\t\tpty: options?.pty,\n\t\t\t\tsessionTempDir: resolveSessionTempDirPath(this.sessionManager.getSessionId()),\n\t\t\t},\n\t\t);\n\n\t\tif (options?.recordResult !== false) this.recordBashResult(command, result, options);\n\t\treturn result;\n\t} finally {\n\t\tcontrollers.delete(abortController);\n\t\tif (controllers.size === 0) this._bashAbortControllers.delete(requestKey);\n\t}\n}\n\n/**\n * Record a bash execution result in session history.\n * Used by executeBash and by extensions that handle bash execution themselves.\n */\n\nexport function recordBashResult(\n\tthis: AgentSession,\n\tcommand: string,\n\tresult: BashResult,\n\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n): void {\n\tconst bashMessage: BashExecutionMessage = {\n\t\trole: \"bashExecution\",\n\t\tcommand,\n\t\toutput: result.output,\n\t\texitCode: result.exitCode,\n\t\tcancelled: result.cancelled,\n\t\ttruncated: result.truncated,\n\t\tfullOutputPath: result.fullOutputPath,\n\t\ttimestamp: Date.now(),\n\t\texcludeFromContext: options?.excludeFromContext,\n\t};\n\n\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\tif (this.isStreaming && options?.defer !== false) {\n\t\t// Queue for later - will be flushed on agent_end\n\t\tthis._pendingBashMessages.push(bashMessage);\n\t} else {\n\t\t// Add to agent state immediately\n\t\tthis.agent.state.messages.push(bashMessage);\n\n\t\t// Avoid writing a source-owned result into a shared manager that an\n\t\t// in-memory fork changed while this execution was active.\n\t\tif (options?.persist !== false) this.sessionManager.appendMessage(bashMessage);\n\t}\n}\n\n/** Cancel one correlated bash request, or all active requests for legacy callers. */\nexport function abortBash(this: AgentSession, id?: string): void {\n\tif (id !== undefined) {\n\t\tfor (const controller of [...(this._bashAbortControllers.get(id) ?? [])]) controller.abort();\n\t\treturn;\n\t}\n\t// Snapshot first: aborting settles owners, and a listener that removes its own\n\t// entry must not shorten the cancellation sweep.\n\tfor (const controllers of [...this._bashAbortControllers.values()]) {\n\t\tfor (const controller of [...controllers]) controller.abort();\n\t}\n}\n\n/** Whether a bash command is currently running */\n\nexport function _flushPendingBashMessages(this: AgentSession): void {\n\tif (this._pendingBashMessages.length === 0) return;\n\n\tfor (const bashMessage of this._pendingBashMessages) {\n\t\t// Add to agent state\n\t\tthis.agent.state.messages.push(bashMessage);\n\n\t\t// Save to session\n\t\tthis.sessionManager.appendMessage(bashMessage);\n\t}\n\n\tthis._pendingBashMessages = [];\n}\n\n// =========================================================================\n// Session Management\n// =========================================================================\n\n/**\n * Set a display name for the current session.\n */\n\nexport const agentSessionBashMethods = {\n\texecuteBash,\n\trecordBashResult,\n\tabortBash,\n\t_flushPendingBashMessages,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-bash.js","sourceRoot":"","sources":["../../src/core/agent-session-bash.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,mBA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AAS,CAAqB,EAAW;IACxD,IAAI,EAAE,KAAK,SAAS,EAAE,CAAC;QACtB,KAAK,MAAM,UAAU,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;YAAE,UAAU,CAAC,KAAK,EAAE,CAAC;QAC7F,OAAO;IACR,CAAC;IACD,+EAA+E;IAC/E,iDAAiD;IACjD,KAAK,MAAM,WAAW,IAAI,CAAC,GAAG,IAAI,CAAC,qBAAqB,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC;QACpE,KAAK,MAAM,UAAU,IAAI,CAAC,GAAG,WAAW,CAAC;YAAE,UAAU,CAAC,KAAK,EAAE,CAAC;IAC/D,CAAC;AACF,CAAC;AAED,kDAAkD;AAElD,MAAM,UAAU,yBAAyB;IACxC,IAAI,IAAI,CAAC,oBAAoB,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAEnD,KAAK,MAAM,WAAW,IAAI,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACrD,IAAI,CAAC,cAAc,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,CAAC,oBAAoB,GAAG,EAAE,CAAC;IAC/B,IAAI,CAAC,wBAAwB,EAAE,CAAC;AACjC,CAAC;AAED,4EAA4E;AAC5E,qBAAqB;AACrB,4EAA4E;AAE5E;;GAEG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACtC,WAAW;IACX,gBAAgB;IAChB,SAAS;IACT,yBAAyB;CACzB,CAAC","sourcesContent":["import { getShellEnv } from \"../utils/shell.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport type { BashResult } from \"./bash-executor.ts\";\nimport { executeBashWithOperations } from \"./bash-executor.ts\";\nimport type { BashExecutionMessage } from \"./messages.ts\";\nimport { sessionGenerationClosing, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport { type BashOperations, type BashOutputChannel, createLocalBashOperations } from \"./tools/bash.js\";\nimport { applyBashSessionEnvironment, snapshotBashSessionEnvironment } from \"./tools/bash-session-environment.ts\";\nimport { createLocalPowerShellOperations } from \"./tools/powershell.ts\";\nimport { resolveSessionTempDirPath } from \"./tools/session-temp-dir.ts\";\n\nexport function executeBash(this: AgentSession, ...args: Parameters<typeof executeBashOperation>): Promise<BashResult> {\n\tif (this._disposed || sessionGenerationClosing.has(this))\n\t\treturn Promise.reject(Object.assign(new Error(\"Session is closed\"), { code: \"SessionClosed\" }));\n\treturn trackSessionWork(this, () => executeBashOperation.call(this, ...args));\n}\n\nasync function executeBashOperation(\n\tthis: AgentSession,\n\tcommand: string,\n\tonChunk?: (chunk: string, channel: BashOutputChannel) => void,\n\toptions?: {\n\t\texcludeFromContext?: boolean;\n\t\tid?: string;\n\t\toperations?: BashOperations;\n\t\tpty?: boolean;\n\t\temitEvent?: boolean;\n\t\trecordResult?: boolean;\n\t},\n): Promise<BashResult> {\n\tconst requestKey = options?.id ?? Symbol(\"bash-request\");\n\tconst abortController = new AbortController();\n\tconst controllers = this._bashAbortControllers.get(requestKey) ?? new Set<AbortController>();\n\tcontrollers.add(abortController);\n\tthis._bashAbortControllers.set(requestKey, controllers);\n\t// Apply command prefix if configured (e.g., \"shopt -s expand_aliases\" for alias support)\n\tconst prefix = this.settingsManager.getShellCommandPrefix();\n\tconst shellPath = this.settingsManager.getShellPath();\n\tconst resolvedCommand = prefix ? `${prefix}\\n${command}` : command;\n\tconst env = { ...getShellEnv() };\n\tapplyBashSessionEnvironment(env, snapshotBashSessionEnvironment(this, true));\n\n\ttry {\n\t\tconst result = await executeBashWithOperations(\n\t\t\tresolvedCommand,\n\t\t\tthis.sessionManager.getCwd(),\n\t\t\toptions?.operations ??\n\t\t\t\t(process.platform === \"win32\"\n\t\t\t\t\t? createLocalPowerShellOperations()\n\t\t\t\t\t: createLocalBashOperations({ shellPath })),\n\t\t\t{\n\t\t\t\tonChunk: (delta, channel) => {\n\t\t\t\t\tonChunk?.(delta, channel);\n\t\t\t\t\tif (options?.emitEvent !== false) {\n\t\t\t\t\t\tthis._emit({ type: \"bash_execution_update\", id: options?.id, channel, delta });\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tsignal: abortController.signal,\n\t\t\t\tenv,\n\t\t\t\tpty: options?.pty,\n\t\t\t\tsessionTempDir: resolveSessionTempDirPath(this.sessionManager.getSessionId()),\n\t\t\t},\n\t\t);\n\n\t\tif (options?.recordResult !== false) this.recordBashResult(command, result, options);\n\t\treturn result;\n\t} finally {\n\t\tcontrollers.delete(abortController);\n\t\tif (controllers.size === 0) this._bashAbortControllers.delete(requestKey);\n\t}\n}\n\n/**\n * Record a bash execution result in session history.\n * Used by executeBash and by extensions that handle bash execution themselves.\n */\n\nexport function recordBashResult(\n\tthis: AgentSession,\n\tcommand: string,\n\tresult: BashResult,\n\toptions?: { excludeFromContext?: boolean; persist?: boolean; defer?: boolean },\n): void {\n\tconst bashMessage: BashExecutionMessage = {\n\t\trole: \"bashExecution\",\n\t\tcommand,\n\t\toutput: result.output,\n\t\texitCode: result.exitCode,\n\t\tcancelled: result.cancelled,\n\t\ttruncated: result.truncated,\n\t\tfullOutputPath: result.fullOutputPath,\n\t\ttimestamp: Date.now(),\n\t\texcludeFromContext: options?.excludeFromContext,\n\t};\n\n\t// If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering\n\tif (this.isStreaming && options?.defer !== false) {\n\t\t// Queue for later - will be flushed on agent_end\n\t\tthis._pendingBashMessages.push(bashMessage);\n\t} else if (options?.persist !== false) {\n\t\t// Persist first, then refresh the finalized context from the canonical projection.\n\t\tthis.sessionManager.appendMessage(bashMessage);\n\t\tthis._refreshFinalizedContext();\n\t} else {\n\t\t// Avoid writing a source-owned result into a shared manager that an\n\t\t// in-memory fork changed while this execution was active. The result stays\n\t\t// visible to this run only, so it must be added to agent state directly.\n\t\tthis.agent.state.messages.push(bashMessage);\n\t}\n}\n\n/** Cancel one correlated bash request, or all active requests for legacy callers. */\nexport function abortBash(this: AgentSession, id?: string): void {\n\tif (id !== undefined) {\n\t\tfor (const controller of [...(this._bashAbortControllers.get(id) ?? [])]) controller.abort();\n\t\treturn;\n\t}\n\t// Snapshot first: aborting settles owners, and a listener that removes its own\n\t// entry must not shorten the cancellation sweep.\n\tfor (const controllers of [...this._bashAbortControllers.values()]) {\n\t\tfor (const controller of [...controllers]) controller.abort();\n\t}\n}\n\n/** Whether a bash command is currently running */\n\nexport function _flushPendingBashMessages(this: AgentSession): void {\n\tif (this._pendingBashMessages.length === 0) return;\n\n\tfor (const bashMessage of this._pendingBashMessages) {\n\t\tthis.sessionManager.appendMessage(bashMessage);\n\t}\n\tthis._pendingBashMessages = [];\n\tthis._refreshFinalizedContext();\n}\n\n// =========================================================================\n// Session Management\n// =========================================================================\n\n/**\n * Set a display name for the current session.\n */\n\nexport const agentSessionBashMethods = {\n\texecuteBash,\n\trecordBashResult,\n\tabortBash,\n\t_flushPendingBashMessages,\n};\n"]}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical session context boundaries.
|
|
3
|
+
*
|
|
4
|
+
* The SessionManager projection is the authoritative model context: every provider
|
|
5
|
+
* request is built from it, recovery paths omit failed attempts through append-only
|
|
6
|
+
* `context_edit` entries instead of slicing agent state, and extensions get two
|
|
7
|
+
* actionable boundaries (`turn_end`, `agent_before_settle`) that may append entries and
|
|
8
|
+
* request one explicit continuation.
|
|
9
|
+
*/
|
|
10
|
+
import type { AssistantMessage, ToolResultMessage } from "@bastani/pi-ai/compat";
|
|
11
|
+
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
12
|
+
import type { AgentSessionInternalSurface as AgentSession } from "./agent-session-methods.ts";
|
|
13
|
+
import type { AgentActivityOutcome, BoundaryContextPreview, SessionBoundaryDraft } from "./extensions/index.js";
|
|
14
|
+
import { type SessionEntry, SessionManager } from "./session-manager.ts";
|
|
15
|
+
type BoundaryKind = "turn_end" | "agent_before_settle";
|
|
16
|
+
/**
|
|
17
|
+
* Materialize the canonical projection as finalized context. Atomic repairs tool-call
|
|
18
|
+
* pairing in derived context only (a resumed session may end on a tool call whose engine
|
|
19
|
+
* died before recording its result) and applies the session's configured projection
|
|
20
|
+
* transform; the durable transcript is never rewritten.
|
|
21
|
+
*/
|
|
22
|
+
export declare function _projectFinalizedMessages(this: AgentSession): AgentMessage[];
|
|
23
|
+
/** Refresh the public finalized transcript from the canonical session projection. */
|
|
24
|
+
export declare function _refreshFinalizedContext(this: AgentSession): void;
|
|
25
|
+
/** Refresh the public finalized transcript from the canonical session projection. */
|
|
26
|
+
export declare function refreshContext(this: AgentSession): void;
|
|
27
|
+
/** Route every provider request through the canonical session projection. */
|
|
28
|
+
export declare function _installAgentRequestProjection(this: AgentSession): void;
|
|
29
|
+
/** Dispatch the actionable `turn_end` boundary from `finishTurn`, before agent-core's own `turn_end`. */
|
|
30
|
+
export declare function _installAgentBoundaryHooks(this: AgentSession): void;
|
|
31
|
+
export declare function _dispatchTurnEndBoundary(this: AgentSession, message: AssistantMessage, toolResults: ToolResultMessage[], awaitPersistence?: boolean): Promise<boolean>;
|
|
32
|
+
export declare function _applyBoundaryDrafts(this: AgentSession, manager: SessionManager, drafts: SessionBoundaryDraft[]): SessionEntry[];
|
|
33
|
+
export declare function _createBoundaryPreviewManager(this: AgentSession, drafts: SessionBoundaryDraft[]): SessionManager;
|
|
34
|
+
export declare function _getPendingBoundaryMessages(this: AgentSession): AgentMessage[];
|
|
35
|
+
export declare function _buildBoundaryContext(this: AgentSession, drafts: SessionBoundaryDraft[], boundary: BoundaryKind): BoundaryContextPreview;
|
|
36
|
+
export declare function _commitBoundaryDrafts(this: AgentSession, drafts: SessionBoundaryDraft[]): void;
|
|
37
|
+
export declare function _reportInvalidBoundaryContinuation(this: AgentSession, event: BoundaryKind): void;
|
|
38
|
+
export declare function _findPersistedMessageEntryId(this: AgentSession, message: AgentMessage): string | undefined;
|
|
39
|
+
/** Keep a failed attempt in raw history while durably omitting it from model projection. */
|
|
40
|
+
export declare function _omitRecoveryAttempt(this: AgentSession, message: AssistantMessage, toolResults?: AgentMessage[]): void;
|
|
41
|
+
/**
|
|
42
|
+
* Omit the trailing assistant attempt (and any tool results it produced) from model
|
|
43
|
+
* projection when the loop must resume from the preceding input. Returns true when an
|
|
44
|
+
* assistant attempt was omitted.
|
|
45
|
+
*/
|
|
46
|
+
export declare function _omitTrailingAssistantAttempt(this: AgentSession, accept?: (message: AssistantMessage) => boolean): boolean;
|
|
47
|
+
/** Run the pre-settlement boundary. Returns true when the run must continue once more. */
|
|
48
|
+
export declare function _runBeforeSettleBoundary(this: AgentSession): Promise<boolean>;
|
|
49
|
+
export declare const agentSessionBoundaryMethods: {
|
|
50
|
+
_refreshFinalizedContext: typeof _refreshFinalizedContext;
|
|
51
|
+
_projectFinalizedMessages: typeof _projectFinalizedMessages;
|
|
52
|
+
refreshContext: typeof refreshContext;
|
|
53
|
+
_installAgentRequestProjection: typeof _installAgentRequestProjection;
|
|
54
|
+
_installAgentBoundaryHooks: typeof _installAgentBoundaryHooks;
|
|
55
|
+
_dispatchTurnEndBoundary: typeof _dispatchTurnEndBoundary;
|
|
56
|
+
_applyBoundaryDrafts: typeof _applyBoundaryDrafts;
|
|
57
|
+
_createBoundaryPreviewManager: typeof _createBoundaryPreviewManager;
|
|
58
|
+
_getPendingBoundaryMessages: typeof _getPendingBoundaryMessages;
|
|
59
|
+
_buildBoundaryContext: typeof _buildBoundaryContext;
|
|
60
|
+
_commitBoundaryDrafts: typeof _commitBoundaryDrafts;
|
|
61
|
+
_reportInvalidBoundaryContinuation: typeof _reportInvalidBoundaryContinuation;
|
|
62
|
+
_findPersistedMessageEntryId: typeof _findPersistedMessageEntryId;
|
|
63
|
+
_omitRecoveryAttempt: typeof _omitRecoveryAttempt;
|
|
64
|
+
_omitTrailingAssistantAttempt: typeof _omitTrailingAssistantAttempt;
|
|
65
|
+
_runBeforeSettleBoundary: typeof _runBeforeSettleBoundary;
|
|
66
|
+
};
|
|
67
|
+
export type { AgentActivityOutcome };
|
|
68
|
+
//# sourceMappingURL=agent-session-boundaries.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-session-boundaries.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-boundaries.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACjF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAClE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAW9F,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAEhH,OAAO,EAAE,KAAK,YAAY,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAEzE,KAAK,YAAY,GAAG,UAAU,GAAG,qBAAqB,CAAC;AAEvD;;;;;GAKG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,YAAY,GAAG,YAAY,EAAE,CAM5E;AAUD,qFAAqF;AACrF,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAEjE;AAED,qFAAqF;AACrF,wBAAgB,cAAc,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAEvD;AAED,6EAA6E;AAC7E,wBAAgB,8BAA8B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAoCvE;AAED,yGAAyG;AACzG,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAUnE;AAED,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,gBAAgB,EACzB,WAAW,EAAE,iBAAiB,EAAE,EAChC,gBAAgB,UAAQ,GACtB,OAAO,CAAC,OAAO,CAAC,CAsClB;AAiCD,wBAAgB,o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onical session context boundaries.
|
|
3
|
+
*
|
|
4
|
+
* The SessionManager projection is the authoritative model context: every provider
|
|
5
|
+
* request is built from it, recovery paths omit failed attempts through append-only
|
|
6
|
+
* `context_edit` entries instead of slicing agent state, and extensions get two
|
|
7
|
+
* actionable boundaries (`turn_end`, `agent_before_settle`) that may append entries and
|
|
8
|
+
* request one explicit continuation.
|
|
9
|
+
*/
|
|
10
|
+
import { COMPACTION_AUTO_QUERY } from "./compaction/compaction-parameters.js";
|
|
11
|
+
import { DEFAULT_COMPRESSION_RATIO, DEFAULT_PRESERVE_RECENT, estimateProjectedContextTokens, serializeConversationForCompaction, VERBATIM_COMPACTION_PROMPT_VERSION, VERBATIM_COMPACTION_STRATEGY, } from "./compaction/index.js";
|
|
12
|
+
import { convertToLlm, deferMessagesInterleavedWithToolBatch, repairOrphanToolResults } from "./messages.js";
|
|
13
|
+
import { SessionManager } from "./session-manager.js";
|
|
14
|
+
/**
|
|
15
|
+
* Materialize the canonical projection as finalized context. Atomic repairs tool-call
|
|
16
|
+
* pairing in derived context only (a resumed session may end on a tool call whose engine
|
|
17
|
+
* died before recording its result) and applies the session's configured projection
|
|
18
|
+
* transform; the durable transcript is never rewritten.
|
|
19
|
+
*/
|
|
20
|
+
export function _projectFinalizedMessages() {
|
|
21
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
22
|
+
for (const entry of projection.entries) {
|
|
23
|
+
for (const message of entry.messages)
|
|
24
|
+
this._entryIdsByMessage.set(message, entry.sourceEntry.id);
|
|
25
|
+
}
|
|
26
|
+
return finalizeProjectedMessages(this, projection.messages);
|
|
27
|
+
}
|
|
28
|
+
function finalizeProjectedMessages(session, messages) {
|
|
29
|
+
// While a run is active the loop owns pairing for the in-flight tool batch.
|
|
30
|
+
const repaired = repairOrphanToolResults(deferMessagesInterleavedWithToolBatch(messages), {
|
|
31
|
+
repairTrailing: !session.isStreaming,
|
|
32
|
+
});
|
|
33
|
+
return session._contextProjectionTransform ? session._contextProjectionTransform(repaired) : repaired;
|
|
34
|
+
}
|
|
35
|
+
/** Refresh the public finalized transcript from the canonical session projection. */
|
|
36
|
+
export function _refreshFinalizedContext() {
|
|
37
|
+
this.agent.state.messages = this._projectFinalizedMessages();
|
|
38
|
+
}
|
|
39
|
+
/** Refresh the public finalized transcript from the canonical session projection. */
|
|
40
|
+
export function refreshContext() {
|
|
41
|
+
this._refreshFinalizedContext();
|
|
42
|
+
}
|
|
43
|
+
/** Route every provider request through the canonical session projection. */
|
|
44
|
+
export function _installAgentRequestProjection() {
|
|
45
|
+
const previousPrepareRequest = this.agent.prepareRequest;
|
|
46
|
+
this.agent.prepareRequest = async (request, signal) => {
|
|
47
|
+
// Session listeners persist messages asynchronously; the projection is canonical
|
|
48
|
+
// only once every queued event has been applied to the session manager. The whole
|
|
49
|
+
// queue is the barrier, not just persistence: message_end handlers may replace the
|
|
50
|
+
// message that gets persisted, and extension dispatch is serialized in event order,
|
|
51
|
+
// so the last message_end cannot settle before earlier handlers. A failed listener
|
|
52
|
+
// is reported through the queue's own recovery, never through the request.
|
|
53
|
+
await this._agentEventQueue.catch(() => { });
|
|
54
|
+
// Atomic honors a caller's complete replacement context from prepareNextTurnWithContext
|
|
55
|
+
// for exactly the request it prepared.
|
|
56
|
+
const callerReplaced = this._callerReplacedNextRequestContext;
|
|
57
|
+
this._callerReplacedNextRequestContext = false;
|
|
58
|
+
const canonicalContext = {
|
|
59
|
+
...request.context,
|
|
60
|
+
messages: callerReplaced ? request.context.messages : this._projectFinalizedMessages(),
|
|
61
|
+
// Messages declare the provider-visible loadout; context.tools keeps executable implementations.
|
|
62
|
+
tools: this.agent.state.tools.slice(),
|
|
63
|
+
};
|
|
64
|
+
const previous = await previousPrepareRequest?.({
|
|
65
|
+
...request,
|
|
66
|
+
context: canonicalContext,
|
|
67
|
+
model: this.agent.state.model,
|
|
68
|
+
thinkingLevel: this.agent.state.thinkingLevel,
|
|
69
|
+
}, signal);
|
|
70
|
+
return {
|
|
71
|
+
...previous,
|
|
72
|
+
context: previous?.context ?? canonicalContext,
|
|
73
|
+
model: previous?.model ?? this.agent.state.model,
|
|
74
|
+
thinkingLevel: previous?.thinkingLevel ?? this.agent.state.thinkingLevel,
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
/** Dispatch the actionable `turn_end` boundary from `finishTurn`, before agent-core's own `turn_end`. */
|
|
79
|
+
export function _installAgentBoundaryHooks() {
|
|
80
|
+
const previousFinishTurn = this.agent.finishTurn;
|
|
81
|
+
this.agent.finishTurn = async (turn, signal) => {
|
|
82
|
+
this._boundaryDispatchedMessages.add(turn.message);
|
|
83
|
+
const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults, true);
|
|
84
|
+
const previousDecision = await previousFinishTurn?.(turn, signal);
|
|
85
|
+
if (previousDecision?.action === "end")
|
|
86
|
+
return previousDecision;
|
|
87
|
+
if (extensionContinue || previousDecision?.action === "continue")
|
|
88
|
+
return { action: "continue" };
|
|
89
|
+
return undefined;
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export async function _dispatchTurnEndBoundary(message, toolResults, awaitPersistence = false) {
|
|
93
|
+
this._lastActivityOutcome =
|
|
94
|
+
message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
|
|
95
|
+
if (!this._extensionRunner.hasHandlers("turn_end"))
|
|
96
|
+
return false;
|
|
97
|
+
// The boundary resolves persisted entry IDs. From finishTurn, session listeners may
|
|
98
|
+
// still be persisting this turn; from the serialized event queue they already have.
|
|
99
|
+
if (awaitPersistence)
|
|
100
|
+
await this._agentEventQueue.catch(() => { });
|
|
101
|
+
const messageEntryId = this._findPersistedMessageEntryId(message);
|
|
102
|
+
if (!messageEntryId) {
|
|
103
|
+
this._extensionRunner.emitError({
|
|
104
|
+
extensionPath: "<boundary>",
|
|
105
|
+
event: "turn_end",
|
|
106
|
+
error: "turn_end could not resolve the persisted assistant entry ID",
|
|
107
|
+
});
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
const toolResultEntryIds = toolResults.flatMap((result) => {
|
|
111
|
+
const entryId = this._findPersistedMessageEntryId(result);
|
|
112
|
+
return entryId ? [entryId] : [];
|
|
113
|
+
});
|
|
114
|
+
const boundary = await this._extensionRunner.emitBoundary({
|
|
115
|
+
type: "turn_end",
|
|
116
|
+
turnIndex: this._turnIndex,
|
|
117
|
+
message,
|
|
118
|
+
toolResults,
|
|
119
|
+
messageEntryId,
|
|
120
|
+
toolResultEntryIds,
|
|
121
|
+
outcome: this._lastActivityOutcome,
|
|
122
|
+
}, (entries) => this._buildBoundaryContext(entries, "turn_end"));
|
|
123
|
+
this._commitBoundaryDrafts(boundary.entries);
|
|
124
|
+
if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
|
|
125
|
+
this._reportInvalidBoundaryContinuation("turn_end");
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
return boundary.continue;
|
|
129
|
+
}
|
|
130
|
+
function extensionCompactionDetails(manager, summary, tokensBefore) {
|
|
131
|
+
const linesBefore = serializeConversationForCompaction(convertToLlm(manager.buildSessionProjection().messages)).split("\n").length;
|
|
132
|
+
const linesKept = summary.split("\n").length;
|
|
133
|
+
const tokensAfter = Math.ceil(summary.length / 4);
|
|
134
|
+
return {
|
|
135
|
+
strategy: VERBATIM_COMPACTION_STRATEGY,
|
|
136
|
+
promptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,
|
|
137
|
+
parameters: {
|
|
138
|
+
compression_ratio: DEFAULT_COMPRESSION_RATIO,
|
|
139
|
+
preserve_recent: DEFAULT_PRESERVE_RECENT,
|
|
140
|
+
query: COMPACTION_AUTO_QUERY,
|
|
141
|
+
},
|
|
142
|
+
stats: {
|
|
143
|
+
linesBefore,
|
|
144
|
+
linesDeleted: Math.max(0, linesBefore - linesKept),
|
|
145
|
+
linesKept,
|
|
146
|
+
rangeCount: 0,
|
|
147
|
+
tokensBefore,
|
|
148
|
+
tokensAfter,
|
|
149
|
+
percentReduction: tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10,
|
|
150
|
+
},
|
|
151
|
+
rung: "extension",
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export function _applyBoundaryDrafts(manager, drafts) {
|
|
155
|
+
const appended = [];
|
|
156
|
+
for (const draft of drafts) {
|
|
157
|
+
let entryId;
|
|
158
|
+
switch (draft.type) {
|
|
159
|
+
case "custom":
|
|
160
|
+
entryId = manager.appendCustomEntry(draft.customType, draft.data);
|
|
161
|
+
break;
|
|
162
|
+
case "custom_message":
|
|
163
|
+
entryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
|
|
164
|
+
break;
|
|
165
|
+
case "context_edit":
|
|
166
|
+
entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
|
|
167
|
+
break;
|
|
168
|
+
case "compaction": {
|
|
169
|
+
if (draft.summary.trim().length === 0)
|
|
170
|
+
throw new Error("Compaction draft summary must not be empty");
|
|
171
|
+
const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
|
|
172
|
+
entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, extensionCompactionDetails(manager, draft.summary, tokensBefore), draft.usage);
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const entry = manager.getEntry(entryId);
|
|
177
|
+
if (entry)
|
|
178
|
+
appended.push(entry);
|
|
179
|
+
}
|
|
180
|
+
return appended;
|
|
181
|
+
}
|
|
182
|
+
export function _createBoundaryPreviewManager(drafts) {
|
|
183
|
+
const header = this.sessionManager.getHeader();
|
|
184
|
+
if (!header)
|
|
185
|
+
throw new Error("Session header is missing");
|
|
186
|
+
const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
|
|
187
|
+
this._applyBoundaryDrafts(manager, drafts);
|
|
188
|
+
return manager;
|
|
189
|
+
}
|
|
190
|
+
export function _getPendingBoundaryMessages() {
|
|
191
|
+
return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
|
|
192
|
+
}
|
|
193
|
+
export function _buildBoundaryContext(drafts, boundary) {
|
|
194
|
+
const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
|
|
195
|
+
const contextMessages = finalizeProjectedMessages(this, projection.messages);
|
|
196
|
+
const pendingMessages = this._getPendingBoundaryMessages();
|
|
197
|
+
const llmMessages = convertToLlm(contextMessages);
|
|
198
|
+
const finalRole = llmMessages[llmMessages.length - 1]?.role;
|
|
199
|
+
const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
|
|
200
|
+
const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
|
|
201
|
+
const pendingCustomContext = this._pendingCustomMessages.length > 0;
|
|
202
|
+
return {
|
|
203
|
+
contextEntries: projection.entries,
|
|
204
|
+
contextMessages,
|
|
205
|
+
llmMessages,
|
|
206
|
+
pendingMessages,
|
|
207
|
+
canContinue: contextCanContinue ||
|
|
208
|
+
pendingCustomContext ||
|
|
209
|
+
(boundary === "turn_end"
|
|
210
|
+
? this.agent.hasQueuedMessages()
|
|
211
|
+
: finalRole === "assistant" && this.agent.hasQueuedMessages()),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
export function _commitBoundaryDrafts(drafts) {
|
|
215
|
+
const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
|
|
216
|
+
this._refreshFinalizedContext();
|
|
217
|
+
for (const entry of appended)
|
|
218
|
+
this._emit({ type: "entry_appended", entry });
|
|
219
|
+
}
|
|
220
|
+
export function _reportInvalidBoundaryContinuation(event) {
|
|
221
|
+
this._extensionRunner.emitError({
|
|
222
|
+
extensionPath: "<boundary>",
|
|
223
|
+
event,
|
|
224
|
+
error: `${event} requested continuation without runnable model context`,
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
export function _findPersistedMessageEntryId(message) {
|
|
228
|
+
const mapped = this._entryIdsByMessage.get(message);
|
|
229
|
+
if (mapped)
|
|
230
|
+
return mapped;
|
|
231
|
+
for (const entry of [...this.sessionManager.getBranch()].reverse()) {
|
|
232
|
+
if (entry.type === "message" && entry.message === message)
|
|
233
|
+
return entry.id;
|
|
234
|
+
}
|
|
235
|
+
const messageIndex = this.agent.state.messages.indexOf(message);
|
|
236
|
+
if (messageIndex < 0)
|
|
237
|
+
return undefined;
|
|
238
|
+
const projection = this.sessionManager.buildSessionProjection();
|
|
239
|
+
let projectedIndex = 0;
|
|
240
|
+
for (const entry of projection.entries) {
|
|
241
|
+
for (let i = 0; i < entry.messages.length; i++) {
|
|
242
|
+
if (projectedIndex === messageIndex) {
|
|
243
|
+
this._entryIdsByMessage.set(message, entry.sourceEntry.id);
|
|
244
|
+
return entry.sourceEntry.id;
|
|
245
|
+
}
|
|
246
|
+
projectedIndex++;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return undefined;
|
|
250
|
+
}
|
|
251
|
+
/** Keep a failed attempt in raw history while durably omitting it from model projection. */
|
|
252
|
+
export function _omitRecoveryAttempt(message, toolResults = []) {
|
|
253
|
+
const targets = [message, ...toolResults];
|
|
254
|
+
const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
|
|
255
|
+
const unresolvedProjectedTarget = targets.some((target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target));
|
|
256
|
+
if (unresolvedProjectedTarget) {
|
|
257
|
+
throw new Error("Cannot persist recovery omission because a projected message has no source entry");
|
|
258
|
+
}
|
|
259
|
+
for (const targetId of targetIds) {
|
|
260
|
+
if (!targetId)
|
|
261
|
+
continue;
|
|
262
|
+
const editId = this.sessionManager.appendContextEdit(targetId, null);
|
|
263
|
+
const entry = this.sessionManager.getEntry(editId);
|
|
264
|
+
if (entry)
|
|
265
|
+
this._emit({ type: "entry_appended", entry });
|
|
266
|
+
}
|
|
267
|
+
this._refreshFinalizedContext();
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Omit the trailing assistant attempt (and any tool results it produced) from model
|
|
271
|
+
* projection when the loop must resume from the preceding input. Returns true when an
|
|
272
|
+
* assistant attempt was omitted.
|
|
273
|
+
*/
|
|
274
|
+
export function _omitTrailingAssistantAttempt(accept = () => true) {
|
|
275
|
+
const messages = this.agent.state.messages;
|
|
276
|
+
let index = messages.length - 1;
|
|
277
|
+
const trailingToolResults = [];
|
|
278
|
+
while (index >= 0 && messages[index]?.role === "toolResult") {
|
|
279
|
+
trailingToolResults.unshift(messages[index]);
|
|
280
|
+
index--;
|
|
281
|
+
}
|
|
282
|
+
const candidate = messages[index];
|
|
283
|
+
if (candidate?.role !== "assistant")
|
|
284
|
+
return false;
|
|
285
|
+
const assistant = candidate;
|
|
286
|
+
if (!accept(assistant))
|
|
287
|
+
return false;
|
|
288
|
+
this._omitRecoveryAttempt(assistant, trailingToolResults);
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
291
|
+
/** Run the pre-settlement boundary. Returns true when the run must continue once more. */
|
|
292
|
+
export async function _runBeforeSettleBoundary() {
|
|
293
|
+
if (!this._extensionRunner.hasHandlers("agent_before_settle"))
|
|
294
|
+
return false;
|
|
295
|
+
this._isBeforeSettle = true;
|
|
296
|
+
this._abortDuringBeforeSettle = false;
|
|
297
|
+
try {
|
|
298
|
+
const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, (entries) => this._buildBoundaryContext(entries, "agent_before_settle"));
|
|
299
|
+
this._commitBoundaryDrafts(result.entries);
|
|
300
|
+
this._flushPendingCustomMessages();
|
|
301
|
+
const finalContext = this._buildBoundaryContext([], "agent_before_settle");
|
|
302
|
+
if (this._abortDuringBeforeSettle)
|
|
303
|
+
return false;
|
|
304
|
+
const shouldContinue = result.continue || this.agent.hasQueuedMessages();
|
|
305
|
+
if (shouldContinue && !finalContext.canContinue) {
|
|
306
|
+
if (result.continue)
|
|
307
|
+
this._reportInvalidBoundaryContinuation("agent_before_settle");
|
|
308
|
+
return false;
|
|
309
|
+
}
|
|
310
|
+
return shouldContinue;
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
this._isBeforeSettle = false;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
export const agentSessionBoundaryMethods = {
|
|
317
|
+
_refreshFinalizedContext,
|
|
318
|
+
_projectFinalizedMessages,
|
|
319
|
+
refreshContext,
|
|
320
|
+
_installAgentRequestProjection,
|
|
321
|
+
_installAgentBoundaryHooks,
|
|
322
|
+
_dispatchTurnEndBoundary,
|
|
323
|
+
_applyBoundaryDrafts,
|
|
324
|
+
_createBoundaryPreviewManager,
|
|
325
|
+
_getPendingBoundaryMessages,
|
|
326
|
+
_buildBoundaryContext,
|
|
327
|
+
_commitBoundaryDrafts,
|
|
328
|
+
_reportInvalidBoundaryContinuation,
|
|
329
|
+
_findPersistedMessageEntryId,
|
|
330
|
+
_omitRecoveryAttempt,
|
|
331
|
+
_omitTrailingAssistantAttempt,
|
|
332
|
+
_runBeforeSettleBoundary,
|
|
333
|
+
};
|
|
334
|
+
//# sourceMappingURL=agent-session-boundaries.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent-session-boundaries.js","sourceRoot":"","sources":["../../src/core/agent-session-boundaries.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AAC9E,OAAO,EACN,yBAAyB,EACzB,uBAAuB,EACvB,8BAA8B,EAC9B,kCAAkC,EAClC,kCAAkC,EAClC,4BAA4B,GAE5B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,YAAY,EAAE,qCAAqC,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAC7G,OAAO,EAAqB,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAIzE;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB;IACxC,MAAM,UAAU,GAAG,IAAI,CAAC,cAAc,CAAC,sBAAsB,EAAE,CAAC;IAChE,KAAK,MAA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B,CAAC,OAAO,EAAE,qBAAqB,CAAC,CACvE,CAAC;QACF,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAC3C,IAAI,CAAC,2BAA2B,EAAE,CAAC;QACnC,MAAM,YAAY,GAAG,IAAI,CAAC,qBAAqB,CAAC,EAAE,EAAE,qBAAqB,CAAC,CAAC;QAC3E,IAAI,IAAI,CAAC,wBAAwB;YAAE,OAAO,KAAK,CAAC;QAChD,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,IAAI,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC;QACzE,IAAI,cAAc,IAAI,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC;YACjD,IAAI,MAAM,CAAC,QAAQ;gBAAE,IAAI,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,CAAC;YACpF,OAAO,KAAK,CAAC;QACd,CAAC;QACD,OAAO,cAAc,CAAC;IACvB,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;IAC9B,CAAC;AACF,CAAC;AAED,MAAM,CAAC,MAAM,2BAA2B,GAAG;IAC1C,wBAAwB;IACxB,yBAAyB;IACzB,cAAc;IACd,8BAA8B;IAC9B,0BAA0B;IAC1B,wBAAwB;IACxB,oBAAoB;IACpB,6BAA6B;IAC7B,2BAA2B;IAC3B,qBAAqB;IACrB,qBAAqB;IACrB,kCAAkC;IAClC,4BAA4B;IAC5B,oBAAoB;IACpB,6BAA6B;IAC7B,wBAAwB;CACxB,CAAC","sourcesContent":["/**\n * Canonical session context boundaries.\n *\n * The SessionManager projection is the authoritative model context: every provider\n * request is built from it, recovery paths omit failed attempts through append-only\n * `context_edit` entries instead of slicing agent state, and extensions get two\n * actionable boundaries (`turn_end`, `agent_before_settle`) that may append entries and\n * request one explicit continuation.\n */\n\nimport type { AssistantMessage, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { COMPACTION_AUTO_QUERY } from \"./compaction/compaction-parameters.js\";\nimport {\n\tDEFAULT_COMPRESSION_RATIO,\n\tDEFAULT_PRESERVE_RECENT,\n\testimateProjectedContextTokens,\n\tserializeConversationForCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n} from \"./compaction/index.ts\";\nimport type { AgentActivityOutcome, BoundaryContextPreview, SessionBoundaryDraft } from \"./extensions/index.js\";\nimport { convertToLlm, deferMessagesInterleavedWithToolBatch, repairOrphanToolResults } from \"./messages.ts\";\nimport { type SessionEntry, SessionManager } from \"./session-manager.ts\";\n\ntype BoundaryKind = \"turn_end\" | \"agent_before_settle\";\n\n/**\n * Materialize the canonical projection as finalized context. Atomic repairs tool-call\n * pairing in derived context only (a resumed session may end on a tool call whose engine\n * died before recording its result) and applies the session's configured projection\n * transform; the durable transcript is never rewritten.\n */\nexport function _projectFinalizedMessages(this: AgentSession): AgentMessage[] {\n\tconst projection = this.sessionManager.buildSessionProjection();\n\tfor (const entry of projection.entries) {\n\t\tfor (const message of entry.messages) this._entryIdsByMessage.set(message, entry.sourceEntry.id);\n\t}\n\treturn finalizeProjectedMessages(this, projection.messages);\n}\n\nfunction finalizeProjectedMessages(session: AgentSession, messages: AgentMessage[]): AgentMessage[] {\n\t// While a run is active the loop owns pairing for the in-flight tool batch.\n\tconst repaired = repairOrphanToolResults(deferMessagesInterleavedWithToolBatch(messages), {\n\t\trepairTrailing: !session.isStreaming,\n\t});\n\treturn session._contextProjectionTransform ? session._contextProjectionTransform(repaired) : repaired;\n}\n\n/** Refresh the public finalized transcript from the canonical session projection. */\nexport function _refreshFinalizedContext(this: AgentSession): void {\n\tthis.agent.state.messages = this._projectFinalizedMessages();\n}\n\n/** Refresh the public finalized transcript from the canonical session projection. */\nexport function refreshContext(this: AgentSession): void {\n\tthis._refreshFinalizedContext();\n}\n\n/** Route every provider request through the canonical session projection. */\nexport function _installAgentRequestProjection(this: AgentSession): void {\n\tconst previousPrepareRequest = this.agent.prepareRequest;\n\tthis.agent.prepareRequest = async (request, signal) => {\n\t\t// Session listeners persist messages asynchronously; the projection is canonical\n\t\t// only once every queued event has been applied to the session manager. The whole\n\t\t// queue is the barrier, not just persistence: message_end handlers may replace the\n\t\t// message that gets persisted, and extension dispatch is serialized in event order,\n\t\t// so the last message_end cannot settle before earlier handlers. A failed listener\n\t\t// is reported through the queue's own recovery, never through the request.\n\t\tawait this._agentEventQueue.catch(() => {});\n\t\t// Atomic honors a caller's complete replacement context from prepareNextTurnWithContext\n\t\t// for exactly the request it prepared.\n\t\tconst callerReplaced = this._callerReplacedNextRequestContext;\n\t\tthis._callerReplacedNextRequestContext = false;\n\t\tconst canonicalContext = {\n\t\t\t...request.context,\n\t\t\tmessages: callerReplaced ? request.context.messages : this._projectFinalizedMessages(),\n\t\t\t// Messages declare the provider-visible loadout; context.tools keeps executable implementations.\n\t\t\ttools: this.agent.state.tools.slice(),\n\t\t};\n\t\tconst previous = await previousPrepareRequest?.(\n\t\t\t{\n\t\t\t\t...request,\n\t\t\t\tcontext: canonicalContext,\n\t\t\t\tmodel: this.agent.state.model,\n\t\t\t\tthinkingLevel: this.agent.state.thinkingLevel,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t\treturn {\n\t\t\t...previous,\n\t\t\tcontext: previous?.context ?? canonicalContext,\n\t\t\tmodel: previous?.model ?? this.agent.state.model,\n\t\t\tthinkingLevel: previous?.thinkingLevel ?? this.agent.state.thinkingLevel,\n\t\t};\n\t};\n}\n\n/** Dispatch the actionable `turn_end` boundary from `finishTurn`, before agent-core's own `turn_end`. */\nexport function _installAgentBoundaryHooks(this: AgentSession): void {\n\tconst previousFinishTurn = this.agent.finishTurn;\n\tthis.agent.finishTurn = async (turn, signal) => {\n\t\tthis._boundaryDispatchedMessages.add(turn.message);\n\t\tconst extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults, true);\n\t\tconst previousDecision = await previousFinishTurn?.(turn, signal);\n\t\tif (previousDecision?.action === \"end\") return previousDecision;\n\t\tif (extensionContinue || previousDecision?.action === \"continue\") return { action: \"continue\" };\n\t\treturn undefined;\n\t};\n}\n\nexport async function _dispatchTurnEndBoundary(\n\tthis: AgentSession,\n\tmessage: AssistantMessage,\n\ttoolResults: ToolResultMessage[],\n\tawaitPersistence = false,\n): Promise<boolean> {\n\tthis._lastActivityOutcome =\n\t\tmessage.stopReason === \"aborted\" ? \"aborted\" : message.stopReason === \"error\" ? \"error\" : \"completed\";\n\tif (!this._extensionRunner.hasHandlers(\"turn_end\")) return false;\n\t// The boundary resolves persisted entry IDs. From finishTurn, session listeners may\n\t// still be persisting this turn; from the serialized event queue they already have.\n\tif (awaitPersistence) await this._agentEventQueue.catch(() => {});\n\tconst messageEntryId = this._findPersistedMessageEntryId(message);\n\tif (!messageEntryId) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<boundary>\",\n\t\t\tevent: \"turn_end\",\n\t\t\terror: \"turn_end could not resolve the persisted assistant entry ID\",\n\t\t});\n\t\treturn false;\n\t}\n\tconst toolResultEntryIds = toolResults.flatMap((result) => {\n\t\tconst entryId = this._findPersistedMessageEntryId(result);\n\t\treturn entryId ? [entryId] : [];\n\t});\n\tconst boundary = await this._extensionRunner.emitBoundary(\n\t\t{\n\t\t\ttype: \"turn_end\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\tmessage,\n\t\t\ttoolResults,\n\t\t\tmessageEntryId,\n\t\t\ttoolResultEntryIds,\n\t\t\toutcome: this._lastActivityOutcome,\n\t\t},\n\t\t(entries) => this._buildBoundaryContext(entries, \"turn_end\"),\n\t);\n\tthis._commitBoundaryDrafts(boundary.entries);\n\tif (boundary.continue && !this._buildBoundaryContext([], \"turn_end\").canContinue) {\n\t\tthis._reportInvalidBoundaryContinuation(\"turn_end\");\n\t\treturn false;\n\t}\n\treturn boundary.continue;\n}\n\nfunction extensionCompactionDetails(\n\tmanager: SessionManager,\n\tsummary: string,\n\ttokensBefore: number,\n): VerbatimCompactionDetails {\n\tconst linesBefore = serializeConversationForCompaction(\n\t\tconvertToLlm(manager.buildSessionProjection().messages),\n\t).split(\"\\n\").length;\n\tconst linesKept = summary.split(\"\\n\").length;\n\tconst tokensAfter = Math.ceil(summary.length / 4);\n\treturn {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: {\n\t\t\tcompression_ratio: DEFAULT_COMPRESSION_RATIO,\n\t\t\tpreserve_recent: DEFAULT_PRESERVE_RECENT,\n\t\t\tquery: COMPACTION_AUTO_QUERY,\n\t\t},\n\t\tstats: {\n\t\t\tlinesBefore,\n\t\t\tlinesDeleted: Math.max(0, linesBefore - linesKept),\n\t\t\tlinesKept,\n\t\t\trangeCount: 0,\n\t\t\ttokensBefore,\n\t\t\ttokensAfter,\n\t\t\tpercentReduction: tokensBefore === 0 ? 0 : Math.round((1 - tokensAfter / tokensBefore) * 1000) / 10,\n\t\t},\n\t\trung: \"extension\",\n\t};\n}\n\nexport function _applyBoundaryDrafts(\n\tthis: AgentSession,\n\tmanager: SessionManager,\n\tdrafts: SessionBoundaryDraft[],\n): SessionEntry[] {\n\tconst appended: SessionEntry[] = [];\n\tfor (const draft of drafts) {\n\t\tlet entryId: string;\n\t\tswitch (draft.type) {\n\t\t\tcase \"custom\":\n\t\t\t\tentryId = manager.appendCustomEntry(draft.customType, draft.data);\n\t\t\t\tbreak;\n\t\t\tcase \"custom_message\":\n\t\t\t\tentryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);\n\t\t\t\tbreak;\n\t\t\tcase \"context_edit\":\n\t\t\t\tentryId = manager.appendContextEdit(draft.targetId, draft.replacement);\n\t\t\t\tbreak;\n\t\t\tcase \"compaction\": {\n\t\t\t\tif (draft.summary.trim().length === 0) throw new Error(\"Compaction draft summary must not be empty\");\n\t\t\t\tconst tokensBefore = estimateProjectedContextTokens(\n\t\t\t\t\tmanager.buildSessionProjection(),\n\t\t\t\t\tmanager.getBranch(),\n\t\t\t\t).tokens;\n\t\t\t\tentryId = manager.appendCompaction(\n\t\t\t\t\tdraft.summary,\n\t\t\t\t\tdraft.firstKeptEntryId,\n\t\t\t\t\ttokensBefore,\n\t\t\t\t\textensionCompactionDetails(manager, draft.summary, tokensBefore),\n\t\t\t\t\tdraft.usage,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst entry = manager.getEntry(entryId);\n\t\tif (entry) appended.push(entry);\n\t}\n\treturn appended;\n}\n\nexport function _createBoundaryPreviewManager(this: AgentSession, drafts: SessionBoundaryDraft[]): SessionManager {\n\tconst header = this.sessionManager.getHeader();\n\tif (!header) throw new Error(\"Session header is missing\");\n\tconst manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);\n\tthis._applyBoundaryDrafts(manager, drafts);\n\treturn manager;\n}\n\nexport function _getPendingBoundaryMessages(this: AgentSession): AgentMessage[] {\n\treturn [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];\n}\n\nexport function _buildBoundaryContext(\n\tthis: AgentSession,\n\tdrafts: SessionBoundaryDraft[],\n\tboundary: BoundaryKind,\n): BoundaryContextPreview {\n\tconst projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();\n\tconst contextMessages = finalizeProjectedMessages(this, projection.messages);\n\tconst pendingMessages = this._getPendingBoundaryMessages();\n\tconst llmMessages = convertToLlm(contextMessages);\n\tconst finalRole = llmMessages[llmMessages.length - 1]?.role;\n\tconst hasNonSystemContext = llmMessages.some((message) => message.role !== \"system\");\n\tconst contextCanContinue = hasNonSystemContext && finalRole !== \"assistant\";\n\tconst pendingCustomContext = this._pendingCustomMessages.length > 0;\n\treturn {\n\t\tcontextEntries: projection.entries,\n\t\tcontextMessages,\n\t\tllmMessages,\n\t\tpendingMessages,\n\t\tcanContinue:\n\t\t\tcontextCanContinue ||\n\t\t\tpendingCustomContext ||\n\t\t\t(boundary === \"turn_end\"\n\t\t\t\t? this.agent.hasQueuedMessages()\n\t\t\t\t: finalRole === \"assistant\" && this.agent.hasQueuedMessages()),\n\t};\n}\n\nexport function _commitBoundaryDrafts(this: AgentSession, drafts: SessionBoundaryDraft[]): void {\n\tconst appended = this._applyBoundaryDrafts(this.sessionManager, drafts);\n\tthis._refreshFinalizedContext();\n\tfor (const entry of appended) this._emit({ type: \"entry_appended\", entry });\n}\n\nexport function _reportInvalidBoundaryContinuation(this: AgentSession, event: BoundaryKind): void {\n\tthis._extensionRunner.emitError({\n\t\textensionPath: \"<boundary>\",\n\t\tevent,\n\t\terror: `${event} requested continuation without runnable model context`,\n\t});\n}\n\nexport function _findPersistedMessageEntryId(this: AgentSession, message: AgentMessage): string | undefined {\n\tconst mapped = this._entryIdsByMessage.get(message);\n\tif (mapped) return mapped;\n\tfor (const entry of [...this.sessionManager.getBranch()].reverse()) {\n\t\tif (entry.type === \"message\" && entry.message === message) return entry.id;\n\t}\n\n\tconst messageIndex = this.agent.state.messages.indexOf(message);\n\tif (messageIndex < 0) return undefined;\n\tconst projection = this.sessionManager.buildSessionProjection();\n\tlet projectedIndex = 0;\n\tfor (const entry of projection.entries) {\n\t\tfor (let i = 0; i < entry.messages.length; i++) {\n\t\t\tif (projectedIndex === messageIndex) {\n\t\t\t\tthis._entryIdsByMessage.set(message, entry.sourceEntry.id);\n\t\t\t\treturn entry.sourceEntry.id;\n\t\t\t}\n\t\t\tprojectedIndex++;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** Keep a failed attempt in raw history while durably omitting it from model projection. */\nexport function _omitRecoveryAttempt(\n\tthis: AgentSession,\n\tmessage: AssistantMessage,\n\ttoolResults: AgentMessage[] = [],\n): void {\n\tconst targets = [message, ...toolResults];\n\tconst targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));\n\tconst unresolvedProjectedTarget = targets.some(\n\t\t(target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target),\n\t);\n\tif (unresolvedProjectedTarget) {\n\t\tthrow new Error(\"Cannot persist recovery omission because a projected message has no source entry\");\n\t}\n\tfor (const targetId of targetIds) {\n\t\tif (!targetId) continue;\n\t\tconst editId = this.sessionManager.appendContextEdit(targetId, null);\n\t\tconst entry = this.sessionManager.getEntry(editId);\n\t\tif (entry) this._emit({ type: \"entry_appended\", entry });\n\t}\n\tthis._refreshFinalizedContext();\n}\n\n/**\n * Omit the trailing assistant attempt (and any tool results it produced) from model\n * projection when the loop must resume from the preceding input. Returns true when an\n * assistant attempt was omitted.\n */\nexport function _omitTrailingAssistantAttempt(\n\tthis: AgentSession,\n\taccept: (message: AssistantMessage) => boolean = () => true,\n): boolean {\n\tconst messages = this.agent.state.messages;\n\tlet index = messages.length - 1;\n\tconst trailingToolResults: AgentMessage[] = [];\n\twhile (index >= 0 && messages[index]?.role === \"toolResult\") {\n\t\ttrailingToolResults.unshift(messages[index]);\n\t\tindex--;\n\t}\n\tconst candidate = messages[index];\n\tif (candidate?.role !== \"assistant\") return false;\n\tconst assistant = candidate as AssistantMessage;\n\tif (!accept(assistant)) return false;\n\tthis._omitRecoveryAttempt(assistant, trailingToolResults);\n\treturn true;\n}\n\n/** Run the pre-settlement boundary. Returns true when the run must continue once more. */\nexport async function _runBeforeSettleBoundary(this: AgentSession): Promise<boolean> {\n\tif (!this._extensionRunner.hasHandlers(\"agent_before_settle\")) return false;\n\tthis._isBeforeSettle = true;\n\tthis._abortDuringBeforeSettle = false;\n\ttry {\n\t\tconst result = await this._extensionRunner.emitBoundary(\n\t\t\t{ type: \"agent_before_settle\", outcome: this._lastActivityOutcome },\n\t\t\t(entries) => this._buildBoundaryContext(entries, \"agent_before_settle\"),\n\t\t);\n\t\tthis._commitBoundaryDrafts(result.entries);\n\t\tthis._flushPendingCustomMessages();\n\t\tconst finalContext = this._buildBoundaryContext([], \"agent_before_settle\");\n\t\tif (this._abortDuringBeforeSettle) return false;\n\t\tconst shouldContinue = result.continue || this.agent.hasQueuedMessages();\n\t\tif (shouldContinue && !finalContext.canContinue) {\n\t\t\tif (result.continue) this._reportInvalidBoundaryContinuation(\"agent_before_settle\");\n\t\t\treturn false;\n\t\t}\n\t\treturn shouldContinue;\n\t} finally {\n\t\tthis._isBeforeSettle = false;\n\t}\n}\n\nexport const agentSessionBoundaryMethods = {\n\t_refreshFinalizedContext,\n\t_projectFinalizedMessages,\n\trefreshContext,\n\t_installAgentRequestProjection,\n\t_installAgentBoundaryHooks,\n\t_dispatchTurnEndBoundary,\n\t_applyBoundaryDrafts,\n\t_createBoundaryPreviewManager,\n\t_getPendingBoundaryMessages,\n\t_buildBoundaryContext,\n\t_commitBoundaryDrafts,\n\t_reportInvalidBoundaryContinuation,\n\t_findPersistedMessageEntryId,\n\t_omitRecoveryAttempt,\n\t_omitTrailingAssistantAttempt,\n\t_runBeforeSettleBoundary,\n};\n\nexport type { AgentActivityOutcome };\n"]}
|
|
@@ -172,7 +172,7 @@ export async function _applyVerbatimCompaction(options) {
|
|
|
172
172
|
...(backupPath ? { backupPath } : {}),
|
|
173
173
|
};
|
|
174
174
|
const entryId = this.sessionManager.appendCompaction(compacted.text, firstKeptEntryId, preparation.tokensBefore, details, compacted.usage);
|
|
175
|
-
this.
|
|
175
|
+
this._refreshFinalizedContext();
|
|
176
176
|
const result = {
|
|
177
177
|
compactedText: compacted.text,
|
|
178
178
|
firstKeptEntryId,
|