@bastani/atomic 0.9.5-alpha.4 → 0.9.5-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +7 -0
- package/dist/builtin/subagents/agents/debugger.md +2 -2
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +11 -0
- package/dist/builtin/workflows/builtin/deep-research-codebase-utils.ts +5 -5
- package/dist/builtin/workflows/builtin/goal-runner.ts +5 -5
- package/dist/builtin/workflows/builtin/goal-types.ts +1 -0
- package/dist/builtin/workflows/builtin/goal.d.ts +2 -0
- package/dist/builtin/workflows/builtin/goal.ts +9 -0
- package/dist/builtin/workflows/builtin/index.d.ts +2 -0
- package/dist/builtin/workflows/builtin/open-claude-design-runner.ts +5 -5
- package/dist/builtin/workflows/builtin/ralph-models.ts +25 -25
- 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 +3 -2
- 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 +25 -4
- package/dist/core/agent-session-compaction.js.map +1 -1
- package/dist/core/compaction/context-compaction-critical.d.ts +15 -0
- package/dist/core/compaction/context-compaction-critical.d.ts.map +1 -0
- package/dist/core/compaction/context-compaction-critical.js +57 -0
- package/dist/core/compaction/context-compaction-critical.js.map +1 -0
- package/dist/core/compaction/context-compaction-eviction.d.ts +4 -0
- package/dist/core/compaction/context-compaction-eviction.d.ts.map +1 -0
- package/dist/core/compaction/context-compaction-eviction.js +172 -0
- package/dist/core/compaction/context-compaction-eviction.js.map +1 -0
- package/dist/core/compaction/context-compaction-runner.d.ts +7 -1
- package/dist/core/compaction/context-compaction-runner.d.ts.map +1 -1
- package/dist/core/compaction/context-compaction-runner.js +97 -21
- package/dist/core/compaction/context-compaction-runner.js.map +1 -1
- package/dist/core/compaction/context-transcript-analysis.d.ts +3 -0
- package/dist/core/compaction/context-transcript-analysis.d.ts.map +1 -1
- package/dist/core/compaction/context-transcript-analysis.js +3 -3
- package/dist/core/compaction/context-transcript-analysis.js.map +1 -1
- package/docs/compaction.md +45 -27
- package/docs/workflows.md +5 -1
- package/npm-shrinkwrap.json +23 -23
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.5-alpha.5] - 2026-07-06
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Added an internal tiered fallback ladder for automatic Verbatim Compaction when the strict `compression_ratio` target is not achievable: threshold and overflow auto-compaction now keep the standard strict planner pass as tier 1, tier 2 can accept a validated below-target result with at least one deletion when projected `tokensAfter` clears the relevant budget (`effectiveInputBudget - reserveTokens` for threshold, effective input budget for overflow), overflow commits from Atomic's internal ladder are gated on fitting the effective input budget even when the strict target is met, overflow-only tier 3 reruns the planner with critical LRU-style protected-entry eligibility for stale task-bearing user/custom/branch-summary context and an effective recent floor of `max(preserve_recent, 5)` across all compactable entries, and overflow-only tier 4 performs deterministic code-level LRU eviction without a model call or API credentials while enforcing the same effective last-5 recent floor until the effective input budget fits or no more safe deletion remains. The fallback tiers remain internal: extension hooks keep their existing shapes, extension-provided deletion requests still bypass the ladder including the overflow budget gate, and no public compaction mode API is exposed.
|
|
10
|
+
- Added hard iteration caps to compaction recovery loops: planner provider turns are capped at 50 per planner run (including tool-call turns), planner nudge follow-ups are capped at 50 per planner run, and deterministic overflow eviction is capped at 50 passes, so compaction cannot spin indefinitely and terminal failures report the achieved reduction, deletion count, projected `tokensAfter`, and budget.
|
|
11
|
+
|
|
12
|
+
### Fixed
|
|
13
|
+
|
|
14
|
+
- Fixed overflow auto-compaction silently no-oping when planner authentication was unavailable or when the current branch has no preparable compactable transcript: overflow recovery now either skips model tiers and runs deterministic no-auth LRU eviction directly through the existing validation pipeline, or surfaces a terminal error that nothing more was safely deletable.
|
|
15
|
+
- Fixed feasible partial compaction results being discarded solely because they missed the strict ratio target: automatic threshold and overflow compaction now commit validated below-target deletions when their projected `tokensAfter` clears the trigger/budget boundary, including partial deletion state salvaged after a provider context-overflow error.
|
|
16
|
+
|
|
5
17
|
## [0.9.5-alpha.4] - 2026-07-05
|
|
6
18
|
|
|
7
19
|
### Changed
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/cursor",
|
|
3
|
-
"version": "0.9.5-alpha.
|
|
3
|
+
"version": "0.9.5-alpha.5",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Experimental first-party Atomic extension for Cursor OAuth, model discovery, and streaming provider registration.",
|
|
6
6
|
"contributors": [
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
}
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@bastani/atomic-natives": "0.9.5-alpha.
|
|
43
|
+
"@bastani/atomic-natives": "0.9.5-alpha.5",
|
|
44
44
|
"@bufbuild/protobuf": "^2.12.1",
|
|
45
45
|
"@earendil-works/pi-ai": "^0.80.3"
|
|
46
46
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/intercom",
|
|
3
|
-
"version": "0.9.5-alpha.
|
|
3
|
+
"version": "0.9.5-alpha.5",
|
|
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/mcp",
|
|
3
|
-
"version": "0.9.5-alpha.
|
|
3
|
+
"version": "0.9.5-alpha.5",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension that adapts MCP (Model Context Protocol) servers into the coding agent. Fork of: https://github.com/nicobailon/pi-mcp-adapter",
|
|
6
6
|
"contributors": [
|
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [0.9.5-alpha.5] - 2026-07-06
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
|
|
9
|
+
- Changed the Claude Fable 5 reasoning level from `xhigh` to `high` in the builtin `debugger` agent, covering the `anthropic/claude-fable-5` primary and its OpenRouter mirror in the fallback chain.
|
|
10
|
+
- Changed the Claude Opus 4.8 reasoning level from `xhigh` to `high` in the builtin `debugger` agent's fallback chain (`github-copilot/claude-opus-4.8 (1m)`, `anthropic/claude-opus-4-8`, and the OpenRouter mirror); Opus 4.8 entries at other levels in other agents are unchanged.
|
|
11
|
+
|
|
5
12
|
## [0.9.5-alpha.2] - 2026-07-04
|
|
6
13
|
|
|
7
14
|
### Changed
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
name: debugger
|
|
3
3
|
description: Debug errors, test failures, and unexpected behavior. Use PROACTIVELY when encountering issues, analyzing stack traces, or investigating system problems.
|
|
4
4
|
tools: read, search, find, ls, bash, web_search, fetch_content, get_search_content, intercom, contact_supervisor, todo
|
|
5
|
-
model: anthropic/claude-fable-5:
|
|
6
|
-
fallbackModels: openai-codex/gpt-5.5:xhigh, github-copilot/gpt-5.5:xhigh, openai/gpt-5.5:xhigh, github-copilot/claude-opus-4.8 (1m):
|
|
5
|
+
model: anthropic/claude-fable-5:high
|
|
6
|
+
fallbackModels: openai-codex/gpt-5.5:xhigh, github-copilot/gpt-5.5:xhigh, openai/gpt-5.5:xhigh, github-copilot/claude-opus-4.8 (1m):high, anthropic/claude-opus-4-8:high, zai/glm-5.2:xhigh, zai-coding-cn/glm-5.2:xhigh, openrouter/anthropic/claude-fable-5:high, openrouter/sakana/fugu-ultra:high, openrouter/openai/gpt-5.5:xhigh, openrouter/anthropic/claude-opus-4-8:high, openrouter/z-ai/glm-5.2:xhigh
|
|
7
7
|
skills: tdd, playwright-cli, tmux
|
|
8
8
|
---
|
|
9
9
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bastani/subagents",
|
|
3
|
-
"version": "0.9.5-alpha.
|
|
3
|
+
"version": "0.9.5-alpha.5",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Atomic extension for delegating tasks to subagents with chains, parallel execution, and TUI clarification. 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.5-alpha.
|
|
3
|
+
"version": "0.9.5-alpha.5",
|
|
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": [
|
|
@@ -6,6 +6,17 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.9.5-alpha.5] - 2026-07-06
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Added `git_worktree_dir` to the builtin `goal` workflow with Ralph-parity input binding so Goal runs can create or reuse a repository worktree from `base_branch` while preserving the invoking repo-relative cwd for worker, reviewer, and optional final PR stages.
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
|
|
17
|
+
- Changed the Claude Fable 5 reasoning level from `xhigh` to `high` across all builtin workflow model chains (`ralph` prompt-engineer/orchestrator/reviewer-a/reviewer-b/reviewer-c, `goal` reviewer, `deep-research-codebase` planner, and `open-claude-design`), covering both the native `anthropic/claude-fable-5` entries and their OpenRouter mirrors.
|
|
18
|
+
- Changed the Claude Opus 4.8 reasoning level from `xhigh` to `high` across the same builtin workflow model chains, covering the `github-copilot/claude-opus-4.8 (1m)`, `anthropic/claude-opus-4-8`, and `openrouter/anthropic/claude-opus-4-8` entries; Opus 4.8 entries already at `medium`/`low` value points are unchanged.
|
|
19
|
+
|
|
9
20
|
## [0.9.5-alpha.4] - 2026-07-05
|
|
10
21
|
|
|
11
22
|
### Changed
|
|
@@ -35,19 +35,19 @@ export const FILE_ONLY_OUTPUT = "file-only" satisfies WorkflowOutputMode;
|
|
|
35
35
|
// for the frontier data). This planner uses the high-capacity synthesis roster
|
|
36
36
|
// because it performs cross-codebase planning before partition fan-out.
|
|
37
37
|
export const PLANNER_MODEL_CONFIG = {
|
|
38
|
-
model: "anthropic/claude-fable-5:
|
|
38
|
+
model: "anthropic/claude-fable-5:high",
|
|
39
39
|
fallbackModels: [
|
|
40
40
|
"openai-codex/gpt-5.5:xhigh",
|
|
41
41
|
"github-copilot/gpt-5.5:xhigh",
|
|
42
42
|
"openai/gpt-5.5:xhigh",
|
|
43
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
44
|
-
"anthropic/claude-opus-4-8:
|
|
43
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
44
|
+
"anthropic/claude-opus-4-8:high",
|
|
45
45
|
"zai/glm-5.2:xhigh",
|
|
46
46
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
47
|
-
"openrouter/anthropic/claude-fable-5:
|
|
47
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
48
48
|
"openrouter/sakana/fugu-ultra:high",
|
|
49
49
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
50
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
50
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
51
51
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
52
52
|
],
|
|
53
53
|
excludedTools: ["ask_user_question"],
|
|
@@ -114,19 +114,19 @@ export async function runGoalWorkflow(ctx: GoalRunnerContext, options: GoalWorkf
|
|
|
114
114
|
};
|
|
115
115
|
|
|
116
116
|
const reviewerModelConfig = {
|
|
117
|
-
model: "anthropic/claude-fable-5:
|
|
117
|
+
model: "anthropic/claude-fable-5:high",
|
|
118
118
|
fallbackModels: [
|
|
119
119
|
"openai-codex/gpt-5.5:xhigh",
|
|
120
120
|
"github-copilot/gpt-5.5:xhigh",
|
|
121
121
|
"openai/gpt-5.5:xhigh",
|
|
122
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
123
|
-
"anthropic/claude-opus-4-8:
|
|
122
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
123
|
+
"anthropic/claude-opus-4-8:high",
|
|
124
124
|
"zai/glm-5.2:xhigh",
|
|
125
125
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
126
|
-
"openrouter/anthropic/claude-fable-5:
|
|
126
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
127
127
|
"openrouter/sakana/fugu-ultra:high",
|
|
128
128
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
129
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
129
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
130
130
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
131
131
|
],
|
|
132
132
|
tools: goalRunnerTools,
|
|
@@ -14,6 +14,7 @@ export type GoalWorkflowInputs = WorkflowInputValues & {
|
|
|
14
14
|
readonly acceptance_criteria?: string;
|
|
15
15
|
readonly max_turns: number;
|
|
16
16
|
readonly base_branch: string;
|
|
17
|
+
readonly git_worktree_dir: string;
|
|
17
18
|
readonly create_pr: boolean;
|
|
18
19
|
};
|
|
19
20
|
|
|
@@ -22,6 +23,7 @@ export type GoalWorkflowRunInputs = WorkflowInputValues & {
|
|
|
22
23
|
readonly acceptance_criteria?: string;
|
|
23
24
|
readonly max_turns?: number;
|
|
24
25
|
readonly base_branch?: string;
|
|
26
|
+
readonly git_worktree_dir?: string;
|
|
25
27
|
readonly create_pr?: boolean;
|
|
26
28
|
};
|
|
27
29
|
|
|
@@ -25,6 +25,11 @@ export default workflow({
|
|
|
25
25
|
default: "origin/main",
|
|
26
26
|
description: "Optional branch reviewers compare the current code delta against (default origin/main).",
|
|
27
27
|
}),
|
|
28
|
+
git_worktree_dir: Type.String({
|
|
29
|
+
default: "",
|
|
30
|
+
description:
|
|
31
|
+
"Optional Git worktree path. Must start inside a Git repo; absolute paths are used as-is, relative paths resolve from the repo root, existing Git worktrees from the invoking repository are reused/shared as-is, and missing paths are created from base_branch.",
|
|
32
|
+
}),
|
|
28
33
|
create_pr: Type.Boolean({
|
|
29
34
|
default: false,
|
|
30
35
|
description:
|
|
@@ -55,6 +60,10 @@ export default workflow({
|
|
|
55
60
|
review_report_path: Type.Optional(Type.String({ description: "JSON artifact path for the latest reviewer decision round." })),
|
|
56
61
|
pr_report: Type.Optional(Type.String({ description: "Pull-request report emitted only when create_pr=true, Goal reaches complete, and the final pull-request stage runs." })),
|
|
57
62
|
},
|
|
63
|
+
worktreeFromInputs: {
|
|
64
|
+
gitWorktreeDir: "git_worktree_dir",
|
|
65
|
+
baseBranch: "base_branch",
|
|
66
|
+
},
|
|
58
67
|
run: async (ctx) => {
|
|
59
68
|
const workflowCtx = ctx;
|
|
60
69
|
const workflowStartCwd = workflowCtx.cwd ?? process.cwd();
|
|
@@ -40,6 +40,7 @@ export type GoalWorkflowInputs = WorkflowInputValues & {
|
|
|
40
40
|
readonly acceptance_criteria?: string;
|
|
41
41
|
readonly max_turns: number;
|
|
42
42
|
readonly base_branch: string;
|
|
43
|
+
readonly git_worktree_dir: string;
|
|
43
44
|
readonly create_pr: boolean;
|
|
44
45
|
};
|
|
45
46
|
export type GoalWorkflowRunInputs = WorkflowInputValues & {
|
|
@@ -47,6 +48,7 @@ export type GoalWorkflowRunInputs = WorkflowInputValues & {
|
|
|
47
48
|
readonly acceptance_criteria?: string;
|
|
48
49
|
readonly max_turns?: number;
|
|
49
50
|
readonly base_branch?: string;
|
|
51
|
+
readonly git_worktree_dir?: string;
|
|
50
52
|
readonly create_pr?: boolean;
|
|
51
53
|
};
|
|
52
54
|
export type GoalWorkflowOutputs = WorkflowOutputValues & {
|
|
@@ -78,14 +78,14 @@ export async function runOpenClaudeDesignWorkflow(ctx: OpenClaudeDesignContext):
|
|
|
78
78
|
// strictly dominated in Atomic's benchmark (see ralph-models.ts). Opus stays
|
|
79
79
|
// at :xhigh here — visual quality, not $/task, is the objective for design.
|
|
80
80
|
const designModelConfig = {
|
|
81
|
-
model: "anthropic/claude-fable-5:
|
|
81
|
+
model: "anthropic/claude-fable-5:high",
|
|
82
82
|
fallbackModels: [
|
|
83
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
84
|
-
"anthropic/claude-opus-4-8:
|
|
83
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
84
|
+
"anthropic/claude-opus-4-8:high",
|
|
85
85
|
"zai/glm-5.2:xhigh",
|
|
86
86
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
87
|
-
"openrouter/anthropic/claude-fable-5:
|
|
88
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
87
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
88
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
89
89
|
"openrouter/sakana/fugu-ultra:high",
|
|
90
90
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
91
91
|
],
|
|
@@ -16,19 +16,19 @@ import { reviewDecisionSchema } from "./ralph-core.js";
|
|
|
16
16
|
// openrouter/z-ai mirror maps :xhigh exclusively, so it is always :xhigh.
|
|
17
17
|
|
|
18
18
|
export const promptEngineerModelConfig = {
|
|
19
|
-
model: "anthropic/claude-fable-5:
|
|
19
|
+
model: "anthropic/claude-fable-5:high",
|
|
20
20
|
fallbackModels: [
|
|
21
21
|
"openai-codex/gpt-5.5:xhigh",
|
|
22
22
|
"github-copilot/gpt-5.5:xhigh",
|
|
23
23
|
"openai/gpt-5.5:xhigh",
|
|
24
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
25
|
-
"anthropic/claude-opus-4-8:
|
|
24
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
25
|
+
"anthropic/claude-opus-4-8:high",
|
|
26
26
|
"zai/glm-5.2:xhigh",
|
|
27
27
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
28
|
-
"openrouter/anthropic/claude-fable-5:
|
|
28
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
29
29
|
"openrouter/sakana/fugu-ultra:high",
|
|
30
30
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
31
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
31
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
32
32
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
33
33
|
],
|
|
34
34
|
excludedTools: ["ask_user_question"],
|
|
@@ -53,38 +53,38 @@ export const researchModelConfig = {
|
|
|
53
53
|
};
|
|
54
54
|
|
|
55
55
|
export const orchestratorModelConfig = {
|
|
56
|
-
model: "anthropic/claude-fable-5:
|
|
56
|
+
model: "anthropic/claude-fable-5:high",
|
|
57
57
|
fallbackModels: [
|
|
58
58
|
"openai-codex/gpt-5.5:xhigh",
|
|
59
59
|
"github-copilot/gpt-5.5:xhigh",
|
|
60
60
|
"openai/gpt-5.5:xhigh",
|
|
61
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
62
|
-
"anthropic/claude-opus-4-8:
|
|
61
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
62
|
+
"anthropic/claude-opus-4-8:high",
|
|
63
63
|
"zai/glm-5.2:xhigh",
|
|
64
64
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
65
|
-
"openrouter/anthropic/claude-fable-5:
|
|
65
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
66
66
|
"openrouter/sakana/fugu-ultra:high",
|
|
67
67
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
68
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
68
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
69
69
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
70
70
|
],
|
|
71
71
|
excludedTools: ["ask_user_question"],
|
|
72
72
|
};
|
|
73
73
|
|
|
74
74
|
export const reviewerAModelConfig = {
|
|
75
|
-
model: "anthropic/claude-fable-5:
|
|
75
|
+
model: "anthropic/claude-fable-5:high",
|
|
76
76
|
fallbackModels: [
|
|
77
77
|
"openai-codex/gpt-5.5:xhigh",
|
|
78
78
|
"github-copilot/gpt-5.5:xhigh",
|
|
79
79
|
"openai/gpt-5.5:xhigh",
|
|
80
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
81
|
-
"anthropic/claude-opus-4-8:
|
|
80
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
81
|
+
"anthropic/claude-opus-4-8:high",
|
|
82
82
|
"zai/glm-5.2:xhigh",
|
|
83
83
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
84
|
-
"openrouter/anthropic/claude-fable-5:
|
|
84
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
85
85
|
"openrouter/sakana/fugu-ultra:high",
|
|
86
86
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
87
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
87
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
88
88
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
89
89
|
],
|
|
90
90
|
excludedTools: ["ask_user_question"],
|
|
@@ -96,15 +96,15 @@ export const reviewerBModelConfig = {
|
|
|
96
96
|
fallbackModels: [
|
|
97
97
|
"github-copilot/gpt-5.5:xhigh",
|
|
98
98
|
"openai/gpt-5.5:xhigh",
|
|
99
|
-
"anthropic/claude-fable-5:
|
|
100
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
101
|
-
"anthropic/claude-opus-4-8:
|
|
99
|
+
"anthropic/claude-fable-5:high",
|
|
100
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
101
|
+
"anthropic/claude-opus-4-8:high",
|
|
102
102
|
"zai/glm-5.2:xhigh",
|
|
103
103
|
"zai-coding-cn/glm-5.2:xhigh",
|
|
104
104
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
105
|
-
"openrouter/anthropic/claude-fable-5:
|
|
105
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
106
106
|
"openrouter/sakana/fugu-ultra:high",
|
|
107
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
107
|
+
"openrouter/anthropic/claude-opus-4-8:high",
|
|
108
108
|
"openrouter/z-ai/glm-5.2:xhigh"
|
|
109
109
|
],
|
|
110
110
|
excludedTools: ["ask_user_question"],
|
|
@@ -118,14 +118,14 @@ export const reviewerCModelConfig = {
|
|
|
118
118
|
"openai-codex/gpt-5.5:xhigh",
|
|
119
119
|
"github-copilot/gpt-5.5:xhigh",
|
|
120
120
|
"openai/gpt-5.5:xhigh",
|
|
121
|
-
"anthropic/claude-fable-5:
|
|
122
|
-
"github-copilot/claude-opus-4.8 (1m):
|
|
123
|
-
"anthropic/claude-opus-4-8:
|
|
121
|
+
"anthropic/claude-fable-5:high",
|
|
122
|
+
"github-copilot/claude-opus-4.8 (1m):high",
|
|
123
|
+
"anthropic/claude-opus-4-8:high",
|
|
124
124
|
"openrouter/sakana/fugu-ultra:high",
|
|
125
125
|
"openrouter/z-ai/glm-5.2:xhigh",
|
|
126
126
|
"openrouter/openai/gpt-5.5:xhigh",
|
|
127
|
-
"openrouter/anthropic/claude-fable-5:
|
|
128
|
-
"openrouter/anthropic/claude-opus-4-8:
|
|
127
|
+
"openrouter/anthropic/claude-fable-5:high",
|
|
128
|
+
"openrouter/anthropic/claude-opus-4-8:high"
|
|
129
129
|
],
|
|
130
130
|
excludedTools: ["ask_user_question"],
|
|
131
131
|
schema: reviewDecisionSchema,
|
|
@@ -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,8BAA8B,CAAC;AAMrE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA+FrI;AAGD,wBAAgB,6CAA6C,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ7H;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAMrF;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,EAC9E,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,IAAI,CAiBN;AAED;;GAEG;AAEH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CASnE;AAED;;GAEG;AAEH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,GAAG,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAqEhI;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;CAO7C,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check 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 && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\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: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\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\tif (this._overflowRecoveryAttempted) {\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\terrorMessage:\n\t\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", false);\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\n/**\n * Internal: remove the trailing overflow error from retry context if it is still present.\n */\n\nexport function _dropTrailingOverflowAssistantErrorIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role === \"assistant\" && (lastMsg as AssistantMessage).stopReason === \"error\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession, \n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport function _resumeAfterAutoCompaction(this: AgentSession): void {\n\tvoid this._runAgentContinue().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: Run auto-compaction with events.\n */\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing,\n\t\t// so compaction silently no-ops if the planner would be needed but credentials are absent.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._dropTrailingOverflowAssistantErrorIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingOverflowAssistantErrorIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|
|
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,8BAA8B,CAAC;AAMrE,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAE9F,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,UAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CA+FrI;AAGD,wBAAgB,6CAA6C,CAAC,IAAI,EAAE,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,GAAG,OAAO,CAQ7H;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAMrF;AAED;;GAEG;AAEH,wBAAgB,4CAA4C,CAAC,IAAI,EAAE,YAAY,EAC9E,MAAM,EAAE,UAAU,GAAG,WAAW,EAChC,SAAS,EAAE,OAAO,GAChB,IAAI,CAiBN;AAED;;GAEG;AAEH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CASnE;AAED;;GAEG;AAEH,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,GAAG,WAAW,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAsEhI;AAED;;GAEG;AAEH,eAAO,MAAM,iCAAiC;;;;;;;CAO7C,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check 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 && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\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: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\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\tif (this._overflowRecoveryAttempted) {\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\terrorMessage:\n\t\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", false);\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\n/**\n * Internal: remove the trailing overflow error from retry context if it is still present.\n */\n\nexport function _dropTrailingOverflowAssistantErrorIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role === \"assistant\" && (lastMsg as AssistantMessage).stopReason === \"error\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession, \n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport function _resumeAfterAutoCompaction(this: AgentSession): void {\n\tvoid this._runAgentContinue().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: Run auto-compaction with events.\n */\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._dropTrailingOverflowAssistantErrorIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingOverflowAssistantErrorIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|
|
@@ -161,8 +161,9 @@ export async function _runAutoCompaction(reason, willRetry) {
|
|
|
161
161
|
// Auth is resolved lazily: only called when the planner fallback is needed.
|
|
162
162
|
// This allows extension-provided deletion requests to run before auth is checked,
|
|
163
163
|
// enabling local extension compaction even when API credentials are unavailable.
|
|
164
|
-
// Auto-mode resolver returns undefined (rather than throwing) when auth is missing
|
|
165
|
-
//
|
|
164
|
+
// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;
|
|
165
|
+
// overflow recovery then falls back to deterministic no-auth eviction, while
|
|
166
|
+
// threshold compaction keeps the previous no-op behavior.
|
|
166
167
|
const model = this.model;
|
|
167
168
|
const result = await this._applyContextVerbatimCompaction({
|
|
168
169
|
resolvePlannerAuth: async () => {
|
|
@@ -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,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACnE,OAAO,EAAE,sBAAsB,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrG,OAAO,EAAE,gCAAgC,EAAE,MAA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EG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,gBAAgB;IAChB,6CAA6C;IAC7C,4CAA4C;IAC5C,4CAA4C;IAC5C,0BAA0B;IAC1B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check 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 && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\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: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\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\tif (this._overflowRecoveryAttempted) {\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\terrorMessage:\n\t\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", false);\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\n/**\n * Internal: remove the trailing overflow error from retry context if it is still present.\n */\n\nexport function _dropTrailingOverflowAssistantErrorIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role === \"assistant\" && (lastMsg as AssistantMessage).stopReason === \"error\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession, \n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport function _resumeAfterAutoCompaction(this: AgentSession): void {\n\tvoid this._runAgentContinue().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: Run auto-compaction with events.\n */\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing,\n\t\t// so compaction silently no-ops if the planner would be needed but credentials are absent.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._dropTrailingOverflowAssistantErrorIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingOverflowAssistantErrorIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-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AAgB;YACtB,MAAM;YACN,MAAM,EAAE,SAAS;YACjB,OAAO;YACP,SAAS,EAAE,KAAK;YAChB,YAAY,EAAE,OAAO;gBACpB,CAAC,CAAC,SAAS;gBACX,CAAC,CAAC,MAAM,KAAK,UAAU;oBACtB,CAAC,CAAC,qCAAqC,YAAY,EAAE;oBACrD,CAAC,CAAC,2BAA2B,YAAY,EAAE;SAC7C,CAAC,CAAC;IACJ,CAAC;YAAS,CAAC;QACV,IAAI,CAAC,8BAA8B,GAAG,SAAS,CAAC;IACjD,CAAC;AACF,CAAC;AAED;;GAEG;AAEH,MAAM,CAAC,MAAM,iCAAiC,GAAG;IAChD,gBAAgB;IAChB,6CAA6C;IAC7C,4CAA4C;IAC5C,4CAA4C;IAC5C,0BAA0B;IAC1B,kBAAkB;CAClB,CAAC","sourcesContent":["import type { AssistantMessage } from \"@earendil-works/pi-ai/compat\";\nimport { isContextOverflow } from \"@earendil-works/pi-ai/compat\";\nimport { getEffectiveInputBudget } from \"./context-window.ts\";\nimport { parseCopilotPromptLimitError } from \"./copilot-errors.ts\";\nimport { calculateContextTokens, estimateContextTokens, shouldCompact } from \"./compaction/index.ts\";\nimport { getLatestCompactionBoundaryEntry } from \"./session-manager.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nexport async function _checkCompaction(this: AgentSession, assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {\n\tconst settings = this.settingsManager.getCompactionSettings();\n\tif (!settings.enabled) return;\n\n\t// Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false\n\tif (skipAbortedCheck && assistantMessage.stopReason === \"aborted\") return;\n\n\tconst contextWindow = this.model?.contextWindow ?? 0;\n\n\t// Skip overflow check 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 && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;\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: Overflow - LLM returned context overflow error\n\t// When Copilot rejects a 1m client-budget prompt at a lower server cap (for example\n\t// because long-context/usage-based billing entitlement is missing), leave the friendly\n\t// error visible instead of auto-compacting down to a smaller server tier silently.\n\tif (sameModel && this._isCopilotServerCapBelowSelectedContextWindow(assistantMessage)) {\n\t\treturn;\n\t}\n\tif (sameModel && isContextOverflow(assistantMessage, contextWindow)) {\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\tif (this._overflowRecoveryAttempted) {\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\terrorMessage:\n\t\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});\n\t\t\treturn;\n\t\t}\n\n\t\tthis._overflowRecoveryAttempted = true;\n\t\t// Remove the error message from agent state (it IS saved to session for history,\n\t\t// but we don't want it in context for the retry)\n\t\tconst messages = this.agent.state.messages;\n\t\tif (messages.length > 0 && messages[messages.length - 1].role === \"assistant\") {\n\t\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t\t}\n\t\tawait this._runAutoCompaction(\"overflow\", willRetry);\n\t\treturn;\n\t}\n\n\t// Case 2: Threshold - context is getting large\n\t// For error messages (no usage data), estimate from last successful response.\n\t// This ensures sessions that hit persistent API errors (e.g. 529) can still compact.\n\tlet contextTokens: number;\n\tif (assistantMessage.stopReason === \"error\") {\n\t\tconst messages = this.agent.state.messages;\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) return; // No usage data at all\n\t\t// Verify the usage source is post-compaction. Kept pre-compaction messages\n\t\t// have stale usage reflecting the old (larger) context and would falsely\n\t\t// trigger compaction right after one just finished.\n\t\tconst usageMsg = messages[estimate.lastUsageIndex];\n\t\tif (\n\t\t\tcompactionBoundaryEntry &&\n\t\t\tusageMsg.role === \"assistant\" &&\n\t\t\t(usageMsg as AssistantMessage).timestamp <= new Date(compactionBoundaryEntry.timestamp).getTime()\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tcontextTokens = estimate.tokens;\n\t} else {\n\t\tcontextTokens = calculateContextTokens(assistantMessage.usage);\n\t}\n\t// Compact against the effective input budget (the hard prompt cap for providers like Copilot\n\t// that advertise a larger total window) so we compact before overrunning the server-side limit\n\t// rather than relying on reactive overflow recovery near the cap.\n\tconst compactionBudget = this.model ? getEffectiveInputBudget(this.model) : contextWindow;\n\tif (shouldCompact(contextTokens, compactionBudget, settings)) {\n\t\tawait this._runAutoCompaction(\"threshold\", false);\n\t}\n}\n\n\nexport function _isCopilotServerCapBelowSelectedContextWindow(this: AgentSession, assistantMessage: AssistantMessage): boolean {\n\tif (!this.model || this.model.provider !== \"github-copilot\" || !assistantMessage.errorMessage) return false;\n\tconst promptLimitError = parseCopilotPromptLimitError(assistantMessage.errorMessage);\n\t// Compare against the effective input budget (the model's real prompt cap), not the displayed\n\t// total window. A rejection at the prompt cap is a normal overflow we should compact-and-retry;\n\t// only a rejection *below* the cap (e.g. a missing long-context entitlement dropping the account\n\t// to a lower server tier) keeps the friendly error visible instead of silently compacting down.\n\treturn promptLimitError !== undefined && getEffectiveInputBudget(this.model) > promptLimitError.limitTokens;\n}\n\n/**\n * Internal: remove the trailing overflow error from retry context if it is still present.\n */\n\nexport function _dropTrailingOverflowAssistantErrorIfPresent(this: AgentSession): void {\n\tconst messages = this.agent.state.messages;\n\tconst lastMsg = messages[messages.length - 1];\n\tif (lastMsg?.role === \"assistant\" && (lastMsg as AssistantMessage).stopReason === \"error\") {\n\t\tthis.agent.state.messages = messages.slice(0, -1);\n\t}\n}\n\n/**\n * Internal: schedule a live post-event continuation probe after compaction_end listeners can flush queues.\n */\n\nexport function _schedulePostAutoCompactionContinuationProbe(this: AgentSession, \n\treason: \"overflow\" | \"threshold\",\n\twillRetry: boolean,\n): void {\n\tsetTimeout(() => {\n\t\tif (this.isCompacting || this.isStreaming) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._resumeAfterAutoCompaction();\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.agent.hasQueuedMessages()) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._resumeAfterAutoCompaction();\n\t}, 100);\n}\n\n/**\n * Internal: resume generation after successful auto-compaction only when active work remains.\n */\n\nexport function _resumeAfterAutoCompaction(this: AgentSession): void {\n\tvoid this._runAgentContinue().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: Run auto-compaction with events.\n */\n\nexport async function _runAutoCompaction(this: AgentSession, reason: \"overflow\" | \"threshold\", willRetry: boolean): Promise<void> {\n\tthis._emit({ type: \"compaction_start\", reason });\n\tthis._autoCompactionAbortController = new AbortController();\n\n\ttry {\n\t\tif (!this.model) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\t// Auth is resolved lazily: only called when the planner fallback is needed.\n\t\t// This allows extension-provided deletion requests to run before auth is checked,\n\t\t// enabling local extension compaction even when API credentials are unavailable.\n\t\t// Auto-mode resolver returns undefined (rather than throwing) when auth is missing;\n\t\t// overflow recovery then falls back to deterministic no-auth eviction, while\n\t\t// threshold compaction keeps the previous no-op behavior.\n\t\tconst model = this.model;\n\t\tconst result = await this._applyContextVerbatimCompaction({\n\t\t\tresolvePlannerAuth: async () => {\n\t\t\t\tconst authResult = await this._modelRegistry.getApiKeyAndHeaders(model);\n\t\t\t\tif (!authResult.ok || !authResult.apiKey) {\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t\treturn { apiKey: authResult.apiKey, headers: authResult.headers };\n\t\t\t},\n\t\t\tabortController: this._autoCompactionAbortController,\n\t\t\tbackupLabel: reason === \"overflow\" ? \"overflow-auto-compact\" : \"auto-compact\",\n\t\t\treason,\n\t\t});\n\t\tif (!result) {\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});\n\t\t\treturn;\n\t\t}\n\n\t\tif (reason === \"overflow\" && willRetry) {\n\t\t\tthis._dropTrailingOverflowAssistantErrorIfPresent();\n\t\t}\n\n\t\tthis._emit({ type: \"compaction_end\", reason, result, aborted: false, willRetry });\n\t\tthis._schedulePostAutoCompactionContinuationProbe(reason, willRetry);\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"compaction failed\";\n\t\tconst aborted = errorMessage === \"Compaction cancelled\" || (error instanceof Error && error.name === \"AbortError\");\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\terrorMessage: aborted\n\t\t\t\t? undefined\n\t\t\t\t: reason === \"overflow\"\n\t\t\t\t\t? `Context overflow recovery failed: ${errorMessage}`\n\t\t\t\t\t: `Auto-compaction failed: ${errorMessage}`,\n\t\t});\n\t} finally {\n\t\tthis._autoCompactionAbortController = undefined;\n\t}\n}\n\n/**\n * Toggle auto-compaction setting.\n */\n\nexport const agentSessionAutoCompactionMethods = {\n\t_checkCompaction,\n\t_isCopilotServerCapBelowSelectedContextWindow,\n\t_dropTrailingOverflowAssistantErrorIfPresent,\n\t_schedulePostAutoCompactionContinuationProbe,\n\t_resumeAfterAutoCompaction,\n\t_runAutoCompaction,\n};\n"]}
|