@bastani/atomic 0.9.53-alpha.1 → 0.9.54-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/core/agent-session-auto-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-auto-compaction.js +2 -1
- package/dist/core/agent-session-auto-compaction.js.map +1 -1
- package/dist/core/agent-session-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-compaction.js +2 -1
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/agent-session-extension-bindings.d.ts.map +1 -1
- package/dist/core/agent-session-extension-bindings.js +2 -1
- package/dist/core/agent-session-extension-bindings.js.map +1 -1
- package/dist/core/agent-session-models.d.ts +17 -1
- package/dist/core/agent-session-models.d.ts.map +1 -1
- package/dist/core/agent-session-models.js +19 -0
- package/dist/core/agent-session-models.js.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.d.ts.map +1 -1
- package/dist/core/agent-session-post-tool-compaction.js +2 -1
- package/dist/core/agent-session-post-tool-compaction.js.map +1 -1
- package/dist/core/agent-session-summary.d.ts.map +1 -1
- package/dist/core/agent-session-summary.js +2 -1
- package/dist/core/agent-session-summary.js.map +1 -1
- package/dist/core/agent-session-tree.d.ts.map +1 -1
- package/dist/core/agent-session-tree.js +2 -1
- package/dist/core/agent-session-tree.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +109 -74
- package/dist/core/exec.js.map +1 -1
- package/dist/core/extensions/loader-virtual-modules.js +2 -2
- package/dist/core/extensions/loader-virtual-modules.js.map +1 -1
- package/dist/core/model-resolver-patterns.d.ts.map +1 -1
- package/dist/core/model-resolver-patterns.js +15 -9
- package/dist/core/model-resolver-patterns.js.map +1 -1
- package/dist/core/package-manager-auto-resources.d.ts.map +1 -1
- package/dist/core/package-manager-auto-resources.js +3 -2
- package/dist/core/package-manager-auto-resources.js.map +1 -1
- package/dist/core/package-manager-git.d.ts +1 -1
- package/dist/core/package-manager-git.d.ts.map +1 -1
- package/dist/core/package-manager-git.js +12 -1
- package/dist/core/package-manager-git.js.map +1 -1
- package/dist/core/package-manager-npm.d.ts +1 -1
- package/dist/core/package-manager-npm.d.ts.map +1 -1
- package/dist/core/package-manager-npm.js +8 -4
- package/dist/core/package-manager-npm.js.map +1 -1
- package/dist/core/package-manager-operations.d.ts.map +1 -1
- package/dist/core/package-manager-operations.js +33 -8
- package/dist/core/package-manager-operations.js.map +1 -1
- package/dist/core/package-manager-resolver.d.ts.map +1 -1
- package/dist/core/package-manager-resolver.js +22 -4
- package/dist/core/package-manager-resolver.js.map +1 -1
- package/dist/core/package-manager-resource-accumulator.d.ts.map +1 -1
- package/dist/core/package-manager-resource-accumulator.js +4 -4
- package/dist/core/package-manager-resource-accumulator.js.map +1 -1
- package/dist/core/package-manager-source.js +5 -5
- package/dist/core/package-manager-source.js.map +1 -1
- package/dist/core/package-manager-types.d.ts +5 -1
- package/dist/core/package-manager-types.d.ts.map +1 -1
- package/dist/core/package-manager-types.js.map +1 -1
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +3 -3
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/project-trust.d.ts.map +1 -1
- package/dist/core/project-trust.js +2 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/prompt-templates-async.d.ts.map +1 -1
- package/dist/core/prompt-templates-async.js +4 -9
- package/dist/core/prompt-templates-async.js.map +1 -1
- package/dist/core/prompt-templates.d.ts.map +1 -1
- package/dist/core/prompt-templates.js +4 -12
- package/dist/core/prompt-templates.js.map +1 -1
- package/dist/core/resource-loader-extensions.d.ts.map +1 -1
- package/dist/core/resource-loader-extensions.js +8 -7
- package/dist/core/resource-loader-extensions.js.map +1 -1
- package/dist/core/resource-loader-paths.js +5 -5
- package/dist/core/resource-loader-paths.js.map +1 -1
- package/dist/core/resource-loader-source-info.d.ts +0 -1
- package/dist/core/resource-loader-source-info.d.ts.map +1 -1
- package/dist/core/resource-loader-source-info.js +6 -17
- package/dist/core/resource-loader-source-info.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager-core.js +2 -2
- package/dist/core/session-manager-core.js.map +1 -1
- package/dist/core/session-manager-list.js +2 -2
- package/dist/core/session-manager-list.js.map +1 -1
- package/dist/core/skills-async.d.ts.map +1 -1
- package/dist/core/skills-async.js +5 -10
- package/dist/core/skills-async.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +5 -13
- package/dist/core/skills.js.map +1 -1
- package/dist/core/source-info.d.ts +2 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +5 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/tool-loadout.d.ts +4 -0
- package/dist/core/tool-loadout.d.ts.map +1 -1
- package/dist/core/tool-loadout.js +7 -1
- package/dist/core/tool-loadout.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +2 -7
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +15 -9
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +33 -8
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -3
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/config-selector-list.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector-list.js +2 -13
- package/dist/modes/interactive/components/config-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-list.js +2 -2
- package/dist/modes/interactive/components/session-selector-list.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-tree.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-tree.js +4 -6
- package/dist/modes/interactive/components/session-selector-tree.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-utils.d.ts +2 -1
- package/dist/modes/interactive/components/session-selector-utils.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-utils.js +5 -13
- package/dist/modes/interactive/components/session-selector-utils.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector-content.js +2 -6
- package/dist/modes/interactive/components/tree-selector-content.js.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.d.ts +2 -0
- package/dist/modes/interactive/interactive-mode-base.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-base.js +4 -0
- package/dist/modes/interactive/interactive-mode-base.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-mode-types.d.ts +6 -0
- package/dist/modes/interactive/interactive-mode-types.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode-types.js.map +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.js +1 -1
- package/dist/modes/interactive/interactive-resource-rendering.js.map +1 -1
- package/dist/modes/interactive/interactive-startup.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-startup.js +15 -8
- package/dist/modes/interactive/interactive-startup.js.map +1 -1
- package/dist/modes/interactive/interactive-tui.d.ts +1 -0
- package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-tui.js +1 -1
- package/dist/modes/interactive/interactive-tui.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +3 -0
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/git.d.ts +1 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/paths.d.ts +14 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +39 -1
- package/dist/utils/paths.js.map +1 -1
- package/docs/extensions/api-reference.md +4 -2
- package/docs/packages.md +2 -0
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,60 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.54] - 2026-10-29
|
|
6
|
+
|
|
7
|
+
Fixes from upstream pi after 1.4.0: packages, Windows paths and start-up.
|
|
8
|
+
|
|
9
|
+
- **Packages that update:** `-e` npm and git packages refresh when a newer version exists, `update` warns when npm leaves the old version in place, and installs through a symlinked agent directory write correct lockfile paths
|
|
10
|
+
- **Windows paths and trust:** paths are compared case-insensitively on Windows, so project trust and settings match however a drive or folder is cased, and a saved "Do not trust" is honored for projects with nothing to trust
|
|
11
|
+
- **Start-up and output:** a deleted working directory gets a clear message instead of a crash, the model scope shows in the fullscreen header instead of staying in the shell, and `pi.exec` caps a command's output instead of buffering it without limit
|
|
12
|
+
- **Models:** OpenRouter's `~anthropic/claude-*-latest` aliases use Anthropic Messages, Zhipu usage-limit errors aren't retried, and SDK branch and session summaries use the stored OAuth login
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- Fixed npm package installs through a symlinked agent directory writing broken nested `package-lock.json` paths: `--prefix` now gets the real path ([#11358](https://github.com/earendil-works/pi/issues/11358)).
|
|
17
|
+
- Fixed model references whose provider id contains a `/`, such as `llama=http://host:10800/unsloth/qwen-gguf:BF16`, failing to resolve ([#11394](https://github.com/earendil-works/pi/issues/11394)).
|
|
18
|
+
- Fixed starting Atomic in a deleted working directory crashing with a stack trace. It now says the directory no longer exists and exits 1 ([#11509](https://github.com/earendil-works/pi/issues/11509)).
|
|
19
|
+
- Fixed the `Model scope:` startup line being printed to the shell's main screen, where it stayed after exit. The fullscreen header shows it instead ([#11508](https://github.com/earendil-works/pi/issues/11508)).
|
|
20
|
+
- Fixed codemode tool descriptions inlining a large union or multi-line output type in every request. They list each variant's fields, or point to `describeTool()` for anything longer ([#11501](https://github.com/earendil-works/pi/issues/11501)).
|
|
21
|
+
- Fixed setting the same active tools in a different order patching the system prompt ([#11495](https://github.com/earendil-works/pi/issues/11495)).
|
|
22
|
+
- Fixed `stripAnsi` leaving terminal mouse reports and similar private-parameter CSI sequences, such as `ESC[<35;59;1M`, in captured output, while keeping the digits after a bare `ESC =` or `ESC >` ([#11377](https://github.com/earendil-works/pi/issues/11377)).
|
|
23
|
+
- Fixed `pi.exec` buffering unbounded output. It now stops a command whose combined stdout and stderr exceed `maxBuffer` (default 256 MiB) and returns the output so far with `truncated: true`, `killed: true` and a nonzero `code` ([#11360](https://github.com/earendil-works/pi/issues/11360)).
|
|
24
|
+
- Fixed branch and session summaries in SDK sessions bypassing the stored OAuth login for providers that also accept an API key ([#11520](https://github.com/earendil-works/pi/issues/11520)).
|
|
25
|
+
- Fixed skill diagnostics being headed `[Skill conflicts]` when they are warnings ([#11566](https://github.com/earendil-works/pi/pull/11566)).
|
|
26
|
+
- Fixed `update` reporting success when npm installed the old version from stale registry metadata. It now warns that the package is still on the old version ([#11571](https://github.com/earendil-works/pi/pull/11571)).
|
|
27
|
+
- Fixed resized images being returned as PNG whenever the PNG fit, even when a JPEG was much smaller. The smaller of the two is now used ([#11551](https://github.com/earendil-works/pi/issues/11551)).
|
|
28
|
+
- Fixed a saved "Do not trust" decision being ignored for a project with no trust inputs ([#10947](https://github.com/earendil-works/pi/issues/10947)).
|
|
29
|
+
- Fixed `-e` packages never updating after the first run. An unpinned npm package is reinstalled when the registry has a newer matching version, and a git package pinned to a branch ref is fetched again, while a ref that is the commit already checked out is not ([#11375](https://github.com/earendil-works/pi/issues/11375)).
|
|
30
|
+
- Fixed path comparisons treating `C:\Users` and `c:\users` as different directories on Windows. Project trust decisions, the user `.agents/skills` directory, session and resource de-duplication, and `~` shortening now ignore case ([#10488](https://github.com/earendil-works/pi/issues/10488)).
|
|
31
|
+
|
|
32
|
+
## [0.9.54-alpha.1] - 2026-10-29
|
|
33
|
+
|
|
34
|
+
Fixes from upstream pi after 1.4.0: packages, Windows paths and start-up.
|
|
35
|
+
|
|
36
|
+
- **Packages that update:** `-e` npm and git packages refresh when a newer version exists, `update` warns when npm leaves the old version in place, and installs through a symlinked agent directory write correct lockfile paths
|
|
37
|
+
- **Windows paths and trust:** paths are compared case-insensitively on Windows, so project trust and settings match however a drive or folder is cased, and a saved "Do not trust" is honored for projects with nothing to trust
|
|
38
|
+
- **Start-up and output:** a deleted working directory gets a clear message instead of a crash, the model scope shows in the fullscreen header instead of staying in the shell, and `pi.exec` caps a command's output instead of buffering it without limit
|
|
39
|
+
- **Models:** OpenRouter's `~anthropic/claude-*-latest` aliases use Anthropic Messages, Zhipu usage-limit errors aren't retried, and SDK branch and session summaries use the stored OAuth login
|
|
40
|
+
|
|
41
|
+
### Fixed
|
|
42
|
+
|
|
43
|
+
- Fixed npm package installs through a symlinked agent directory writing broken nested `package-lock.json` paths: `--prefix` now gets the real path ([#11358](https://github.com/earendil-works/pi/issues/11358)).
|
|
44
|
+
- Fixed model references whose provider id contains a `/`, such as `llama=http://host:10800/unsloth/qwen-gguf:BF16`, failing to resolve ([#11394](https://github.com/earendil-works/pi/issues/11394)).
|
|
45
|
+
- Fixed starting Atomic in a deleted working directory crashing with a stack trace. It now says the directory no longer exists and exits 1 ([#11509](https://github.com/earendil-works/pi/issues/11509)).
|
|
46
|
+
- Fixed the `Model scope:` startup line being printed to the shell's main screen, where it stayed after exit. The fullscreen header shows it instead ([#11508](https://github.com/earendil-works/pi/issues/11508)).
|
|
47
|
+
- Fixed codemode tool descriptions inlining a large union or multi-line output type in every request. They list each variant's fields, or point to `describeTool()` for anything longer ([#11501](https://github.com/earendil-works/pi/issues/11501)).
|
|
48
|
+
- Fixed setting the same active tools in a different order patching the system prompt ([#11495](https://github.com/earendil-works/pi/issues/11495)).
|
|
49
|
+
- Fixed `stripAnsi` leaving terminal mouse reports and similar private-parameter CSI sequences, such as `ESC[<35;59;1M`, in captured output, while keeping the digits after a bare `ESC =` or `ESC >` ([#11377](https://github.com/earendil-works/pi/issues/11377)).
|
|
50
|
+
- Fixed `pi.exec` buffering unbounded output. It now stops a command whose combined stdout and stderr exceed `maxBuffer` (default 256 MiB) and returns the output so far with `truncated: true`, `killed: true` and a nonzero `code` ([#11360](https://github.com/earendil-works/pi/issues/11360)).
|
|
51
|
+
- Fixed branch and session summaries in SDK sessions bypassing the stored OAuth login for providers that also accept an API key ([#11520](https://github.com/earendil-works/pi/issues/11520)).
|
|
52
|
+
- Fixed skill diagnostics being headed `[Skill conflicts]` when they are warnings ([#11566](https://github.com/earendil-works/pi/pull/11566)).
|
|
53
|
+
- Fixed `update` reporting success when npm installed the old version from stale registry metadata. It now warns that the package is still on the old version ([#11571](https://github.com/earendil-works/pi/pull/11571)).
|
|
54
|
+
- Fixed resized images being returned as PNG whenever the PNG fit, even when a JPEG was much smaller. The smaller of the two is now used ([#11551](https://github.com/earendil-works/pi/issues/11551)).
|
|
55
|
+
- Fixed a saved "Do not trust" decision being ignored for a project with no trust inputs ([#10947](https://github.com/earendil-works/pi/issues/10947)).
|
|
56
|
+
- Fixed `-e` packages never updating after the first run. An unpinned npm package is reinstalled when the registry has a newer matching version, and a git package pinned to a branch ref is fetched again, while a ref that is the commit already checked out is not ([#11375](https://github.com/earendil-works/pi/issues/11375)).
|
|
57
|
+
- Fixed path comparisons treating `C:\Users` and `c:\users` as different directories on Windows. Project trust decisions, the user `.agents/skills` directory, session and resource de-duplication, and `~` shortening now ignore case ([#10488](https://github.com/earendil-works/pi/issues/10488)).
|
|
58
|
+
|
|
5
59
|
## [0.9.53] - 2026-10-29
|
|
6
60
|
|
|
7
61
|
Task pages show their own status lines, and a dependency security fix.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/intercom",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.54-alpha.1",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension providing a private coordination channel between parent and child agent sessions. Fork of: https://github.com/nicobailon/pi-intercom",
|
|
6
6
|
"contributors": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/subagents",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.54-alpha.1",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension for delegating tasks to subagents with parallel execution. Fork of: https://github.com/nicobailon/pi-subagents",
|
|
6
6
|
"contributors": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/web-access",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.54-alpha.1",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension for web search, URL fetching, GitHub repo cloning, PDF/video extraction. Fork of: https://github.com/nicobailon/pi-web-access",
|
|
6
6
|
"contributors": [
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AAExH,OAAO,EACN,KAAK,iBAAiB,EAKtB,MAAM,uBAAuB,CAAC;AAI/B;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,IAAI,CAAC;AAElD,eAAO,MAAM,6CAA6C,IAAI,CAAC;AAS/D,6EAA6E;AAC7E,wBAAgB,8BAA8B,IAAI;IACjD,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,EAAE,MAAM,IAAI,CAAC;CACpB,CAMA;AAOD,wBAAsB,gBAAgB,CACrC,IAAI,EAAE,YAAY,EAClB,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,UAAO,GACrB,OAAO,CAAC,IAAI,CAAC,CA2Of;AAED,wBAAgB,uBAAuB,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAEnF;AAED,wBAAgB,wBAAwB,CAAC,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAE9G;AAqDD,wBAAgB,8BAA8B,CAAC,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ1F;AAED,wBAAgB,mCAAmC,CAClD,gBAAgB,EAAE,gBAAgB,EAClC,gBAAgB,EAAE,MAAM,EACxB,oBAAoB,EAAE,OAAO,GAC3B,OAAO,CAKT;AAED;;GAEG;AAEH,wBAAsB,kDAAkD,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1G;AAED;;;;;GAKG;AAEH,wBAAgB,4CAA4C,CAC3D,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,UAAU,GAAG,WAAW,EACjC,SAAS,EAAE,OAAO,GAChB,IAAI,CA4DN;AAED,wBAAsB,uCAAuC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAM/F;AAED;;GAEG;AAEH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAWlF;AAED;;;;GAIG;AAEH,wBAAgB,4BAA4B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQrE;AAYD,wBAAgB,kCAAkC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAE9E;AAED,wBAAsB,kBAAkB,CACvC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,EAClB,OAAO,GAAE,iBAA0E,GACjF,OAAO,CAAC,wBAAwB,CAAC,CA2InC;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;;CAQ7C,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { isContextOverflow, isRecoverableLength } from "@bastani/pi-ai/compat";
|
|
2
2
|
import { emitSessionCompactFailed } from "./agent-session-compaction.js";
|
|
3
|
+
import { authForStream } from "./agent-session-models.js";
|
|
3
4
|
import { calculateContextTokens, estimateContextTokens, estimateProjectedContextTokens, shouldCompact, } from "./compaction/index.js";
|
|
4
5
|
import { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from "./openai-responses-payload-sanitizer.js";
|
|
5
6
|
import { getLatestCompactionBoundaryEntry } from "./session-manager.js";
|
|
@@ -494,7 +495,7 @@ export async function _runAutoCompaction(reason, willRetry, urgency = reason ===
|
|
|
494
495
|
const result = await this._applyVerbatimCompaction({
|
|
495
496
|
resolvePlannerAuth: async (candidate) => {
|
|
496
497
|
const authResult = await this._getRequiredRequestAuth(candidate, controller.signal);
|
|
497
|
-
return authResult.apiKey || authResult.headers ? authResult : undefined;
|
|
498
|
+
return authResult.apiKey || authResult.headers ? authForStream(this, authResult) : undefined;
|
|
498
499
|
},
|
|
499
500
|
abortController: controller,
|
|
500
501
|
backupLabel: urgency === "load_bearing" ? "overflow-auto-compact" : "auto-compact",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,8BAA8B,EAC9B,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAyB,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAE/F;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAErC,gBAAkC,EAClC,gBAAgB,GAAG,IAAI;IAEvB,IAAI,IAAI,CAAC,uBAAuB;QAAE,OAAO;IACzC,IAAI,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC1C,MAAM,EAAE,MAAM,EAAE,GA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AAO,qBAAqB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,IAAI,IAAI,CAAC,8BAA8B,KAAK,UAAU;YAAE,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QACxG,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t: \"Response truncation recovery stopped after one retry.\";\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\";\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport async function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): Promise<void> {\n\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tawait this._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authResult : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-auto-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-auto-compaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAEN,sBAAsB,EACtB,qBAAqB,EACrB,8BAA8B,EAC9B,aAAa,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,yCAAyC,CAAC;AAC1F,OAAO,EAAyB,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAE/F;;;;GAIG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC;AAElD,MAAM,CAAC,MAAM,6CAA6C,GAAG,CAAC,CAAC;AAS/D,6EAA6E;AAC7E,MAAM,UAAU,8BAA8B;IAI7C,IAAI,OAAoB,CAAC;IACzB,MAAM,OAAO,GAAG,IAAI,OAAO,CAAO,CAAC,IAAI,EAAE,EAAE;QAC1C,OAAO,GAAG,IAAI,CAAC;IAChB,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAC7B,CAAC;AAED,MAAM,+BAA+B,GAAG,uBAAuB,CAAC;AAChE,MAAM,+BAA+B,GAAG,IAAI,MAAM,CACjD,gFAAgF,+BAA+B,uBAAuB,CACtI,CAAC;AAEF,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAErC,gBAAkC,EAClC,gBAAgB,GAAG,IAAI;IAEvB,IAAI,IAAI,CAAC,uBAAuB;QAAE,OAAO;IACzC,IAAI,IAAI,CAAC,+BAA+B,EAAE,CAAC;QAC1C,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,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ACb,CAAC,CAAC;QACH,OAAO,qBAAqB,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;IACtD,CAAC;YAAS,CAAC;QACV,IAAI,IAAI,CAAC,8BAA8B,KAAK,UAAU;YAAE,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;QACxG,IAAI,IAAI,CAAC,iBAAiB,KAAK,MAAM;YAAE,IAAI,CAAC,iBAAiB,GAAG,SAAS,CAAC;QAC1E,UAAU,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,IAAI,CAAC,yBAAyB,KAAK,UAAU,CAAC,OAAO;YAAE,IAAI,CAAC,yBAAyB,GAAG,SAAS,CAAC;IACvG,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,uCAAuC;IACvC,gBAAgB;IAChB,kDAAkD;IAClD,4CAA4C;IAC5C,0BAA0B;IAC1B,4BAA4B;IAC5B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@bastani/pi-ai/compat\";\nimport { isContextOverflow, isRecoverableLength } from \"@bastani/pi-ai/compat\";\nimport { emitSessionCompactFailed } from \"./agent-session-compaction.ts\";\nimport type { AgentSessionInternalSurface as AgentSession, AutoCompactionRunOutcome } from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport {\n\ttype CompactionUrgency,\n\tcalculateContextTokens,\n\testimateContextTokens,\n\testimateProjectedContextTokens,\n\tshouldCompact,\n} from \"./compaction/index.ts\";\nimport { MIN_RESPONSES_MAX_OUTPUT_TOKENS } from \"./openai-responses-payload-sanitizer.ts\";\nimport { type ContextEditEntry, getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\n\n/**\n * Upper bound on direct continuations after a response reaches its requested\n * output cap. Context-limited truncations use one compact-and-retry attempt\n * instead; this bound preserves Atomic's separate output-cap continuation.\n */\nexport const MAX_LENGTH_CONTINUATION_ATTEMPTS = 3;\n\nexport const MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS = 1;\n\ntype JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\ntype ProviderErrorDetails = {\n\tmessage?: string;\n\tcode?: string;\n\tparam?: string;\n};\n\n/** Create the settlement boundary for a regular automatic compaction run. */\nexport function createAutoCompactionCompletion(): {\n\tpromise: Promise<void>;\n\tresolve: () => void;\n} {\n\tlet resolve!: () => void;\n\tconst promise = new Promise<void>((done) => {\n\t\tresolve = done;\n\t});\n\treturn { promise, resolve };\n}\n\nconst OUTPUT_BUDGET_PARAMETER_PATTERN = /\\bmax_output_tokens\\b/;\nconst OUTPUT_BUDGET_UNDERFLOW_PATTERN = new RegExp(\n\t`(?:integer\\\\s+below\\\\s+minimum\\\\s+value|expected\\\\s+(?:a\\\\s+)?value\\\\s*>=\\\\s*${MIN_RESPONSES_MAX_OUTPUT_TOKENS}|got\\\\s+1\\\\s+instead)`,\n);\n\nexport async function _checkCompaction(\n\tthis: AgentSession,\n\tassistantMessage: AssistantMessage,\n\tskipAbortedCheck = true,\n): Promise<void> {\n\tif (this._agentRunAbortRequested) return;\n\tif (this._pendingPostToolCompactionGuard) {\n\t\tconst { result } = this._pendingPostToolCompactionGuard;\n\t\tthis._pendingPostToolCompactionGuard = undefined;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason: \"threshold\",\n\t\t\tresult,\n\t\t\taborted: true,\n\t\t\twillRetry: false,\n\t\t\tmidTurn: true,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t}\n\tif (\n\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\tassistantMessage.errorMessage === this._postToolCompactionPreflightError\n\t) {\n\t\tthis._postToolCompactionPreflightError = undefined;\n\t\treturn;\n\t}\n\t// The agent_end path passes skipAbortedCheck=true; the pre-prompt path passes\n\t// false. Only the live turn-completion path may auto-continue a truncated\n\t// response — before a fresh user prompt we must not resume the old turn.\n\tconst isLiveTurnCompletion = skipAbortedCheck;\n\tconst settings = this.settingsManager.getCompactionSettings(this.model);\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\t// Skip overflow handling if the message came from a different model.\n\t// This handles the case where user switched from a smaller-context model (e.g. opus)\n\t// to a larger-context model (e.g. codex) - the overflow error from the old model\n\t// shouldn't trigger compaction for the new model.\n\tconst sameModel =\n\t\tthis.model !== undefined &&\n\t\tassistantMessage.provider === this.model.provider &&\n\t\tassistantMessage.model === this.model.id;\n\t// Usage and overflow signals belong to the request that produced this assistant.\n\t// A later context edit or compaction changes what the next request contains, so\n\t// only a projected, unedited assistant may drive usage-based decisions; an explicit\n\t// provider overflow error still recovers while its attempt is retained.\n\t// Guarded because fallback suites drive this function on a synthetic session.\n\tconst projectionAware =\n\t\ttypeof this.sessionManager?.buildSessionProjection === \"function\" &&\n\t\ttypeof this._findPersistedMessageEntryId === \"function\";\n\tconst currentProjection = projectionAware ? this.sessionManager.buildSessionProjection() : undefined;\n\tconst branch = projectionAware ? this.sessionManager.getBranch() : [];\n\tconst assistantEntryId = projectionAware ? this._findPersistedMessageEntryId(assistantMessage) : undefined;\n\tconst assistantIsProjected =\n\t\tassistantEntryId === undefined ||\n\t\tcurrentProjection?.entries.some(\n\t\t\t(entry) =>\n\t\t\t\tentry.sourceEntry.id === assistantEntryId && entry.messages.some((message) => message.role === \"assistant\"),\n\t\t) === true;\n\tconst assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;\n\tconst entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];\n\tconst hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === \"context_edit\");\n\tconst latestAssistantEdit = entriesAfterAssistant\n\t\t.filter(\n\t\t\t(entry): entry is ContextEditEntry => entry.type === \"context_edit\" && entry.targetId === assistantEntryId,\n\t\t)\n\t\t.at(-1);\n\tconst assistantRetainedForExplicitRecovery =\n\t\tassistantEntryId === undefined ||\n\t\t(!entriesAfterAssistant.some((entry) => entry.type === \"compaction\") &&\n\t\t\tlatestAssistantEdit?.replacement !== null);\n\tconst assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;\n\tconst explicitOverflow = assistantMessage.stopReason === \"error\" && isContextOverflow(assistantMessage);\n\tconst contextOverflow =\n\t\tsameModel &&\n\t\t((explicitOverflow && assistantRetainedForExplicitRecovery) ||\n\t\t\t(assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));\n\tif (!settings.enabled) {\n\t\t// Compaction cannot recover this turn, so a configured fallback chain may\n\t\t// advance to a larger-context candidate instead of dead-ending.\n\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\treturn;\n\t}\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\t// Skip compaction checks if this assistant message is older than the latest\n\t// compaction boundary. This prevents a stale pre-compaction usage/error\n\t// from retriggering compaction on the first prompt after compaction.\n\tconst compactionBoundaryEntry = getLatestCompactionBoundaryEntry(this.sessionManager.getBranch());\n\tconst assistantIsFromBeforeCompactionBoundary =\n\t\tcompactionBoundaryEntry !== null &&\n\t\tassistantMessage.timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime();\n\tif (assistantIsFromBeforeCompactionBoundary) {\n\t\treturn;\n\t}\n\n\t// Case 1: Recoverable failure. Explicit/silent context overflow still uses\n\t// context metadata. A length stop below the model's original requested output\n\t// cap instead receives one compact-and-retry independent of context metadata.\n\t// This recovers a chat response; `truncated-range-recovery` separately parses\n\t// deletion records from a compaction planner response and is not involved here.\n\tconst desiredMaxOutput = this.model?.maxTokens ?? 0;\n\tconst recoverableLength =\n\t\tisLiveTurnCompletion &&\n\t\tsameModel &&\n\t\tassistantIsProjected &&\n\t\tisRecoverableLength(assistantMessage, desiredMaxOutput);\n\tif (contextOverflow || recoverableLength) {\n\t\tconst willRetry = assistantMessage.stopReason !== \"stop\";\n\t\tif (!willRetry) {\n\t\t\tawait this._runAutoCompaction(\"overflow\", false);\n\t\t\treturn;\n\t\t}\n\n\t\tconst recoveryAttempted = contextOverflow\n\t\t\t? this._overflowRecoveryAttempted\n\t\t\t: this._recoverableLengthRecoveryAttempted;\n\t\tif (recoveryAttempted) {\n\t\t\t// One recovery of this kind has already been spent on this turn. A real\n\t\t\t// context overflow may now advance to a larger-context fallback; a\n\t\t\t// recoverable output truncation stops without claiming overflow.\n\t\t\tif (contextOverflow) this._contextOverflowUnresolved = true;\n\t\t\tconst errorMessage = contextOverflow\n\t\t\t\t? \"Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.\"\n\t\t\t\t: \"Response truncation recovery stopped after one retry.\";\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason: \"overflow\",\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\t...(contextOverflow ? { unresolvedOverflow: true } : {}),\n\t\t\t\terrorMessage,\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason: \"overflow\",\n\t\t\t\terrorMessage,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = true;\n\t\telse this._recoverableLengthRecoveryAttempted = true;\n\t\tlet outcome: AutoCompactionRunOutcome;\n\t\ttry {\n\t\t\toutcome = contextOverflow\n\t\t\t\t? await this._runAutoCompaction(\"overflow\", willRetry)\n\t\t\t\t: await this._runAutoCompaction(\"overflow\", willRetry, \"recoverable\");\n\t\t} catch (error) {\n\t\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\t\tthrow error;\n\t\t}\n\t\tif (outcome === \"compacted\" || outcome === \"failed\") return;\n\t\t// No boundary means there is no context to free. Keep this recovery\n\t\t// attempt spent while its one direct continuation is pending, so another\n\t\t// below-cap stop cannot start a new compaction cycle.\n\t\tif (\n\t\t\trecoverableLength &&\n\t\t\toutcome === \"not_compactable\" &&\n\t\t\tthis._compactionAbortController === undefined &&\n\t\t\tthis._manualCompactionPromise === undefined\n\t\t) {\n\t\t\tthis._resumeAfterLengthTruncation();\n\t\t\treturn;\n\t\t}\n\t\tif (contextOverflow) this._overflowRecoveryAttempted = false;\n\t\telse this._recoverableLengthRecoveryAttempted = false;\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For errors or all-zero provider usage, estimate from message content.\n\tlet contextTokens = calculateContextTokens(assistantMessage.usage, assistantMessage.api);\n\tconst hasContextEdits =\n\t\tcurrentProjection?.entries.some((entry) => entry.sourceEntry.type === \"context_edit\") === true;\n\tif (currentProjection && hasContextEdits) {\n\t\t// Edited context invalidates usage captured before the edit; estimate the projection.\n\t\tcontextTokens = estimateProjectedContextTokens(currentProjection, branch).tokens;\n\t} else if (assistantMessage.stopReason === \"error\" || contextTokens === 0) {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\t// Without provider usage, estimate.tokens is the pure message-size estimate.\n\t\t// Only usage-backed estimates need the stale pre-compaction check.\n\t\tif (estimate.lastUsageIndex !== null) {\n\t\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\t\tif (\n\t\t\t\tcompactionBoundaryEntry &&\n\t\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t\t) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t}\n\tif (shouldCompact(contextTokens, contextWindow, settings)) {\n\t\tconst willRetry = shouldRetryAfterThresholdCompaction(assistantMessage, desiredMaxOutput, isLiveTurnCompletion);\n\t\tif (willRetry && isRetryWorthyOutputBudgetError(assistantMessage)) {\n\t\t\tif (this._outputBudgetErrorContinuationAttempts >= MAX_OUTPUT_BUDGET_ERROR_CONTINUATION_ATTEMPTS) {\n\t\t\t\tconst errorMessage =\n\t\t\t\t\t\"Output-budget recovery stopped after a compact-and-retry attempt. Try reducing context or switching to a larger-context model.\";\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"compaction_end\",\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\tresult: undefined,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\t\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\t\treason: \"threshold\",\n\t\t\t\t\terrorMessage,\n\t\t\t\t\taborted: false,\n\t\t\t\t\twillRetry: false,\n\t\t\t\t\tfromExtension: false,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis._outputBudgetErrorContinuationAttempts += 1;\n\t\t}\n\t\tawait this._runAutoCompaction(\"threshold\", willRetry);\n\t\treturn;\n\t}\n\n\t// A length stop that reached its requested output cap is not the\n\t// context-limited truncation recovered above. Preserve Atomic's bounded\n\t// direct-continuation policy for that distinct case.\n\tif (\n\t\tisLiveTurnCompletion &&\n\t\tisOutputCappedLengthStop(assistantMessage, desiredMaxOutput) &&\n\t\tthis._compactionAbortController === undefined &&\n\t\tthis._manualCompactionPromise === undefined\n\t) {\n\t\tthis._resumeAfterLengthTruncation();\n\t}\n}\n\nexport function isRetryWorthyLengthStop(assistantMessage: AssistantMessage): boolean {\n\treturn assistantMessage.stopReason === \"length\" && assistantMessage.usage.output > 0;\n}\n\nexport function isOutputCappedLengthStop(assistantMessage: AssistantMessage, desiredMaxOutput: number): boolean {\n\treturn isRetryWorthyLengthStop(assistantMessage) && !isRecoverableLength(assistantMessage, desiredMaxOutput);\n}\n\nfunction isJsonRecord(value: JsonValue): value is { [key: string]: JsonValue } {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringField(record: { [key: string]: JsonValue }, key: string): string | undefined {\n\tconst value = record[key];\n\treturn typeof value === \"string\" ? value : undefined;\n}\n\nfunction parseProviderErrorDetails(errorMessage: string): ProviderErrorDetails | undefined {\n\tconst start = errorMessage.indexOf(\"{\");\n\tconst end = errorMessage.lastIndexOf(\"}\");\n\tif (start === -1 || end <= start) return undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(errorMessage.slice(start, end + 1)) as JsonValue;\n\t\tif (!isJsonRecord(parsed)) return undefined;\n\n\t\tconst nestedError = parsed.error;\n\t\tif (nestedError !== undefined && isJsonRecord(nestedError)) {\n\t\t\treturn {\n\t\t\t\tmessage: stringField(nestedError, \"message\"),\n\t\t\t\tcode: stringField(nestedError, \"code\") ?? stringField(parsed, \"code\"),\n\t\t\t\tparam: stringField(nestedError, \"param\") ?? stringField(parsed, \"param\"),\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tmessage: stringField(parsed, \"message\"),\n\t\t\tcode: stringField(parsed, \"code\"),\n\t\t\tparam: stringField(parsed, \"param\"),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isOutputBudgetUnderflowText(text: string): boolean {\n\tconst message = text.toLowerCase();\n\treturn OUTPUT_BUDGET_PARAMETER_PATTERN.test(message) && OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message);\n}\n\nfunction isStructuredOutputBudgetUnderflow(details: ProviderErrorDetails): boolean {\n\tconst message = details.message?.toLowerCase() ?? \"\";\n\tconst param = details.param?.toLowerCase();\n\tif (!OUTPUT_BUDGET_UNDERFLOW_PATTERN.test(message)) return false;\n\treturn param !== undefined\n\t\t? OUTPUT_BUDGET_PARAMETER_PATTERN.test(param)\n\t\t: OUTPUT_BUDGET_PARAMETER_PATTERN.test(message);\n}\n\nexport function isRetryWorthyOutputBudgetError(assistantMessage: AssistantMessage): boolean {\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return false;\n\tif (assistantMessage.api !== \"openai-responses\") return false;\n\n\tconst structuredDetails = parseProviderErrorDetails(assistantMessage.errorMessage);\n\tif (structuredDetails && isStructuredOutputBudgetUnderflow(structuredDetails)) return true;\n\n\treturn isOutputBudgetUnderflowText(assistantMessage.errorMessage);\n}\n\nexport function shouldRetryAfterThresholdCompaction(\n\tassistantMessage: AssistantMessage,\n\tdesiredMaxOutput: number,\n\tisLiveTurnCompletion: boolean,\n): boolean {\n\treturn (\n\t\tisRetryWorthyOutputBudgetError(assistantMessage) ||\n\t\t(isLiveTurnCompletion && isOutputCappedLengthStop(assistantMessage, desiredMaxOutput))\n\t);\n}\n\n/**\n * Internal: remove an incomplete assistant from retry context before auto-continuing after compaction.\n */\n\nexport async function _dropTrailingAutoCompactionRetryAssistantIfPresent(this: AgentSession): Promise<void> {\n\t// The attempt stays in raw session history; a durable context edit omits it from\n\t// the model projection so the continuation resumes from the preceding input.\n\tawait this._omitTrailingAssistantAttempt(\n\t\t(assistant) => assistant.stopReason === \"error\" || assistant.stopReason === \"length\",\n\t);\n}\n\n/**\n * Internal: schedule a live post-event continuation after compaction_end listeners can flush queues.\n * The grace period preserves listener ordering. Queue-only probes wait for transient work to become\n * idle, while retry probes remain tied to the turn that scheduled them and are abandoned if another\n * turn owns the agent when the grace period ends.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(\n\tthis: AgentSession,\n\t_reason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tif (this._agentRunAbortRequested) return;\n\tconst token = this._postCompactionContinuationToken + 1;\n\tthis._postCompactionContinuationToken = token;\n\tconst fallbackScopeGeneration = this._fallbackOriginGeneration;\n\tlet pending: Promise<void>;\n\tpending = new Promise<void>((resolve) => {\n\t\tsetTimeout(() => {\n\t\t\tvoid (async () => {\n\t\t\t\tconst settleIfOwned = async (): Promise<void> => {\n\t\t\t\t\tif (\n\t\t\t\t\t\tfallbackScopeGeneration === undefined ||\n\t\t\t\t\t\tthis._fallbackOriginGeneration !== fallbackScopeGeneration ||\n\t\t\t\t\t\ttypeof this._settleFallbackModelScope !== \"function\"\n\t\t\t\t\t)\n\t\t\t\t\t\treturn;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait this._settleFallbackModelScope();\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// A listener must not strand the continuation waiter. The fallback\n\t\t\t\t\t\t// state was already settled before lifecycle notifications ran.\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\ttry {\n\t\t\t\t\tif (this._agentRunAbortRequested) return;\n\t\t\t\t\tif (willRetry) {\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tawait this.agent.waitForIdle();\n\t\t\t\t\t\tif (this._postCompactionContinuationToken !== token) return;\n\t\t\t\t\t\tif (this.isCompacting || this.isStreaming) return;\n\t\t\t\t\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// A queued message starts the next user turn. Settle before Agent\n\t\t\t\t\t\t// snapshots the next request's model.\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\n\t\t\t\t\tif (this._pendingPostCompactionContinuation !== pending) return;\n\t\t\t\t\t// Clear this probe before entering the next run. Its promise is\n\t\t\t\t\t// still awaited by _awaitPendingPostCompactionContinuation, but\n\t\t\t\t\t// the nested agent_end must be free to schedule a new probe.\n\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\tawait this._resumeAfterAutoCompaction();\n\t\t\t\t\tif (willRetry && this._pendingPostCompactionContinuation === undefined) {\n\t\t\t\t\t\tawait settleIfOwned();\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tif (this._pendingPostCompactionContinuation === pending) {\n\t\t\t\t\t\tthis._pendingPostCompactionContinuation = undefined;\n\t\t\t\t\t}\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})();\n\t\t}, 100);\n\t});\n\tthis._pendingPostCompactionContinuation = pending;\n}\n\nexport async function _awaitPendingPostCompactionContinuation(this: AgentSession): Promise<void> {\n\t// A continuation can schedule another probe (for example a second output-cap\n\t// stop). Keep the owning prompt alive until the whole automatic chain drains.\n\twhile (this._pendingPostCompactionContinuation !== undefined) {\n\t\tawait this._pendingPostCompactionContinuation;\n\t}\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport async function _resumeAfterAutoCompaction(this: AgentSession): Promise<void> {\n\ttry {\n\t\tawait this._runAgentContinue();\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tthis._emit({\n\t\t\ttype: \"agent_continue_error\",\n\t\t\tsource: \"post_compaction\",\n\t\t\terrorMessage: `Post-compaction continuation failed: ${message}`,\n\t\t});\n\t}\n}\n\n/**\n * Internal: resume a response that reached its requested output cap when the\n * context does not warrant compaction. Bounded so a model that repeatedly\n * stops at that cap can still terminate.\n */\n\nexport function _resumeAfterLengthTruncation(this: AgentSession): void {\n\tif (this._lengthContinuationAttempts >= MAX_LENGTH_CONTINUATION_ATTEMPTS) return;\n\tthis._lengthContinuationAttempts += 1;\n\t// agent.continue() rejects an assistant tail; drop the incomplete\n\t// length-stopped message so the preceding user/tool-result anchors the\n\t// continuation. It remains persisted in session history.\n\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\tthis._schedulePostAutoCompactionContinuationProbe(\"threshold\", true);\n}\n\n/**\n * Whether an overflow turn is now unrecoverable by compaction, recording it on\n * the session so a configured fallback chain may advance to another candidate.\n */\nfunction overflowUnresolved(this: AgentSession, loadBearing: boolean, aborted = false): boolean | undefined {\n\tif (!loadBearing || aborted) return undefined;\n\tthis._contextOverflowUnresolved = true;\n\treturn true;\n}\n\nexport function hasPendingManualCompactionTakeover(this: AgentSession): boolean {\n\treturn this._compactionReason === \"manual\" && this._compactionAbortController !== undefined;\n}\n\nexport async function _runAutoCompaction(\n\tthis: AgentSession,\n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n\turgency: CompactionUrgency = reason === \"overflow\" ? \"load_bearing\" : \"recoverable\",\n): Promise<AutoCompactionRunOutcome> {\n\tif (\n\t\tthis._compactionAbortController !== undefined ||\n\t\tthis._manualCompactionPromise !== undefined ||\n\t\tthis._autoCompactionAbortController !== undefined\n\t)\n\t\treturn \"deferred\";\n\n\tconst controller = new AbortController();\n\tconst completion = createAutoCompactionCompletion();\n\tthis._autoCompactionAbortController = controller;\n\tthis._autoCompactionCompletion = completion.promise;\n\tthis._compactionReason = reason;\n\tlet fromExtension = false;\n\ttry {\n\t\tthis._emit({ type: \"compaction_start\", reason });\n\t} catch (error) {\n\t\t// A throwing start listener still propagates, matching current behavior,\n\t\t// but must not leave ownership published with no owner running.\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t\tthrow error;\n\t}\n\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension: false,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t\t}\n\n\t\t// Resolve auth only after extension hooks have had an opportunity to cancel\n\t\t// compaction or provide compacted text, so local extension compaction does not\n\t\t// require provider credentials. Missing auth then fails model-driven compaction\n\t\t// before persistence or continuation, matching other provider-call failures.\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async (candidate) => {\n\t\t\t\tconst authResult = await this._getRequiredRequestAuth(candidate, controller.signal);\n\t\t\t\treturn authResult.apiKey || authResult.headers ? authForStream(this, authResult) : undefined;\n\t\t\t},\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: urgency === \"load_bearing\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t\turgency,\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t\t// Only an actual context overflow proved the context cannot fit. A\n\t\t\t// recoverable length stop must never reach the fresh-context fallback.\n\t\t\t...(urgency === \"load_bearing\" ? { allowSmallRegion: true } : {}),\n\t\t});\n\t\tif (!result) {\n\t\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\t\tthis._emit({\n\t\t\t\ttype: \"compaction_end\",\n\t\t\t\treason,\n\t\t\t\tresult: undefined,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\"),\n\t\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\t});\n\t\t\tawait emitSessionCompactFailed(this, {\n\t\t\t\treason,\n\t\t\t\taborted: false,\n\t\t\t\twillRetry: false,\n\t\t\t\tfromExtension,\n\t\t\t});\n\t\t\treturn manualTakeoverPending ? \"deferred\" : \"not_compactable\";\n\t\t}\n\n\t\tif (willRetry) {\n\t\t\tthis._dropTrailingAutoCompactionRetryAssistantIfPresent();\n\t\t}\n\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult,\n\t\t\taborted: false,\n\t\t\twillRetry,\n\t\t\t...(hasPendingManualCompactionTakeover.call(this) ? { manualTakeoverPending: true } : {}),\n\t\t});\n\t\tif (!hasPendingManualCompactionTakeover.call(this)) {\n\t\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t\t}\n\t\treturn \"compacted\";\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = controller.signal.aborted;\n\t\tconst manualTakeoverPending = hasPendingManualCompactionTakeover.call(this);\n\t\tconst formattedErrorMessage = aborted\n\t\t\t? undefined\n\t\t\t: reason === \"overflow\"\n\t\t\t\t? urgency === \"recoverable\"\n\t\t\t\t\t? `Response truncation recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t: `Auto-compaction failed: ${errorMessage}`;\n\t\tthis._emit({\n\t\t\ttype: \"compaction_end\",\n\t\t\treason,\n\t\t\tresult: undefined,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tunresolvedOverflow: overflowUnresolved.call(this, urgency === \"load_bearing\", aborted),\n\t\t\t...(manualTakeoverPending ? { manualTakeoverPending: true } : {}),\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t});\n\t\tawait emitSessionCompactFailed(this, {\n\t\t\treason,\n\t\t\terrorMessage: formattedErrorMessage,\n\t\t\taborted,\n\t\t\twillRetry: false,\n\t\t\tfromExtension,\n\t\t});\n\t\treturn manualTakeoverPending ? \"deferred\" : \"failed\";\n\t} finally {\n\t\tif (this._autoCompactionAbortController === controller) this._autoCompactionAbortController = undefined;\n\t\tif (this._compactionReason === reason) this._compactionReason = undefined;\n\t\tcompletion.resolve();\n\t\tif (this._autoCompactionCompletion === completion.promise) this._autoCompactionCompletion = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_awaitPendingPostCompactionContinuation,\n\t_checkCompaction,\n\t_dropTrailingAutoCompactionRetryAssistantIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_resumeAfterLengthTruncation,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,qBAAqB,EACrB,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-compaction.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,2BAA2B,IAAI,YAAY,EAC3C,qBAAqB,EACrB,8BAA8B,EAC9B,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAYN,KAAK,wBAAwB,EAG7B,MAAM,uBAAuB,CAAC;AAE/B,OAAO,KAAK,EAIX,yBAAyB,EACzB,MAAM,uBAAuB,CAAC;AA4D/B,wBAAsB,wBAAwB,CAC7C,IAAI,EAAE,YAAY,EAClB,OAAO,EAAE,8BAA8B,GACrC,OAAO,CAAC,wBAAwB,GAAG,SAAS,CAAC,CAyM/C;AAED,wBAAsB,wBAAwB,CAC7C,OAAO,EAAE,YAAY,EACrB,KAAK,EAAE,IAAI,CAAC,yBAAyB,EAAE,MAAM,CAAC,GAC5C,OAAO,CAAC,IAAI,CAAC,CAIf;AA+ED;;;;;;;GAOG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAuDlH;AAED,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAGxD;AACD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAE3D;AACD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAEnF;AAED,eAAO,MAAM,6BAA6B;;;;;;CAMzC,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { authForStream } from "./agent-session-models.js";
|
|
1
2
|
import { formatNoModelSelectedMessage } from "./auth-guidance.js";
|
|
2
3
|
import { getKeptTailTokenEstimate, prepareCompactionBoundary, runVerbatimCompaction, VERBATIM_COMPACTION_PROMPT_VERSION, VERBATIM_COMPACTION_STRATEGY, widenToWholeContextStats, } from "./compaction/index.js";
|
|
3
4
|
import { resolveCompactionModel } from "./compaction/model-resolver.js";
|
|
@@ -276,7 +277,7 @@ async function runOwnedManualCompaction(controller, options) {
|
|
|
276
277
|
...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),
|
|
277
278
|
...(options.query === undefined ? {} : { query: options.query }),
|
|
278
279
|
...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),
|
|
279
|
-
resolvePlannerAuth: (candidate) => this._getRequiredRequestAuth(candidate, controller.signal),
|
|
280
|
+
resolvePlannerAuth: async (candidate) => authForStream(this, await this._getRequiredRequestAuth(candidate, controller.signal)),
|
|
280
281
|
abortController: controller,
|
|
281
282
|
backupLabel: "compact",
|
|
282
283
|
reason: "manual",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,EAK5B,wBAAwB,GACxB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAOxE,OAAO,EAAE,iBAAiB,IAAI,oBAAoB,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAE1G,OAAO,EAA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AAC,CAAC,CAAC;IACH,IAAI,CAAC,wBAAwB,GAAG,MAAM,CAAC;IACvC,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,eAAe;IAC9B,IAAI,CAAC,0BAA0B,EAAE,KAAK,EAAE,CAAC;IACzC,IAAI,CAAC,8BAA8B,EAAE,KAAK,EAAE,CAAC;AAC9C,CAAC;AACD,MAAM,UAAU,kBAAkB;IACjC,IAAI,CAAC,6BAA6B,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,kBAAkB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;AACxF,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type { Usage } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgentSessionInternalSurface as AgentSession,\n\tSessionCompactOptions,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport {\n\ttype CompactionPlannerModel,\n\ttype CompactionPlanOptions,\n\ttype CompactionRung,\n\ttype FallbackPlannerContext,\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n\twidenToWholeContextStats,\n} from \"./compaction/index.ts\";\nimport { resolveCompactionModel } from \"./compaction/model-resolver.js\";\nimport type {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\nimport { assertSessionOpen as assertCompactionOpen, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport type { CompactionEntry } from \"./session-manager.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nfunction frozenCollectionMutation(): never {\n\tthrow new TypeError(\"Cannot mutate frozen compaction preparation\");\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tif (value instanceof Map) {\n\t\tfor (const [key, nested] of value) {\n\t\t\tdeepFreeze(key);\n\t\t\tdeepFreeze(nested);\n\t\t}\n\t\tObject.defineProperties(value, {\n\t\t\tset: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else if (value instanceof Set) {\n\t\tfor (const nested of value) deepFreeze(nested);\n\t\tObject.defineProperties(value, {\n\t\t\tadd: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else {\n\t\tfor (const nested of Object.values(value)) deepFreeze(nested);\n\t}\n\treturn Object.freeze(value);\n}\n\nfunction extensionStats(preparation: VerbatimCompactionPreparation, compactedText: string): VerbatimCompactionStats {\n\tconst linesBefore = preparation.region.lines.length;\n\tconst linesKept = compactedText.split(\"\\n\").length;\n\t// Region-only view first — what the extension's replacement text now costs\n\t// inside the region — then widen it to the whole context with the\n\t// independently estimated kept tail (symmetric, present on both sides when\n\t// kept). The authoritative `preparation.tokensBefore` is never mixed into\n\t// this comparison (#2052).\n\tconst tokensBefore = preparation.region.tokenEstimate;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4);\n\treturn widenToWholeContextStats(\n\t\t{\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\tgetKeptTailTokenEstimate(preparation),\n\t\ttrue,\n\t);\n}\n\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tassertCompactionOpen(this);\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\toptions.abortController.signal.throwIfAborted();\n\tconst model = this.model;\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings(model);\n\t// A sub-minimum region is admitted only when the caller already knows the\n\t// context does not fit: overflow recovery, or a post-tool preflight over the\n\t// provider hard input limit. A threshold crossing that still fits must not\n\t// clear context — its follow-up request can be sent as-is. `load_bearing`\n\t// alone does not mean \"must destroy context\".\n\tconst allowSmallRegion = options.urgency === \"load_bearing\" && options.allowSmallRegion === true;\n\tconst preparation = prepareCompactionBoundary(\n\t\tpathEntries,\n\t\tsettings,\n\t\t{\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t},\n\t\t{ allowSmallRegion },\n\t);\n\tif (!preparation) {\n\t\t// Mid-turn threshold preflight needs the load-bearing planner fallback if\n\t\t// a region exists, but a context that still fits is safe to send unchanged.\n\t\t// True overflow and a hard-limit preflight have no such escape hatch.\n\t\tconst mustFreeContext = options.urgency === \"load_bearing\" && (options.reason === \"overflow\" || allowSmallRegion);\n\t\tif (mustFreeContext) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Context compaction found no compactable transcript entries; nothing more was safely deletable\",\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tconst plan: CompactionPlanOptions = {\n\t\tstreamFn: this.agent.streamFunction,\n\t\tsessionFilePath: this.sessionManager.getSessionFile(),\n\t\tretry: this.settingsManager.getRetrySettings(),\n\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"compaction\", reason: options.reason }),\n\t};\n\tlet fromExtension = false;\n\tlet compacted:\n\t\t| {\n\t\t\t\ttext: string;\n\t\t\t\tstats: VerbatimCompactionStats;\n\t\t\t\trung: CompactionRung;\n\t\t\t\tplannerModel?: CompactionPlannerModel;\n\t\t\t\tkeptTail: boolean;\n\t\t\t\tusage?: Usage;\n\t\t\t\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\t\t\t\tmodel?: string;\n\t\t\t\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t\t\t\tsummaryFirstKeptEntryId?: string;\n\t\t\t\tsummaryTokensBefore?: number;\n\t\t }\n\t\t| undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\tlet snapshot: VerbatimCompactionPreparation;\n\t\ttry {\n\t\t\tsnapshot = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tpreparation: snapshot,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\t\tassertCompactionOpen(this);\n\t\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.cancel) {\n\t\t\toptions.abortController.abort();\n\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t}\n\t\tif (hookResult?.compactedText !== undefined) {\n\t\t\tif (hookResult.compactedText.trim().length === 0) throw new Error(\"No compacted text provided by extension\");\n\t\t\tcompacted = {\n\t\t\t\ttext: hookResult.compactedText,\n\t\t\t\tstats: extensionStats(preparation, hookResult.compactedText),\n\t\t\t\trung: \"extension\",\n\t\t\t\tkeptTail: true,\n\t\t\t};\n\t\t\tfromExtension = true;\n\t\t\toptions.onCompactionSource?.(true);\n\t\t}\n\t}\n\n\tif (!compacted) {\n\t\t// Borrowing walks the session's *effective* fallback list, which SDK\n\t\t// options may override, and resolves credentials per candidate. It never\n\t\t// touches session model state or the main chat's attempted-key set.\n\t\tconst fallback: FallbackPlannerContext = {\n\t\t\tfallbackModels: this._fallbackModels,\n\t\t\tregistry: this._modelRuntime,\n\t\t\tpreferredProvider: model.provider,\n\t\t\tsessionThinkingLevel: this.thinkingLevel,\n\t\t\tisFallbackModelAllowed: this._isFallbackModelAllowed,\n\t\t};\n\t\tconst run = await runVerbatimCompaction(preparation, model, {\n\t\t\t...plan,\n\t\t\tresolveAuth: options.resolvePlannerAuth,\n\t\t\tsignal: options.abortController.signal,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t\tresolveMorphApiKey: async () =>\n\t\t\t\t(await this._modelRuntime.getAuth(\"morph\", { signal: options.abortController.signal }))?.auth.apiKey,\n\t\t\tclassify: (classifierModel, context, classifierOptions) =>\n\t\t\t\tthis._modelRuntime.classify(classifierModel, context, classifierOptions),\n\t\t\tcompactionModel: resolveCompactionModel(\n\t\t\t\toptions.compactionModel ?? this.settingsManager.getCompactionModel(),\n\t\t\t\tmodel,\n\t\t\t\tthis._modelRuntime.getAllModels(),\n\t\t\t),\n\t\t\tsummaryEntries: pathEntries,\n\t\t\tcwd: this._cwd,\n\t\t});\n\t\tcompacted = {\n\t\t\ttext: run.text,\n\t\t\tstats: run.stats,\n\t\t\trung: run.rung,\n\t\t\t...(run.plannerModel ? { plannerModel: run.plannerModel } : {}),\n\t\t\t...(run.usage ? { usage: run.usage } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t\t...(run.backend ? { backend: run.backend } : {}),\n\t\t\t...(run.model ? { model: run.model } : {}),\n\t\t\t...(run.summary ? { summary: run.summary } : {}),\n\t\t\t...(run.summaryFirstKeptEntryId ? { summaryFirstKeptEntryId: run.summaryFirstKeptEntryId } : {}),\n\t\t\t...(run.summaryTokensBefore !== undefined ? { summaryTokensBefore: run.summaryTokensBefore } : {}),\n\t\t};\n\t}\n\tassertCompactionOpen(this);\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\t// A fresh rung that had to drop the protected tail persists no tail boundary.\n\tconst firstKeptEntryId =\n\t\tcompacted.summaryFirstKeptEntryId ?? (compacted.keptTail ? preparation.firstKeptEntryId : null);\n\tconst tokensBefore = compacted.summaryTokensBefore ?? preparation.tokensBefore;\n\tconst backupPath = await this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: preparation.parameters,\n\t\tstats: compacted.stats,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst entryId = await this.sessionManager.appendCompaction(\n\t\tcompacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails,\n\t\tcompacted.usage,\n\t);\n\tthis._refreshFinalizedContext();\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tstats: compacted.stats,\n\t\tparameters: preparation.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t...(compacted.usage ? { usage: compacted.usage } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst compactionEntry = this.sessionManager.getEntry(entryId) as CompactionEntry<VerbatimCompactionDetails>;\n\ttry {\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension,\n\t\t} satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<session_compact>\",\n\t\t\tevent: \"session_compact\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\nexport async function emitSessionCompactFailed(\n\tsession: AgentSession,\n\tevent: Omit<SessionCompactFailedEvent, \"type\">,\n): Promise<void> {\n\tif (session._extensionRunner?.hasHandlers(\"session_compact_failed\")) {\n\t\tawait session._extensionRunner.emit({ type: \"session_compact_failed\", ...event });\n\t}\n}\n\nfunction clearOwnedManualCompactionState(this: AgentSession, controller: AbortController): void {\n\tif (this._compactionAbortController !== controller) return;\n\tthis._compactionAbortController = undefined;\n\tif (this._compactionReason === \"manual\") this._compactionReason = undefined;\n\t// Lifecycle listeners run synchronously. Once the manual end event is\n\t// emitted, a new /compact must own a new run rather than join the settled one.\n\tthis._manualCompactionPromise = undefined;\n}\n\nasync function emitManualCompactionFailure(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\terror: unknown,\n\tfromExtension: boolean,\n): Promise<void> {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst aborted = controller.signal.aborted;\n\tconst errorMessage = aborted ? undefined : `Compaction failed: ${message}`;\n\tclearOwnedManualCompactionState.call(this, controller);\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"manual\",\n\t\tresult: undefined,\n\t\taborted,\n\t\twillRetry: false,\n\t\terrorMessage,\n\t});\n\tawait emitSessionCompactFailed(this, {\n\t\treason: \"manual\",\n\t\terrorMessage,\n\t\taborted,\n\t\twillRetry: false,\n\t\tfromExtension,\n\t});\n}\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: SessionCompactOptions,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\t// Caller parameters are projected explicitly, so no extra runtime\n\t\t\t// property survives. A widened or cast object could otherwise carry\n\t\t\t// `urgency: \"load_bearing\"` through a public `session.compact()` call and\n\t\t\t// reach the context-destroying rung, which manual compaction must never do.\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t\t...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),\n\t\t\tresolvePlannerAuth: (candidate) => this._getRequiredRequestAuth(candidate, controller.signal),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\t// compaction_end listeners synchronously flush queued prompts, so they must\n\t\t// observe an idle session before dispatching the next user turn.\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tawait emitManualCompactionFailure.call(this, controller, error, fromExtension);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Persist one verbatim line-subset compaction boundary.\n *\n * Re-entrancy safe: a call made while a manual compaction is still in flight\n * joins that run instead of starting a second one. Manual compaction aborts an\n * active agent run before it starts, while agent event delivery remains live so\n * a pending threshold check cannot race the requested manual boundary.\n */\nexport function compact(this: AgentSession, options: SessionCompactOptions = {}): Promise<VerbatimCompactionResult> {\n\ttry {\n\t\tassertCompactionOpen(this);\n\t\tif (options.compactionModel !== undefined && this.model) {\n\t\t\tresolveCompactionModel(options.compactionModel, this.model, this._modelRuntime.getAllModels());\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\n\t// A manual boundary replaces the automatic turn that scheduled any pending\n\t// retry. Invalidate its timer before this run claims compaction ownership.\n\tthis._postCompactionContinuationToken += 1;\n\tthis._pendingPostCompactionContinuation = undefined;\n\n\tconst automaticCompletion = this._autoCompactionCompletion;\n\t// The manual request wins. Abort the active automatic planner now, before the\n\t// next microtask can admit a post-tool or threshold boundary, then wait for\n\t// its owner to settle before mutating the transcript ourselves. Start the\n\t// session abort before publishing this new manual owner so abort() cancels\n\t// prior work rather than cancelling or waiting on the compaction being started.\n\tthis._autoCompactionAbortController?.abort();\n\tconst abortBoundary = this.abort();\n\n\tconst controller = new AbortController();\n\tthis._compactionAbortController = controller;\n\tthis._compactionReason = \"manual\";\n\t// Handle rejection now so a failing event drain cannot become unhandled\n\t// while an automatic run finishes.\n\tvoid abortBoundary.catch(() => {});\n\tlet flight!: Promise<VerbatimCompactionResult>;\n\t// Start the owned run in a microtask so both single-flight fields are\n\t// published before any joiner can observe a partially claimed compaction.\n\tflight = trackSessionWork(this, () =>\n\t\tPromise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tif (automaticCompletion !== undefined) await automaticCompletion;\n\t\t\t\tawait abortBoundary;\n\t\t\t} catch (error) {\n\t\t\t\t// The abort drain can fail before the planner starts. Finish the\n\t\t\t\t// manual lifecycle so event consumers can release queued input.\n\t\t\t\tawait emitManualCompactionFailure.call(this, controller, error, false);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCompactionOpen(this);\n\t\t\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t}),\n\t).finally(() => {\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\t});\n\tthis._manualCompactionPromise = flight;\n\treturn flight;\n}\n\nexport function abortCompaction(this: AgentSession): void {\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setCompactionEnabled(enabled));\n}\n\nexport const agentSessionCompactionMethods = {\n\t_applyVerbatimCompaction,\n\tcompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-compaction.js","sourceRoot":"","sources":["../../src/core/agent-session-compaction.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAKN,wBAAwB,EACxB,yBAAyB,EACzB,qBAAqB,EACrB,kCAAkC,EAClC,4BAA4B,EAK5B,wBAAwB,GACxB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AAOxE,OAAO,EAAE,iBA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AE,UAAU,CAAC,CAAC;QACvD,IAAI,IAAI,CAAC,wBAAwB,KAAK,MAAM;YAAE,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;IACzF,CAAC,CAAC,CAAC;IACH,IAAI,CAAC,wBAAwB,GAAG,MAAM,CAAC;IACvC,OAAO,MAAM,CAAC;AACf,CAAC;AAED,MAAM,UAAU,eAAe;IAC9B,IAAI,CAAC,0BAA0B,EAAE,KAAK,EAAE,CAAC;IACzC,IAAI,CAAC,8BAA8B,EAAE,KAAK,EAAE,CAAC;AAC9C,CAAC;AACD,MAAM,UAAU,kBAAkB;IACjC,IAAI,CAAC,6BAA6B,EAAE,KAAK,EAAE,CAAC;AAC7C,CAAC;AACD,MAAM,UAAU,wBAAwB,CAAqB,OAAgB;IAC5E,kBAAkB,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC;AACxF,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC5C,wBAAwB;IACxB,OAAO;IACP,eAAe;IACf,kBAAkB;IAClB,wBAAwB;CACxB,CAAC","sourcesContent":["import type { Usage } from \"@bastani/pi-ai/compat\";\nimport type {\n\tAgentSessionInternalSurface as AgentSession,\n\tSessionCompactOptions,\n\tVerbatimCompactionApplyOptions,\n} from \"./agent-session-methods.ts\";\nimport { authForStream } from \"./agent-session-models.ts\";\nimport { formatNoModelSelectedMessage } from \"./auth-guidance.ts\";\nimport {\n\ttype CompactionPlannerModel,\n\ttype CompactionPlanOptions,\n\ttype CompactionRung,\n\ttype FallbackPlannerContext,\n\tgetKeptTailTokenEstimate,\n\tprepareCompactionBoundary,\n\trunVerbatimCompaction,\n\tVERBATIM_COMPACTION_PROMPT_VERSION,\n\tVERBATIM_COMPACTION_STRATEGY,\n\ttype VerbatimCompactionDetails,\n\ttype VerbatimCompactionPreparation,\n\ttype VerbatimCompactionResult,\n\ttype VerbatimCompactionStats,\n\twidenToWholeContextStats,\n} from \"./compaction/index.ts\";\nimport { resolveCompactionModel } from \"./compaction/model-resolver.js\";\nimport type {\n\tSessionBeforeCompactEvent,\n\tSessionBeforeCompactResult,\n\tSessionCompactEvent,\n\tSessionCompactFailedEvent,\n} from \"./extensions/index.js\";\nimport { assertSessionOpen as assertCompactionOpen, trackSessionWork } from \"./session-lifecycle-work.ts\";\nimport type { CompactionEntry } from \"./session-manager.ts\";\nimport { settingsWriteOwner } from \"./settings-write-ownership.ts\";\nimport { createSummarizationRetryCallbacks } from \"./summarization-retry.ts\";\n\nfunction frozenCollectionMutation(): never {\n\tthrow new TypeError(\"Cannot mutate frozen compaction preparation\");\n}\n\nfunction deepFreeze<T>(value: T): T {\n\tif (!value || typeof value !== \"object\" || Object.isFrozen(value)) return value;\n\tif (value instanceof Map) {\n\t\tfor (const [key, nested] of value) {\n\t\t\tdeepFreeze(key);\n\t\t\tdeepFreeze(nested);\n\t\t}\n\t\tObject.defineProperties(value, {\n\t\t\tset: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else if (value instanceof Set) {\n\t\tfor (const nested of value) deepFreeze(nested);\n\t\tObject.defineProperties(value, {\n\t\t\tadd: { value: frozenCollectionMutation },\n\t\t\tdelete: { value: frozenCollectionMutation },\n\t\t\tclear: { value: frozenCollectionMutation },\n\t\t});\n\t} else {\n\t\tfor (const nested of Object.values(value)) deepFreeze(nested);\n\t}\n\treturn Object.freeze(value);\n}\n\nfunction extensionStats(preparation: VerbatimCompactionPreparation, compactedText: string): VerbatimCompactionStats {\n\tconst linesBefore = preparation.region.lines.length;\n\tconst linesKept = compactedText.split(\"\\n\").length;\n\t// Region-only view first — what the extension's replacement text now costs\n\t// inside the region — then widen it to the whole context with the\n\t// independently estimated kept tail (symmetric, present on both sides when\n\t// kept). The authoritative `preparation.tokensBefore` is never mixed into\n\t// this comparison (#2052).\n\tconst tokensBefore = preparation.region.tokenEstimate;\n\tconst tokensAfter = Math.ceil(compactedText.length / 4);\n\treturn widenToWholeContextStats(\n\t\t{\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\tgetKeptTailTokenEstimate(preparation),\n\t\ttrue,\n\t);\n}\n\nexport async function _applyVerbatimCompaction(\n\tthis: AgentSession,\n\toptions: VerbatimCompactionApplyOptions,\n): Promise<VerbatimCompactionResult | undefined> {\n\tassertCompactionOpen(this);\n\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\toptions.abortController.signal.throwIfAborted();\n\tconst model = this.model;\n\tconst pathEntries = this.sessionManager.getBranch();\n\tconst settings = this.settingsManager.getCompactionSettings(model);\n\t// A sub-minimum region is admitted only when the caller already knows the\n\t// context does not fit: overflow recovery, or a post-tool preflight over the\n\t// provider hard input limit. A threshold crossing that still fits must not\n\t// clear context — its follow-up request can be sent as-is. `load_bearing`\n\t// alone does not mean \"must destroy context\".\n\tconst allowSmallRegion = options.urgency === \"load_bearing\" && options.allowSmallRegion === true;\n\tconst preparation = prepareCompactionBoundary(\n\t\tpathEntries,\n\t\tsettings,\n\t\t{\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t},\n\t\t{ allowSmallRegion },\n\t);\n\tif (!preparation) {\n\t\t// Mid-turn threshold preflight needs the load-bearing planner fallback if\n\t\t// a region exists, but a context that still fits is safe to send unchanged.\n\t\t// True overflow and a hard-limit preflight have no such escape hatch.\n\t\tconst mustFreeContext = options.urgency === \"load_bearing\" && (options.reason === \"overflow\" || allowSmallRegion);\n\t\tif (mustFreeContext) {\n\t\t\tthrow new Error(\n\t\t\t\t\"Context compaction found no compactable transcript entries; nothing more was safely deletable\",\n\t\t\t);\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tconst plan: CompactionPlanOptions = {\n\t\tstreamFn: this.agent.streamFunction,\n\t\tsessionFilePath: this.sessionManager.getSessionFile(),\n\t\tretry: this.settingsManager.getRetrySettings(),\n\t\tcallbacks: createSummarizationRetryCallbacks(this, { source: \"compaction\", reason: options.reason }),\n\t};\n\tlet fromExtension = false;\n\tlet compacted:\n\t\t| {\n\t\t\t\ttext: string;\n\t\t\t\tstats: VerbatimCompactionStats;\n\t\t\t\trung: CompactionRung;\n\t\t\t\tplannerModel?: CompactionPlannerModel;\n\t\t\t\tkeptTail: boolean;\n\t\t\t\tusage?: Usage;\n\t\t\t\tbackend?: \"planner\" | \"classifier\" | \"morph\" | \"summary\";\n\t\t\t\tmodel?: string;\n\t\t\t\tsummary?: { readFiles: string[]; modifiedFiles: string[] };\n\t\t\t\tsummaryFirstKeptEntryId?: string;\n\t\t\t\tsummaryTokensBefore?: number;\n\t\t }\n\t\t| undefined;\n\n\tif (this._extensionRunner.hasHandlers(\"session_before_compact\")) {\n\t\tlet snapshot: VerbatimCompactionPreparation;\n\t\ttry {\n\t\t\tsnapshot = deepFreeze(structuredClone(preparation));\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to snapshot transcript for compaction extensions: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tconst hookResult = (await this._extensionRunner.emit({\n\t\t\ttype: \"session_before_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tpreparation: snapshot,\n\t\t\tbranchEntries: pathEntries,\n\t\t\tsignal: options.abortController.signal,\n\t\t} satisfies SessionBeforeCompactEvent)) as SessionBeforeCompactResult | undefined;\n\t\tassertCompactionOpen(this);\n\t\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\t\tif (hookResult?.cancel) {\n\t\t\toptions.abortController.abort();\n\t\t\tthrow new Error(\"Compaction cancelled\");\n\t\t}\n\t\tif (hookResult?.compactedText !== undefined) {\n\t\t\tif (hookResult.compactedText.trim().length === 0) throw new Error(\"No compacted text provided by extension\");\n\t\t\tcompacted = {\n\t\t\t\ttext: hookResult.compactedText,\n\t\t\t\tstats: extensionStats(preparation, hookResult.compactedText),\n\t\t\t\trung: \"extension\",\n\t\t\t\tkeptTail: true,\n\t\t\t};\n\t\t\tfromExtension = true;\n\t\t\toptions.onCompactionSource?.(true);\n\t\t}\n\t}\n\n\tif (!compacted) {\n\t\t// Borrowing walks the session's *effective* fallback list, which SDK\n\t\t// options may override, and resolves credentials per candidate. It never\n\t\t// touches session model state or the main chat's attempted-key set.\n\t\tconst fallback: FallbackPlannerContext = {\n\t\t\tfallbackModels: this._fallbackModels,\n\t\t\tregistry: this._modelRuntime,\n\t\t\tpreferredProvider: model.provider,\n\t\t\tsessionThinkingLevel: this.thinkingLevel,\n\t\t\tisFallbackModelAllowed: this._isFallbackModelAllowed,\n\t\t};\n\t\tconst run = await runVerbatimCompaction(preparation, model, {\n\t\t\t...plan,\n\t\t\tresolveAuth: options.resolvePlannerAuth,\n\t\t\tsignal: options.abortController.signal,\n\t\t\tthinkingLevel: this.thinkingLevel,\n\t\t\turgency: options.urgency,\n\t\t\tfallback,\n\t\t\tresolveMorphApiKey: async () =>\n\t\t\t\t(await this._modelRuntime.getAuth(\"morph\", { signal: options.abortController.signal }))?.auth.apiKey,\n\t\t\tclassify: (classifierModel, context, classifierOptions) =>\n\t\t\t\tthis._modelRuntime.classify(classifierModel, context, classifierOptions),\n\t\t\tcompactionModel: resolveCompactionModel(\n\t\t\t\toptions.compactionModel ?? this.settingsManager.getCompactionModel(),\n\t\t\t\tmodel,\n\t\t\t\tthis._modelRuntime.getAllModels(),\n\t\t\t),\n\t\t\tsummaryEntries: pathEntries,\n\t\t\tcwd: this._cwd,\n\t\t});\n\t\tcompacted = {\n\t\t\ttext: run.text,\n\t\t\tstats: run.stats,\n\t\t\trung: run.rung,\n\t\t\t...(run.plannerModel ? { plannerModel: run.plannerModel } : {}),\n\t\t\t...(run.usage ? { usage: run.usage } : {}),\n\t\t\tkeptTail: run.keptTail,\n\t\t\t...(run.backend ? { backend: run.backend } : {}),\n\t\t\t...(run.model ? { model: run.model } : {}),\n\t\t\t...(run.summary ? { summary: run.summary } : {}),\n\t\t\t...(run.summaryFirstKeptEntryId ? { summaryFirstKeptEntryId: run.summaryFirstKeptEntryId } : {}),\n\t\t\t...(run.summaryTokensBefore !== undefined ? { summaryTokensBefore: run.summaryTokensBefore } : {}),\n\t\t};\n\t}\n\tassertCompactionOpen(this);\n\tif (options.abortController.signal.aborted) throw new Error(\"Compaction cancelled\");\n\n\t// A fresh rung that had to drop the protected tail persists no tail boundary.\n\tconst firstKeptEntryId =\n\t\tcompacted.summaryFirstKeptEntryId ?? (compacted.keptTail ? preparation.firstKeptEntryId : null);\n\tconst tokensBefore = compacted.summaryTokensBefore ?? preparation.tokensBefore;\n\tconst backupPath = await this.sessionManager.writeBackupSnapshot(options.backupLabel);\n\tconst details: VerbatimCompactionDetails = {\n\t\tstrategy: VERBATIM_COMPACTION_STRATEGY,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\tparameters: preparation.parameters,\n\t\tstats: compacted.stats,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst entryId = await this.sessionManager.appendCompaction(\n\t\tcompacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tdetails,\n\t\tcompacted.usage,\n\t);\n\tthis._refreshFinalizedContext();\n\tconst result: VerbatimCompactionResult = {\n\t\tcompactedText: compacted.text,\n\t\tfirstKeptEntryId,\n\t\ttokensBefore,\n\t\tstats: compacted.stats,\n\t\tparameters: preparation.parameters,\n\t\tpromptVersion: VERBATIM_COMPACTION_PROMPT_VERSION,\n\t\trung: compacted.rung,\n\t\t...(compacted.plannerModel ? { plannerModel: compacted.plannerModel } : {}),\n\t\t...(compacted.backend ? { backend: compacted.backend } : {}),\n\t\t...(compacted.model ? { model: compacted.model } : {}),\n\t\t...(compacted.summary ? { summary: compacted.summary } : {}),\n\t\t...(compacted.usage ? { usage: compacted.usage } : {}),\n\t\t...(backupPath ? { backupPath } : {}),\n\t};\n\tconst compactionEntry = this.sessionManager.getEntry(entryId) as CompactionEntry<VerbatimCompactionDetails>;\n\ttry {\n\t\tawait this._extensionRunner.emit({\n\t\t\ttype: \"session_compact\",\n\t\t\treason: options.reason,\n\t\t\tparameters: preparation.parameters,\n\t\t\tresult,\n\t\t\tcompactionEntry,\n\t\t\tfromExtension,\n\t\t} satisfies SessionCompactEvent);\n\t} catch (error) {\n\t\tthis._extensionRunner.emitError({\n\t\t\textensionPath: \"<session_compact>\",\n\t\t\tevent: \"session_compact\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\tstack: error instanceof Error ? error.stack : undefined,\n\t\t});\n\t}\n\treturn result;\n}\n\nexport async function emitSessionCompactFailed(\n\tsession: AgentSession,\n\tevent: Omit<SessionCompactFailedEvent, \"type\">,\n): Promise<void> {\n\tif (session._extensionRunner?.hasHandlers(\"session_compact_failed\")) {\n\t\tawait session._extensionRunner.emit({ type: \"session_compact_failed\", ...event });\n\t}\n}\n\nfunction clearOwnedManualCompactionState(this: AgentSession, controller: AbortController): void {\n\tif (this._compactionAbortController !== controller) return;\n\tthis._compactionAbortController = undefined;\n\tif (this._compactionReason === \"manual\") this._compactionReason = undefined;\n\t// Lifecycle listeners run synchronously. Once the manual end event is\n\t// emitted, a new /compact must own a new run rather than join the settled one.\n\tthis._manualCompactionPromise = undefined;\n}\n\nasync function emitManualCompactionFailure(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\terror: unknown,\n\tfromExtension: boolean,\n): Promise<void> {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tconst aborted = controller.signal.aborted;\n\tconst errorMessage = aborted ? undefined : `Compaction failed: ${message}`;\n\tclearOwnedManualCompactionState.call(this, controller);\n\tthis._emit({\n\t\ttype: \"compaction_end\",\n\t\treason: \"manual\",\n\t\tresult: undefined,\n\t\taborted,\n\t\twillRetry: false,\n\t\terrorMessage,\n\t});\n\tawait emitSessionCompactFailed(this, {\n\t\treason: \"manual\",\n\t\terrorMessage,\n\t\taborted,\n\t\twillRetry: false,\n\t\tfromExtension,\n\t});\n}\n\nasync function runOwnedManualCompaction(\n\tthis: AgentSession,\n\tcontroller: AbortController,\n\toptions: SessionCompactOptions,\n): Promise<VerbatimCompactionResult> {\n\tthis._emit({ type: \"compaction_start\", reason: \"manual\" });\n\tlet fromExtension = false;\n\ttry {\n\t\tcontroller.signal.throwIfAborted();\n\t\tif (!this.model) throw new Error(formatNoModelSelectedMessage());\n\t\tconst result = await this._applyVerbatimCompaction({\n\t\t\t// Caller parameters are projected explicitly, so no extra runtime\n\t\t\t// property survives. A widened or cast object could otherwise carry\n\t\t\t// `urgency: \"load_bearing\"` through a public `session.compact()` call and\n\t\t\t// reach the context-destroying rung, which manual compaction must never do.\n\t\t\t...(options.compression_ratio === undefined ? {} : { compression_ratio: options.compression_ratio }),\n\t\t\t...(options.preserve_recent === undefined ? {} : { preserve_recent: options.preserve_recent }),\n\t\t\t...(options.query === undefined ? {} : { query: options.query }),\n\t\t\t...(options.compactionModel === undefined ? {} : { compactionModel: options.compactionModel }),\n\t\t\tresolvePlannerAuth: async (candidate) =>\n\t\t\t\tauthForStream(this, await this._getRequiredRequestAuth(candidate, controller.signal)),\n\t\t\tabortController: controller,\n\t\t\tbackupLabel: \"compact\",\n\t\t\treason: \"manual\",\n\t\t\turgency: \"recoverable\",\n\t\t\tonCompactionSource: (value) => {\n\t\t\t\tfromExtension = value;\n\t\t\t},\n\t\t});\n\t\tif (!result) throw new Error(\"Nothing to compact (session too small)\");\n\t\t// compaction_end listeners synchronously flush queued prompts, so they must\n\t\t// observe an idle session before dispatching the next user turn.\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tthis._emit({ type: \"compaction_end\", reason: \"manual\", result, aborted: false, willRetry: false });\n\t\treturn result;\n\t} catch (error) {\n\t\tawait emitManualCompactionFailure.call(this, controller, error, fromExtension);\n\t\tthrow error;\n\t}\n}\n\n/**\n * Persist one verbatim line-subset compaction boundary.\n *\n * Re-entrancy safe: a call made while a manual compaction is still in flight\n * joins that run instead of starting a second one. Manual compaction aborts an\n * active agent run before it starts, while agent event delivery remains live so\n * a pending threshold check cannot race the requested manual boundary.\n */\nexport function compact(this: AgentSession, options: SessionCompactOptions = {}): Promise<VerbatimCompactionResult> {\n\ttry {\n\t\tassertCompactionOpen(this);\n\t\tif (options.compactionModel !== undefined && this.model) {\n\t\t\tresolveCompactionModel(options.compactionModel, this.model, this._modelRuntime.getAllModels());\n\t\t}\n\t} catch (error) {\n\t\treturn Promise.reject(error);\n\t}\n\tconst inFlight = this._manualCompactionPromise;\n\tif (inFlight) return inFlight;\n\n\t// A manual boundary replaces the automatic turn that scheduled any pending\n\t// retry. Invalidate its timer before this run claims compaction ownership.\n\tthis._postCompactionContinuationToken += 1;\n\tthis._pendingPostCompactionContinuation = undefined;\n\n\tconst automaticCompletion = this._autoCompactionCompletion;\n\t// The manual request wins. Abort the active automatic planner now, before the\n\t// next microtask can admit a post-tool or threshold boundary, then wait for\n\t// its owner to settle before mutating the transcript ourselves. Start the\n\t// session abort before publishing this new manual owner so abort() cancels\n\t// prior work rather than cancelling or waiting on the compaction being started.\n\tthis._autoCompactionAbortController?.abort();\n\tconst abortBoundary = this.abort();\n\n\tconst controller = new AbortController();\n\tthis._compactionAbortController = controller;\n\tthis._compactionReason = \"manual\";\n\t// Handle rejection now so a failing event drain cannot become unhandled\n\t// while an automatic run finishes.\n\tvoid abortBoundary.catch(() => {});\n\tlet flight!: Promise<VerbatimCompactionResult>;\n\t// Start the owned run in a microtask so both single-flight fields are\n\t// published before any joiner can observe a partially claimed compaction.\n\tflight = trackSessionWork(this, () =>\n\t\tPromise.resolve().then(async () => {\n\t\t\ttry {\n\t\t\t\tif (automaticCompletion !== undefined) await automaticCompletion;\n\t\t\t\tawait abortBoundary;\n\t\t\t} catch (error) {\n\t\t\t\t// The abort drain can fail before the planner starts. Finish the\n\t\t\t\t// manual lifecycle so event consumers can release queued input.\n\t\t\t\tawait emitManualCompactionFailure.call(this, controller, error, false);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tassertCompactionOpen(this);\n\t\t\treturn runOwnedManualCompaction.call(this, controller, options);\n\t\t}),\n\t).finally(() => {\n\t\tclearOwnedManualCompactionState.call(this, controller);\n\t\tif (this._manualCompactionPromise === flight) this._manualCompactionPromise = undefined;\n\t});\n\tthis._manualCompactionPromise = flight;\n\treturn flight;\n}\n\nexport function abortCompaction(this: AgentSession): void {\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n}\nexport function abortBranchSummary(this: AgentSession): void {\n\tthis._branchSummaryAbortController?.abort();\n}\nexport function setAutoCompactionEnabled(this: AgentSession, enabled: boolean): void {\n\tsettingsWriteOwner.run(this, () => this.settingsManager.setCompactionEnabled(enabled));\n}\n\nexport const agentSessionCompactionMethods = {\n\t_applyVerbatimCompaction,\n\tcompact,\n\tabortCompaction,\n\tabortBranchSummary,\n\tsetAutoCompactionEnabled,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-extension-bindings.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-extension-bindings.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session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E,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAEvF;AAED,wBAAsB,gCAAgC,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BxF;AAED,wBAAgB,kBAAkB,CACjC,IAAI,EAAE,YAAY,EAClB,MAAM,EAAE,eAAe,EACvB,WAAW,CAAC,EAAE,wBAAwB,EACtC,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,EACpC,cAAc,CAAC,EAAE,mBAAmB,GAClC,IAAI,CA4UN;AAED,wBAAsB,MAAM,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAKnG;AAkUD,qGAAqG;AACrG,wBAAsB,wBAAwB,CAAC,IAAI,EAAE,YAAY,EAAE,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BhH;AAMD;;;GAGG;AAEH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;CAYhD,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { basename, dirname } from "node:path";
|
|
2
2
|
import { clampThinkingLevel, resetApiProviders } from "@bastani/pi-ai/compat";
|
|
3
3
|
import { resolveWorkflowStageDeliveryTarget } from "./agent-session-delivery-forwarding.js";
|
|
4
|
+
import { authForStream } from "./agent-session-models.js";
|
|
4
5
|
import { executeNestedToolCall, getCallableTools } from "./agent-session-nested-tools.js";
|
|
5
6
|
import { activatesAfterRecordedLoadout, preservesInitialToolLoadout, recordedToolLoadout, } from "./agent-session-state.js";
|
|
6
7
|
import { replaceSessionTaskOwner } from "./agent-session-tasks.js";
|
|
@@ -596,7 +597,7 @@ export function _bindExtensionCore(runner, publication, startupToolNames, startu
|
|
|
596
597
|
try {
|
|
597
598
|
if (signal.aborted)
|
|
598
599
|
return undefined;
|
|
599
|
-
const auth = await this._getRequiredRequestAuth(model);
|
|
600
|
+
const auth = authForStream(this, await this._getRequiredRequestAuth(model));
|
|
600
601
|
if (signal.aborted)
|
|
601
602
|
return undefined;
|
|
602
603
|
const result = await generateWorkflowSummary(text, {
|