@kenkaiiii/ggcoder 5.109.0 → 6.0.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/README.md +1 -1
- package/assets/skills/gg-guide/references/code-mode.md +3 -0
- package/dist/app-sidecar/branch-routes.d.ts +42 -0
- package/dist/app-sidecar/branch-routes.js +189 -0
- package/dist/app-sidecar/branch-routes.js.map +1 -0
- package/dist/app-sidecar/git-branches.d.ts +81 -0
- package/dist/app-sidecar/git-branches.js +270 -0
- package/dist/app-sidecar/git-branches.js.map +1 -0
- package/dist/app-sidecar/history-routes.js +3 -0
- package/dist/app-sidecar/history-routes.js.map +1 -1
- package/dist/app-sidecar/history.d.ts +2 -0
- package/dist/app-sidecar/history.js.map +1 -1
- package/dist/app-sidecar/repo-polls.d.ts +3 -1
- package/dist/app-sidecar/repo-polls.js +9 -1
- package/dist/app-sidecar/repo-polls.js.map +1 -1
- package/dist/app-sidecar/route-context.d.ts +1 -0
- package/dist/app-sidecar/session-types.d.ts +5 -0
- package/dist/app-sidecar/workspace-routes.js +12 -2
- package/dist/app-sidecar/workspace-routes.js.map +1 -1
- package/dist/app-sidecar/worktrees.d.ts +100 -0
- package/dist/app-sidecar/worktrees.js +260 -0
- package/dist/app-sidecar/worktrees.js.map +1 -0
- package/dist/app-sidecar-sessions.d.ts +3 -1
- package/dist/app-sidecar-sessions.js +6 -4
- package/dist/app-sidecar-sessions.js.map +1 -1
- package/dist/app-sidecar.js +159 -7
- package/dist/app-sidecar.js.map +1 -1
- package/dist/core/agent-session.d.ts +79 -0
- package/dist/core/agent-session.js +206 -46
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/checkout-record.d.ts +22 -0
- package/dist/core/checkout-record.js +68 -0
- package/dist/core/checkout-record.js.map +1 -0
- package/dist/core/claude-code/events.d.ts +2 -0
- package/dist/core/claude-code/events.js +27 -2
- package/dist/core/claude-code/events.js.map +1 -1
- package/dist/core/claude-code/live-session.d.ts +2 -0
- package/dist/core/claude-code/live-session.js +7 -1
- package/dist/core/claude-code/live-session.js.map +1 -1
- package/dist/core/compaction/tool-result-pruner.d.ts +11 -0
- package/dist/core/compaction/tool-result-pruner.js +26 -0
- package/dist/core/compaction/tool-result-pruner.js.map +1 -1
- package/dist/core/destructive-git-guard.d.ts +23 -0
- package/dist/core/destructive-git-guard.js +11 -8
- package/dist/core/destructive-git-guard.js.map +1 -1
- package/dist/core/event-bus.d.ts +11 -0
- package/dist/core/event-bus.js +10 -0
- package/dist/core/event-bus.js.map +1 -1
- package/dist/core/lsp/servers.js +1 -1
- package/dist/core/project-discovery.d.ts +3 -1
- package/dist/core/project-discovery.js +5 -3
- package/dist/core/project-discovery.js.map +1 -1
- package/dist/core/regrounding.d.ts +9 -1
- package/dist/core/regrounding.js +46 -6
- package/dist/core/regrounding.js.map +1 -1
- package/dist/core/session-manager.d.ts +3 -1
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/shared-checkout-guard.d.ts +78 -0
- package/dist/core/shared-checkout-guard.js +219 -0
- package/dist/core/shared-checkout-guard.js.map +1 -0
- package/dist/modes/subagent-worker-mode.js +4 -0
- package/dist/modes/subagent-worker-mode.js.map +1 -1
- package/dist/system-prompt.js +3 -1
- package/dist/system-prompt.js.map +1 -1
- package/dist/tools/ask-user.js +2 -1
- package/dist/tools/ask-user.js.map +1 -1
- package/dist/tools/bash.d.ts +3 -1
- package/dist/tools/bash.js +19 -7
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/enter-plan.js +2 -1
- package/dist/tools/enter-plan.js.map +1 -1
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +1 -1
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/prompt-hints.js +1 -1
- package/dist/tools/prompt-hints.js.map +1 -1
- package/dist/ui/App.js +2 -2
- package/dist/ui/App.js.map +1 -1
- package/dist/ui/hooks/useAgentLoop.d.ts +1 -1
- package/dist/ui/hooks/useAgentLoop.js +10 -1
- package/dist/ui/hooks/useAgentLoop.js.map +1 -1
- package/dist/utils/git.d.ts +7 -0
- package/dist/utils/git.js +12 -1
- package/dist/utils/git.js.map +1 -1
- package/package.json +12 -12
|
@@ -48,7 +48,7 @@ import { decidePlanStepCompaction, DEFAULT_CACHE_WRITE_READ_RATIO, PLAN_STEP_KEE
|
|
|
48
48
|
import { extractPlanSteps, findCompletedMarkers } from "../utils/plan-steps.js";
|
|
49
49
|
import { readFileSync } from "node:fs";
|
|
50
50
|
import { clampThinkingForPlanMode } from "./thinking-level.js";
|
|
51
|
-
import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
|
|
51
|
+
import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, stablePrefixEnd, } from "./compaction/tool-result-pruner.js";
|
|
52
52
|
import { discoverAgents } from "./agents.js";
|
|
53
53
|
import { enhancePrompt } from "../utils/prompt-enhancer.js";
|
|
54
54
|
import { assistantText, renderTranscript } from "./claude-code/events.js";
|
|
@@ -57,7 +57,7 @@ import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, c
|
|
|
57
57
|
import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
|
|
58
58
|
import { detectLanguages, detectProjectStack } from "./language-detector.js";
|
|
59
59
|
import { buildLoopBreakMessage } from "./loop-breaker.js";
|
|
60
|
-
import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
|
|
60
|
+
import { buildRegroundingMessage, recordUserDecision, requestTextForRegrounding, } from "./regrounding.js";
|
|
61
61
|
import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, parseSemanticLoopVerdict, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
|
|
62
62
|
import { buildEnvDeltaMessage, buildLanguageUpdateMessage } from "./env-delta.js";
|
|
63
63
|
import { buildUserShellContextText } from "./user-shell-context.js";
|
|
@@ -66,6 +66,7 @@ import { listProjectFiles } from "./project-files.js";
|
|
|
66
66
|
import { wrapSteeringText, buildNotificationSteeringText, buildIdleWakeNotificationText, STEERING_PREFIX, } from "./steering.js";
|
|
67
67
|
import { AgentNotificationQueue } from "./agent-notifications.js";
|
|
68
68
|
import { VerificationGate, VERIFICATION_STATE_KIND } from "./verification-gate.js";
|
|
69
|
+
import { CHECKOUT_RECORD_KIND, latestCheckoutRecord, } from "./checkout-record.js";
|
|
69
70
|
import { findUserSessionPrompt, getUserSessionPrompt } from "./session-preview.js";
|
|
70
71
|
import { normalizeMessageImages } from "./message-images.js";
|
|
71
72
|
import { loadStreamRules } from "./stream-rules.js";
|
|
@@ -314,9 +315,15 @@ export class AgentSession {
|
|
|
314
315
|
deferredCompactionPending = false;
|
|
315
316
|
/** Latest provider count, anchored to the assistant response it measured. */
|
|
316
317
|
providerContext = null;
|
|
318
|
+
/** Where the last prune made history stable; becomes the cache anchor on the next step. */
|
|
319
|
+
pendingCacheAnchor = null;
|
|
320
|
+
/** The message currently carrying `cacheAnchor` (see applyPendingCacheAnchor). */
|
|
321
|
+
cacheAnchored = null;
|
|
317
322
|
/** See {@link toolDefinitionChars}. */
|
|
318
323
|
toolCharsCache = null;
|
|
319
324
|
originalRequest = "";
|
|
325
|
+
/** The user's own ask_user answers this run; they scope the pinned request. */
|
|
326
|
+
runUserDecisions = [];
|
|
320
327
|
// Messages queued by the user while a run is in flight. Drained at the
|
|
321
328
|
// mid-loop steering boundary (user steering wins over the hooks), mirroring
|
|
322
329
|
// the TUI's getSteeringMessages. Each entry carries its own attachments so a
|
|
@@ -374,9 +381,12 @@ export class AgentSession {
|
|
|
374
381
|
* transport-specific windows (e.g. OpenAI Codex OAuth's smaller window)
|
|
375
382
|
* without re-resolving credentials on every poll. */
|
|
376
383
|
lastAccountId;
|
|
384
|
+
/** The branch and checkout this conversation is on (core/checkout-record.ts). */
|
|
385
|
+
checkoutRecord = null;
|
|
377
386
|
baseUrl;
|
|
378
387
|
maxTokens;
|
|
379
388
|
thinkingLevel;
|
|
389
|
+
thinkingDisplay;
|
|
380
390
|
customSystemPrompt;
|
|
381
391
|
/** Sub-agent definition body composed into the standard prompt scaffolding. */
|
|
382
392
|
agentPrompt;
|
|
@@ -460,6 +470,7 @@ export class AgentSession {
|
|
|
460
470
|
this.baseUrl = options.baseUrl;
|
|
461
471
|
this.maxTokens = this.resolveMaxTokens(options.model);
|
|
462
472
|
this.thinkingLevel = options.thinkingLevel;
|
|
473
|
+
this.thinkingDisplay = options.thinkingDisplay;
|
|
463
474
|
this.customSystemPrompt = options.systemPrompt;
|
|
464
475
|
this.agentPrompt = options.agentPrompt;
|
|
465
476
|
}
|
|
@@ -570,6 +581,7 @@ export class AgentSession {
|
|
|
570
581
|
}),
|
|
571
582
|
getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
|
|
572
583
|
getBashPath: () => this.settingsManager.get("bashPath"),
|
|
584
|
+
getCheckoutSharers: this.opts.getCheckoutSharers,
|
|
573
585
|
getNetworkPolicy: () => ({
|
|
574
586
|
mode: this.settingsManager.get("networkMode"),
|
|
575
587
|
allow: this.settingsManager.get("networkAllow"),
|
|
@@ -1093,19 +1105,7 @@ export class AgentSession {
|
|
|
1093
1105
|
accountId: creds?.accountId,
|
|
1094
1106
|
approvedPlanPath: this.approvedPlanPath,
|
|
1095
1107
|
});
|
|
1096
|
-
|
|
1097
|
-
if (this.providerContext) {
|
|
1098
|
-
const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
|
|
1099
|
-
if (anchorIndex >= 0) {
|
|
1100
|
-
activeTokens = calculateActiveContextTokens(this.messages, {
|
|
1101
|
-
usage: this.providerContext.usage,
|
|
1102
|
-
pendingMessages: this.messages.slice(anchorIndex + 1),
|
|
1103
|
-
});
|
|
1104
|
-
}
|
|
1105
|
-
else {
|
|
1106
|
-
this.providerContext = null;
|
|
1107
|
-
}
|
|
1108
|
-
}
|
|
1108
|
+
const activeTokens = this.idleActiveContextTokens();
|
|
1109
1109
|
log("INFO", "compaction", "Pre-run compaction decision", {
|
|
1110
1110
|
provider: this.provider,
|
|
1111
1111
|
model: this.model,
|
|
@@ -1118,8 +1118,7 @@ export class AgentSession {
|
|
|
1118
1118
|
try {
|
|
1119
1119
|
await this.compact(creds, "automatic");
|
|
1120
1120
|
if (this.lastCompactionCompacted) {
|
|
1121
|
-
|
|
1122
|
-
this.compactionOccurred = true;
|
|
1121
|
+
this.markCompacted();
|
|
1123
1122
|
this.compactionRetryAfter = 0;
|
|
1124
1123
|
}
|
|
1125
1124
|
else {
|
|
@@ -1195,6 +1194,7 @@ export class AgentSession {
|
|
|
1195
1194
|
claudeCode: {
|
|
1196
1195
|
...process,
|
|
1197
1196
|
maxSeedChars: CLAUDE_CODE_SEED_CHARS,
|
|
1197
|
+
...(this.thinkingDisplay ? { thinkingDisplay: this.thinkingDisplay } : {}),
|
|
1198
1198
|
...(resume ? { resume } : {}),
|
|
1199
1199
|
...(title ? { title } : {}),
|
|
1200
1200
|
onSessionId: (id) => {
|
|
@@ -1634,6 +1634,12 @@ export class AgentSession {
|
|
|
1634
1634
|
this.compactionOccurred = true;
|
|
1635
1635
|
}
|
|
1636
1636
|
this.originalRequest = originalRequest;
|
|
1637
|
+
this.runUserDecisions = [];
|
|
1638
|
+
}
|
|
1639
|
+
/** The context was just summarized: arm a fresh re-ground note, even if one already ran this run. */
|
|
1640
|
+
markCompacted() {
|
|
1641
|
+
this.compactionOccurred = true;
|
|
1642
|
+
this.regroundingInjected = false;
|
|
1637
1643
|
}
|
|
1638
1644
|
/**
|
|
1639
1645
|
* Fold one agent event into the hook stat accumulators. Pure bookkeeping —
|
|
@@ -1664,6 +1670,9 @@ export class AgentSession {
|
|
|
1664
1670
|
if (safetyRule)
|
|
1665
1671
|
this.recordSafetyBlock(safetyRule, name, args, event.details);
|
|
1666
1672
|
this.loopMonitor.recordToolEnd(name, args, event.result, event.isError);
|
|
1673
|
+
if (name === "ask_user" && !event.isError) {
|
|
1674
|
+
this.runUserDecisions = recordUserDecision(this.runUserDecisions, event.result);
|
|
1675
|
+
}
|
|
1667
1676
|
const verificationChanged = await this.verificationTracker.recordToolCallEnd(event, call, this.planModeRef.current);
|
|
1668
1677
|
if (verificationChanged)
|
|
1669
1678
|
await this.persistVerificationState();
|
|
@@ -1907,7 +1916,7 @@ export class AgentSession {
|
|
|
1907
1916
|
if (!this.regroundingInjected && this.compactionOccurred) {
|
|
1908
1917
|
this.regroundingInjected = true;
|
|
1909
1918
|
this.eventBus.emit("hook", { kind: "regrounding" });
|
|
1910
|
-
return [buildRegroundingMessage(this.originalRequest)];
|
|
1919
|
+
return [buildRegroundingMessage(this.originalRequest, this.runUserDecisions)];
|
|
1911
1920
|
}
|
|
1912
1921
|
return null;
|
|
1913
1922
|
}
|
|
@@ -2452,32 +2461,21 @@ export class AgentSession {
|
|
|
2452
2461
|
};
|
|
2453
2462
|
let activeTokens = measureActiveTokens();
|
|
2454
2463
|
// Cheap stale-tool-output pruning before the expensive LLM
|
|
2455
|
-
// compaction check
|
|
2456
|
-
//
|
|
2457
|
-
//
|
|
2458
|
-
//
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
freedTokens: String(pruneResult.freedTokens),
|
|
2471
|
-
});
|
|
2472
|
-
// The measured size counted the pruned content, so take the
|
|
2473
|
-
// freed tokens off it. Never swap the provider's count for a
|
|
2474
|
-
// whole-history estimate here: that estimate rides a shared
|
|
2475
|
-
// chars-per-token ratio, and it once read a 234K-token MiMo
|
|
2476
|
-
// context (23% of 1M) as ~400K and compacted it against a 340K
|
|
2477
|
-
// trigger.
|
|
2478
|
-
activeTokens = Math.max(0, activeTokens - pruneResult.freedTokens);
|
|
2479
|
-
}
|
|
2480
|
-
}
|
|
2464
|
+
// compaction check (see pruneToolOutputsIfDue). First move the
|
|
2465
|
+
// cache anchor the last prune left pending, never in the request
|
|
2466
|
+
// that pruned: that one still reads through the previous anchor.
|
|
2467
|
+
// The new anchor's cache entry is created by reading the previous
|
|
2468
|
+
// request's tail, so a prune in this same step (which edits history
|
|
2469
|
+
// before that tail) waits one step.
|
|
2470
|
+
const freedTokens = this.applyPendingCacheAnchor(messages)
|
|
2471
|
+
? 0
|
|
2472
|
+
: this.pruneToolOutputsIfDue(messages, activeTokens, policy.targetTokens);
|
|
2473
|
+
// The measured size counted the pruned content, so take the freed
|
|
2474
|
+
// tokens off it. Never swap the provider's count for a
|
|
2475
|
+
// whole-history estimate here: that estimate rides a shared
|
|
2476
|
+
// chars-per-token ratio, and it once read a 234K-token MiMo context
|
|
2477
|
+
// (23% of 1M) as ~400K and compacted it against a 340K trigger.
|
|
2478
|
+
activeTokens = Math.max(0, activeTokens - freedTokens);
|
|
2481
2479
|
if (Date.now() < this.compactionRetryAfter)
|
|
2482
2480
|
return messages;
|
|
2483
2481
|
// An approved plan runs as ONE run, so step boundaries are only
|
|
@@ -2523,7 +2521,7 @@ export class AgentSession {
|
|
|
2523
2521
|
return messages;
|
|
2524
2522
|
}
|
|
2525
2523
|
this.compactionRetryAfter = 0;
|
|
2526
|
-
this.
|
|
2524
|
+
this.markCompacted();
|
|
2527
2525
|
return this.messages;
|
|
2528
2526
|
},
|
|
2529
2527
|
});
|
|
@@ -2832,6 +2830,7 @@ export class AgentSession {
|
|
|
2832
2830
|
this.currentLeafId = loaded.header.leafId;
|
|
2833
2831
|
this.setSessionPath(loaded.path);
|
|
2834
2832
|
this.markers.restore(loaded.entries, loaded.header.leafId);
|
|
2833
|
+
this.checkoutRecord = latestCheckoutRecord(loaded.entries) ?? this.checkoutRecord;
|
|
2835
2834
|
this.lastPersistedIndex = this.messages.length;
|
|
2836
2835
|
this.providerContext = null;
|
|
2837
2836
|
await this.subAgentManager?.rebindParentSession(this.sessionId);
|
|
@@ -2873,6 +2872,8 @@ export class AgentSession {
|
|
|
2873
2872
|
this.lastPersistedIndex = this.messages.length;
|
|
2874
2873
|
await this.markers.rePersistAll();
|
|
2875
2874
|
await this.persistVerificationState();
|
|
2875
|
+
// A compaction checkpoint is a new file: the conversation's branch must follow it.
|
|
2876
|
+
await this.persistCheckoutRecord();
|
|
2876
2877
|
await this.persistAppMarker("compaction", {
|
|
2877
2878
|
originalCount: result.originalCount,
|
|
2878
2879
|
newCount: result.newCount,
|
|
@@ -3732,6 +3733,16 @@ export class AgentSession {
|
|
|
3732
3733
|
listBackgroundProcesses() {
|
|
3733
3734
|
return this.processManager?.list() ?? [];
|
|
3734
3735
|
}
|
|
3736
|
+
/**
|
|
3737
|
+
* Start a background process on the host's behalf (a new worktree's setup),
|
|
3738
|
+
* listed with the agent's own background tasks. Null without a process manager.
|
|
3739
|
+
*/
|
|
3740
|
+
async startBackgroundProcess(command, cwd = this.cwd) {
|
|
3741
|
+
if (!this.processManager)
|
|
3742
|
+
return null;
|
|
3743
|
+
const started = await this.processManager.start(command, cwd);
|
|
3744
|
+
return { id: started.id, pid: started.pid };
|
|
3745
|
+
}
|
|
3735
3746
|
/** Stop a background process by id. Returns a human-readable status string. */
|
|
3736
3747
|
async killBackgroundProcess(id) {
|
|
3737
3748
|
if (!this.processManager)
|
|
@@ -4248,6 +4259,42 @@ export class AgentSession {
|
|
|
4248
4259
|
data: this.opts.completionReview.snapshot(),
|
|
4249
4260
|
});
|
|
4250
4261
|
}
|
|
4262
|
+
/**
|
|
4263
|
+
* A chat row saying where this conversation now works ("Opened on branch x in
|
|
4264
|
+
* its own worktree"), live and on every later restore of the transcript.
|
|
4265
|
+
*/
|
|
4266
|
+
noteCheckout(text) {
|
|
4267
|
+
this.eventBus.emit("checkout_notice", { text });
|
|
4268
|
+
void this.persistAppMarker("checkout", { text }).catch(() => { });
|
|
4269
|
+
}
|
|
4270
|
+
/** The branch and checkout this conversation last recorded, or null. */
|
|
4271
|
+
getCheckoutRecord() {
|
|
4272
|
+
return this.checkoutRecord;
|
|
4273
|
+
}
|
|
4274
|
+
/**
|
|
4275
|
+
* Remember the branch this conversation is on, so resuming it later opens
|
|
4276
|
+
* that branch (see core/checkout-record.ts). Unchanged records write nothing.
|
|
4277
|
+
*/
|
|
4278
|
+
async recordCheckout(record) {
|
|
4279
|
+
const previous = this.checkoutRecord;
|
|
4280
|
+
if (previous?.branch === record.branch && previous.cwd === record.cwd)
|
|
4281
|
+
return;
|
|
4282
|
+
this.checkoutRecord = { ...record };
|
|
4283
|
+
await this.persistCheckoutRecord();
|
|
4284
|
+
}
|
|
4285
|
+
async persistCheckoutRecord() {
|
|
4286
|
+
if (!this.sessionPath || !this.checkoutRecord)
|
|
4287
|
+
return;
|
|
4288
|
+
const entry = {
|
|
4289
|
+
type: "custom",
|
|
4290
|
+
kind: CHECKOUT_RECORD_KIND,
|
|
4291
|
+
id: crypto.randomUUID(),
|
|
4292
|
+
parentId: null,
|
|
4293
|
+
timestamp: new Date().toISOString(),
|
|
4294
|
+
data: { ...this.checkoutRecord },
|
|
4295
|
+
};
|
|
4296
|
+
await this.sessionManager.appendEntry(this.sessionPath, entry);
|
|
4297
|
+
}
|
|
4251
4298
|
async persistVerificationState() {
|
|
4252
4299
|
if (this.opts.completionReview)
|
|
4253
4300
|
await this.persistCompletionReviewState();
|
|
@@ -4439,6 +4486,106 @@ export class AgentSession {
|
|
|
4439
4486
|
}
|
|
4440
4487
|
/** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
|
|
4441
4488
|
claudeCodeLive = null;
|
|
4489
|
+
/**
|
|
4490
|
+
* Context size between runs: the last provider usage plus messages appended
|
|
4491
|
+
* after it, or undefined when there is no usable sample (callers estimate).
|
|
4492
|
+
* Same measurement the pre-run compaction check makes.
|
|
4493
|
+
*/
|
|
4494
|
+
idleActiveContextTokens() {
|
|
4495
|
+
if (!this.providerContext)
|
|
4496
|
+
return undefined;
|
|
4497
|
+
const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
|
|
4498
|
+
if (anchorIndex < 0) {
|
|
4499
|
+
this.providerContext = null;
|
|
4500
|
+
return undefined;
|
|
4501
|
+
}
|
|
4502
|
+
return calculateActiveContextTokens(this.messages, {
|
|
4503
|
+
usage: this.providerContext.usage,
|
|
4504
|
+
pendingMessages: this.messages.slice(anchorIndex + 1),
|
|
4505
|
+
});
|
|
4506
|
+
}
|
|
4507
|
+
/**
|
|
4508
|
+
* Prune stale tool outputs in place once the context is big enough for the
|
|
4509
|
+
* freed tokens to be worth a cache rewrite (a larger share on a warm cache,
|
|
4510
|
+
* see pruneMinimumTokens). In-place mutation preserves usage anchors; the
|
|
4511
|
+
* retained usage is dropped since it counted the pruned content. Shared by
|
|
4512
|
+
* the in-flight context transform and prewarm so both send the same prefix.
|
|
4513
|
+
* Returns the freed tokens (0 when nothing was pruned).
|
|
4514
|
+
*/
|
|
4515
|
+
pruneToolOutputsIfDue(messages, activeTokens, targetTokens) {
|
|
4516
|
+
if (!shouldPruneToolResults(activeTokens, targetTokens))
|
|
4517
|
+
return 0;
|
|
4518
|
+
const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
|
|
4519
|
+
const pruneResult = pruneStaleToolResults(messages, {
|
|
4520
|
+
minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, targetTokens),
|
|
4521
|
+
});
|
|
4522
|
+
if (!pruneResult.pruned)
|
|
4523
|
+
return 0;
|
|
4524
|
+
this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
|
|
4525
|
+
this.providerContext = null;
|
|
4526
|
+
this.pendingCacheAnchor = stablePrefixEnd(messages) ?? null;
|
|
4527
|
+
log("INFO", "compaction", "Pruned stale tool outputs", {
|
|
4528
|
+
prunedResults: String(pruneResult.prunedResults),
|
|
4529
|
+
compactedToolCalls: String(pruneResult.compactedToolCalls),
|
|
4530
|
+
freedTokens: String(pruneResult.freedTokens),
|
|
4531
|
+
});
|
|
4532
|
+
return pruneResult.freedTokens;
|
|
4533
|
+
}
|
|
4534
|
+
/**
|
|
4535
|
+
* Mark where the last prune made history stable (`Message.cacheAnchor`), so
|
|
4536
|
+
* the provider can keep a cache breakpoint there. Without it every prune on a
|
|
4537
|
+
* 5-min route re-sent everything after the last entry the tail's lookback
|
|
4538
|
+
* finds; in live sessions a prune freed ~24K tokens and re-wrote ~400K. gg-ai
|
|
4539
|
+
* decides per route whether the hint is used (not on 1-h routes). Returns
|
|
4540
|
+
* true when the anchor moved.
|
|
4541
|
+
*/
|
|
4542
|
+
applyPendingCacheAnchor(messages) {
|
|
4543
|
+
const next = this.pendingCacheAnchor;
|
|
4544
|
+
this.pendingCacheAnchor = null;
|
|
4545
|
+
if (!next || next === this.cacheAnchored || !messages.includes(next))
|
|
4546
|
+
return false;
|
|
4547
|
+
if (this.cacheAnchored)
|
|
4548
|
+
delete this.cacheAnchored.cacheAnchor;
|
|
4549
|
+
next.cacheAnchor = true;
|
|
4550
|
+
this.cacheAnchored = next;
|
|
4551
|
+
return true;
|
|
4552
|
+
}
|
|
4553
|
+
/**
|
|
4554
|
+
* Apply the next request's context policy before warming: report when its
|
|
4555
|
+
* pre-run check will compact, otherwise prune now exactly as its first model
|
|
4556
|
+
* step would. The cache is cold here (prewarm only runs once it has lapsed),
|
|
4557
|
+
* so the prune uses the cold-cache floor, as the request would without the
|
|
4558
|
+
* prewarm; afterwards the warm cache's larger floor keeps that request from
|
|
4559
|
+
* pruning again. Prewarm is Anthropic-only, so the cached account id never
|
|
4560
|
+
* changes the window.
|
|
4561
|
+
*/
|
|
4562
|
+
prepareContextForPrewarm() {
|
|
4563
|
+
if (!this.settingsManager.get("autoCompact"))
|
|
4564
|
+
return "ready";
|
|
4565
|
+
// A post-turn compaction is about to replace this history.
|
|
4566
|
+
if (this.postTurnCompaction)
|
|
4567
|
+
return "compaction_due";
|
|
4568
|
+
const contextWindow = getContextWindow(this.model, {
|
|
4569
|
+
provider: this.provider,
|
|
4570
|
+
accountId: this.lastAccountId,
|
|
4571
|
+
});
|
|
4572
|
+
const policy = resolveCompactionPolicy({
|
|
4573
|
+
provider: this.provider,
|
|
4574
|
+
model: this.model,
|
|
4575
|
+
contextWindow,
|
|
4576
|
+
threshold: this.settingsManager.get("compactThreshold"),
|
|
4577
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
4578
|
+
accountId: this.lastAccountId,
|
|
4579
|
+
approvedPlanPath: this.approvedPlanPath,
|
|
4580
|
+
});
|
|
4581
|
+
const activeTokens = this.idleActiveContextTokens();
|
|
4582
|
+
if (Date.now() >= this.compactionRetryAfter &&
|
|
4583
|
+
shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
|
|
4584
|
+
return "compaction_due";
|
|
4585
|
+
}
|
|
4586
|
+
this.pruneToolOutputsIfDue(this.messages, activeTokens ?? calculateActiveContextTokens(this.messages), policy.targetTokens);
|
|
4587
|
+
return "ready";
|
|
4588
|
+
}
|
|
4442
4589
|
/**
|
|
4443
4590
|
* Best-effort Anthropic prompt-cache prewarm before the user's next turn
|
|
4444
4591
|
* (desktop app calls this on the first keystroke after opening a chat or an
|
|
@@ -4476,6 +4623,16 @@ export class AgentSession {
|
|
|
4476
4623
|
return { ok: false, reason: "run_active" };
|
|
4477
4624
|
if (this.prewarmController)
|
|
4478
4625
|
return { ok: false, reason: "in_flight" };
|
|
4626
|
+
// Warm what the next request will actually send. Its pre-run check compacts
|
|
4627
|
+
// an over-trigger history (rewriting the whole prefix, so warming now is
|
|
4628
|
+
// waste), and its first model step prunes stale tool outputs when due:
|
|
4629
|
+
// apply that same in-place prune now, so the request finds nothing left to
|
|
4630
|
+
// prune and the warmed prefix matches it. Measured with a live A/B: a 700K
|
|
4631
|
+
// session wrote its full history at the 1-h price here, then rewrote it on
|
|
4632
|
+
// the very next request.
|
|
4633
|
+
if (this.prepareContextForPrewarm() === "compaction_due") {
|
|
4634
|
+
return { ok: false, reason: "compaction_due" };
|
|
4635
|
+
}
|
|
4479
4636
|
// End at the last user/tool message: the next real turn appends a new user
|
|
4480
4637
|
// message after the trailing assistant reply, and its cache lookback hits
|
|
4481
4638
|
// the entry written at this boundary. A request must end on a user turn.
|
|
@@ -4699,6 +4856,7 @@ export class AgentSession {
|
|
|
4699
4856
|
}
|
|
4700
4857
|
this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
|
|
4701
4858
|
this.verificationTracker.clearBackground();
|
|
4859
|
+
this.checkoutRecord = latestCheckoutRecord(loaded.entries);
|
|
4702
4860
|
if (savedVerification?.type === "custom") {
|
|
4703
4861
|
this.verificationGate.restore(savedVerification.data);
|
|
4704
4862
|
}
|
|
@@ -4854,12 +5012,14 @@ export class AgentSession {
|
|
|
4854
5012
|
if (!this.sessionPath)
|
|
4855
5013
|
return;
|
|
4856
5014
|
const entryId = crypto.randomUUID();
|
|
5015
|
+
// The cache-anchor hint only holds for the live run; never store it.
|
|
5016
|
+
const { cacheAnchor: _cacheAnchor, ...stored } = message;
|
|
4857
5017
|
const entry = {
|
|
4858
5018
|
type: "message",
|
|
4859
5019
|
id: entryId,
|
|
4860
5020
|
parentId: this.currentLeafId,
|
|
4861
5021
|
timestamp: new Date().toISOString(),
|
|
4862
|
-
message,
|
|
5022
|
+
message: stored,
|
|
4863
5023
|
};
|
|
4864
5024
|
await this.sessionManager.appendEntry(this.sessionPath, entry);
|
|
4865
5025
|
this.currentLeafId = entryId;
|