@kenkaiiii/ggcoder 5.108.0 → 6.0.0
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 +2 -2
- 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/cli.js +9 -4
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session.d.ts +72 -0
- package/dist/core/agent-session.js +249 -88
- 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/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 +4 -0
- package/dist/core/event-bus.js +1 -0
- package/dist/core/event-bus.js.map +1 -1
- package/dist/core/lsp/servers.js +1 -1
- package/dist/core/mcp/defaults.d.ts +7 -0
- package/dist/core/mcp/defaults.js +10 -0
- package/dist/core/mcp/defaults.js.map +1 -1
- package/dist/core/mcp/index.d.ts +1 -1
- package/dist/core/mcp/index.js +1 -1
- package/dist/core/mcp/index.js.map +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/tools/bash.d.ts +3 -1
- package/dist/tools/bash.js +19 -7
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/browser-session.d.ts +16 -1
- package/dist/tools/browser-session.js +87 -3
- package/dist/tools/browser-session.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/ui/App.js +58 -53
- 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
|
@@ -13,7 +13,7 @@ import { loadWorkspaceCustomCommands } from "./custom-commands.js";
|
|
|
13
13
|
import { expandPromptCommand } from "./prompt-command-expansion.js";
|
|
14
14
|
import { SettingsManager } from "./settings-manager.js";
|
|
15
15
|
import { AuthStorage } from "./auth-storage.js";
|
|
16
|
-
import { claudeCodeConfigDir, dualAuthProvider } from "@kenkaiiii/gg-core";
|
|
16
|
+
import { apiKeyStorageKeys, claudeCodeConfigDir, dualAuthProvider } from "@kenkaiiii/gg-core";
|
|
17
17
|
import { claudeCodeTranscriptExists, holdClaudeCodeTranscript, pruneClaudeCodeTranscriptsOnce, } from "./claude-code/transcripts.js";
|
|
18
18
|
import { runSideWebSearch, runSideWebSearchViaClaudeCode, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
|
|
19
19
|
import { SessionManager, processIsAlive, } from "./session-manager.js";
|
|
@@ -33,7 +33,7 @@ import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
|
|
|
33
33
|
import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
|
|
34
34
|
import { resolveStrictTools } from "./codex-request-shape.js";
|
|
35
35
|
import { subAgentDescription } from "../tools/subagent.js";
|
|
36
|
-
import { getAllMcpServers } from "./mcp/index.js";
|
|
36
|
+
import { getAllMcpServers, usesZaiMcpServers } from "./mcp/index.js";
|
|
37
37
|
import { CONTEXT_LIMITS, resolveSessionContextLimits, } from "./context-limits.js";
|
|
38
38
|
import { describeDropped, importForeignSession, } from "./foreign-session-import.js";
|
|
39
39
|
import { createSessionStatsTool } from "../tools/session-stats.js";
|
|
@@ -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,6 +381,8 @@ 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;
|
|
@@ -570,6 +579,7 @@ export class AgentSession {
|
|
|
570
579
|
}),
|
|
571
580
|
getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
|
|
572
581
|
getBashPath: () => this.settingsManager.get("bashPath"),
|
|
582
|
+
getCheckoutSharers: this.opts.getCheckoutSharers,
|
|
573
583
|
getNetworkPolicy: () => ({
|
|
574
584
|
mode: this.settingsManager.get("networkMode"),
|
|
575
585
|
allow: this.settingsManager.get("networkAllow"),
|
|
@@ -854,9 +864,11 @@ export class AgentSession {
|
|
|
854
864
|
return;
|
|
855
865
|
try {
|
|
856
866
|
let apiKey;
|
|
857
|
-
if (this.provider
|
|
867
|
+
if (usesZaiMcpServers(this.provider, this.model)) {
|
|
858
868
|
try {
|
|
859
|
-
const glmCreds = await this.authStorage.resolveCredentials("glm"
|
|
869
|
+
const glmCreds = await this.authStorage.resolveCredentials("glm", {
|
|
870
|
+
storageKeys: apiKeyStorageKeys("glm"),
|
|
871
|
+
});
|
|
860
872
|
apiKey = glmCreds.accessToken;
|
|
861
873
|
}
|
|
862
874
|
catch {
|
|
@@ -1091,19 +1103,7 @@ export class AgentSession {
|
|
|
1091
1103
|
accountId: creds?.accountId,
|
|
1092
1104
|
approvedPlanPath: this.approvedPlanPath,
|
|
1093
1105
|
});
|
|
1094
|
-
|
|
1095
|
-
if (this.providerContext) {
|
|
1096
|
-
const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
|
|
1097
|
-
if (anchorIndex >= 0) {
|
|
1098
|
-
activeTokens = calculateActiveContextTokens(this.messages, {
|
|
1099
|
-
usage: this.providerContext.usage,
|
|
1100
|
-
pendingMessages: this.messages.slice(anchorIndex + 1),
|
|
1101
|
-
});
|
|
1102
|
-
}
|
|
1103
|
-
else {
|
|
1104
|
-
this.providerContext = null;
|
|
1105
|
-
}
|
|
1106
|
-
}
|
|
1106
|
+
const activeTokens = this.idleActiveContextTokens();
|
|
1107
1107
|
log("INFO", "compaction", "Pre-run compaction decision", {
|
|
1108
1108
|
provider: this.provider,
|
|
1109
1109
|
model: this.model,
|
|
@@ -1116,8 +1116,7 @@ export class AgentSession {
|
|
|
1116
1116
|
try {
|
|
1117
1117
|
await this.compact(creds, "automatic");
|
|
1118
1118
|
if (this.lastCompactionCompacted) {
|
|
1119
|
-
|
|
1120
|
-
this.compactionOccurred = true;
|
|
1119
|
+
this.markCompacted();
|
|
1121
1120
|
this.compactionRetryAfter = 0;
|
|
1122
1121
|
}
|
|
1123
1122
|
else {
|
|
@@ -1632,6 +1631,12 @@ export class AgentSession {
|
|
|
1632
1631
|
this.compactionOccurred = true;
|
|
1633
1632
|
}
|
|
1634
1633
|
this.originalRequest = originalRequest;
|
|
1634
|
+
this.runUserDecisions = [];
|
|
1635
|
+
}
|
|
1636
|
+
/** The context was just summarized: arm a fresh re-ground note, even if one already ran this run. */
|
|
1637
|
+
markCompacted() {
|
|
1638
|
+
this.compactionOccurred = true;
|
|
1639
|
+
this.regroundingInjected = false;
|
|
1635
1640
|
}
|
|
1636
1641
|
/**
|
|
1637
1642
|
* Fold one agent event into the hook stat accumulators. Pure bookkeeping —
|
|
@@ -1662,6 +1667,9 @@ export class AgentSession {
|
|
|
1662
1667
|
if (safetyRule)
|
|
1663
1668
|
this.recordSafetyBlock(safetyRule, name, args, event.details);
|
|
1664
1669
|
this.loopMonitor.recordToolEnd(name, args, event.result, event.isError);
|
|
1670
|
+
if (name === "ask_user" && !event.isError) {
|
|
1671
|
+
this.runUserDecisions = recordUserDecision(this.runUserDecisions, event.result);
|
|
1672
|
+
}
|
|
1665
1673
|
const verificationChanged = await this.verificationTracker.recordToolCallEnd(event, call, this.planModeRef.current);
|
|
1666
1674
|
if (verificationChanged)
|
|
1667
1675
|
await this.persistVerificationState();
|
|
@@ -1905,7 +1913,7 @@ export class AgentSession {
|
|
|
1905
1913
|
if (!this.regroundingInjected && this.compactionOccurred) {
|
|
1906
1914
|
this.regroundingInjected = true;
|
|
1907
1915
|
this.eventBus.emit("hook", { kind: "regrounding" });
|
|
1908
|
-
return [buildRegroundingMessage(this.originalRequest)];
|
|
1916
|
+
return [buildRegroundingMessage(this.originalRequest, this.runUserDecisions)];
|
|
1909
1917
|
}
|
|
1910
1918
|
return null;
|
|
1911
1919
|
}
|
|
@@ -2450,32 +2458,21 @@ export class AgentSession {
|
|
|
2450
2458
|
};
|
|
2451
2459
|
let activeTokens = measureActiveTokens();
|
|
2452
2460
|
// Cheap stale-tool-output pruning before the expensive LLM
|
|
2453
|
-
// compaction check
|
|
2454
|
-
//
|
|
2455
|
-
//
|
|
2456
|
-
//
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
freedTokens: String(pruneResult.freedTokens),
|
|
2469
|
-
});
|
|
2470
|
-
// The measured size counted the pruned content, so take the
|
|
2471
|
-
// freed tokens off it. Never swap the provider's count for a
|
|
2472
|
-
// whole-history estimate here: that estimate rides a shared
|
|
2473
|
-
// chars-per-token ratio, and it once read a 234K-token MiMo
|
|
2474
|
-
// context (23% of 1M) as ~400K and compacted it against a 340K
|
|
2475
|
-
// trigger.
|
|
2476
|
-
activeTokens = Math.max(0, activeTokens - pruneResult.freedTokens);
|
|
2477
|
-
}
|
|
2478
|
-
}
|
|
2461
|
+
// compaction check (see pruneToolOutputsIfDue). First move the
|
|
2462
|
+
// cache anchor the last prune left pending, never in the request
|
|
2463
|
+
// that pruned: that one still reads through the previous anchor.
|
|
2464
|
+
// The new anchor's cache entry is created by reading the previous
|
|
2465
|
+
// request's tail, so a prune in this same step (which edits history
|
|
2466
|
+
// before that tail) waits one step.
|
|
2467
|
+
const freedTokens = this.applyPendingCacheAnchor(messages)
|
|
2468
|
+
? 0
|
|
2469
|
+
: this.pruneToolOutputsIfDue(messages, activeTokens, policy.targetTokens);
|
|
2470
|
+
// The measured size counted the pruned content, so take the freed
|
|
2471
|
+
// tokens off it. Never swap the provider's count for a
|
|
2472
|
+
// whole-history estimate here: that estimate rides a shared
|
|
2473
|
+
// chars-per-token ratio, and it once read a 234K-token MiMo context
|
|
2474
|
+
// (23% of 1M) as ~400K and compacted it against a 340K trigger.
|
|
2475
|
+
activeTokens = Math.max(0, activeTokens - freedTokens);
|
|
2479
2476
|
if (Date.now() < this.compactionRetryAfter)
|
|
2480
2477
|
return messages;
|
|
2481
2478
|
// An approved plan runs as ONE run, so step boundaries are only
|
|
@@ -2521,7 +2518,7 @@ export class AgentSession {
|
|
|
2521
2518
|
return messages;
|
|
2522
2519
|
}
|
|
2523
2520
|
this.compactionRetryAfter = 0;
|
|
2524
|
-
this.
|
|
2521
|
+
this.markCompacted();
|
|
2525
2522
|
return this.messages;
|
|
2526
2523
|
},
|
|
2527
2524
|
});
|
|
@@ -2750,46 +2747,48 @@ export class AgentSession {
|
|
|
2750
2747
|
allow: this.settingsManager.get("networkAllow"),
|
|
2751
2748
|
}), (request) => this.runSideWebSearch(request)));
|
|
2752
2749
|
}
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2750
|
+
}
|
|
2751
|
+
// Reconnect MCP servers ONLY when the Z.AI server set flips on or off
|
|
2752
|
+
// (GLM-5.3 ↔ anything else) — every other switch keeps the identical set.
|
|
2753
|
+
// Skipping the dispose/reconnect there avoids tearing down a live stdio
|
|
2754
|
+
// child and gambling on a `npx` re-spawn that could fail and drop the tools.
|
|
2755
|
+
const zaiChanged = usesZaiMcpServers(prevProvider, prevModel) !==
|
|
2756
|
+
usesZaiMcpServers(this.provider, this.model);
|
|
2757
|
+
const mcpManager = this.mcp.manager;
|
|
2758
|
+
if (mcpManager && zaiChanged) {
|
|
2759
|
+
// Remove old MCP tools
|
|
2760
|
+
this.tools = this.tools.filter((t) => !t.name.startsWith("mcp__"));
|
|
2761
|
+
// Disconnect old MCP servers
|
|
2762
|
+
await mcpManager.dispose();
|
|
2763
|
+
// Connect new MCP servers for the new provider
|
|
2764
|
+
try {
|
|
2765
|
+
let apiKey;
|
|
2766
|
+
if (usesZaiMcpServers(this.provider, this.model)) {
|
|
2767
|
+
try {
|
|
2768
|
+
const glmCreds = await this.authStorage.resolveCredentials("glm", {
|
|
2769
|
+
storageKeys: apiKeyStorageKeys("glm"),
|
|
2770
|
+
});
|
|
2771
|
+
apiKey = glmCreds.accessToken;
|
|
2772
|
+
}
|
|
2773
|
+
catch {
|
|
2774
|
+
// GLM not configured — skip Z.AI MCP servers
|
|
2776
2775
|
}
|
|
2777
|
-
// Use getAllMcpServers so user-configured servers survive the reconnect.
|
|
2778
|
-
const servers = await getAllMcpServers(this.provider, apiKey, this.cwd, {
|
|
2779
|
-
allowProjectScope: this.settingsManager.isProjectTrusted(this.cwd),
|
|
2780
|
-
});
|
|
2781
|
-
const results = await mcpManager.connectAllDetailed(servers);
|
|
2782
|
-
const mcpTools = results.flatMap((r) => r.tools);
|
|
2783
|
-
// Drop stale MCP tools from both the live set and deferred catalog before
|
|
2784
|
-
// re-adding. Some tools may already have been promoted out of the catalog.
|
|
2785
|
-
this.tools = this.tools.filter((t) => !t.name.startsWith("mcp__"));
|
|
2786
|
-
this.mcp.clearMcpTools();
|
|
2787
|
-
this.mcp.recordServers(servers, results);
|
|
2788
|
-
this.addMcpTools(mcpTools);
|
|
2789
|
-
}
|
|
2790
|
-
catch (err) {
|
|
2791
|
-
log("WARN", "mcp", `MCP reconnection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
2792
2776
|
}
|
|
2777
|
+
// Use getAllMcpServers so user-configured servers survive the reconnect.
|
|
2778
|
+
const servers = await getAllMcpServers(this.provider, apiKey, this.cwd, {
|
|
2779
|
+
allowProjectScope: this.settingsManager.isProjectTrusted(this.cwd),
|
|
2780
|
+
});
|
|
2781
|
+
const results = await mcpManager.connectAllDetailed(servers);
|
|
2782
|
+
const mcpTools = results.flatMap((r) => r.tools);
|
|
2783
|
+
// Drop stale MCP tools from both the live set and deferred catalog before
|
|
2784
|
+
// re-adding. Some tools may already have been promoted out of the catalog.
|
|
2785
|
+
this.tools = this.tools.filter((t) => !t.name.startsWith("mcp__"));
|
|
2786
|
+
this.mcp.clearMcpTools();
|
|
2787
|
+
this.mcp.recordServers(servers, results);
|
|
2788
|
+
this.addMcpTools(mcpTools);
|
|
2789
|
+
}
|
|
2790
|
+
catch (err) {
|
|
2791
|
+
log("WARN", "mcp", `MCP reconnection failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
2793
2792
|
}
|
|
2794
2793
|
}
|
|
2795
2794
|
}
|
|
@@ -2828,6 +2827,7 @@ export class AgentSession {
|
|
|
2828
2827
|
this.currentLeafId = loaded.header.leafId;
|
|
2829
2828
|
this.setSessionPath(loaded.path);
|
|
2830
2829
|
this.markers.restore(loaded.entries, loaded.header.leafId);
|
|
2830
|
+
this.checkoutRecord = latestCheckoutRecord(loaded.entries) ?? this.checkoutRecord;
|
|
2831
2831
|
this.lastPersistedIndex = this.messages.length;
|
|
2832
2832
|
this.providerContext = null;
|
|
2833
2833
|
await this.subAgentManager?.rebindParentSession(this.sessionId);
|
|
@@ -2869,6 +2869,8 @@ export class AgentSession {
|
|
|
2869
2869
|
this.lastPersistedIndex = this.messages.length;
|
|
2870
2870
|
await this.markers.rePersistAll();
|
|
2871
2871
|
await this.persistVerificationState();
|
|
2872
|
+
// A compaction checkpoint is a new file: the conversation's branch must follow it.
|
|
2873
|
+
await this.persistCheckoutRecord();
|
|
2872
2874
|
await this.persistAppMarker("compaction", {
|
|
2873
2875
|
originalCount: result.originalCount,
|
|
2874
2876
|
newCount: result.newCount,
|
|
@@ -3728,6 +3730,16 @@ export class AgentSession {
|
|
|
3728
3730
|
listBackgroundProcesses() {
|
|
3729
3731
|
return this.processManager?.list() ?? [];
|
|
3730
3732
|
}
|
|
3733
|
+
/**
|
|
3734
|
+
* Start a background process on the host's behalf (a new worktree's setup),
|
|
3735
|
+
* listed with the agent's own background tasks. Null without a process manager.
|
|
3736
|
+
*/
|
|
3737
|
+
async startBackgroundProcess(command, cwd = this.cwd) {
|
|
3738
|
+
if (!this.processManager)
|
|
3739
|
+
return null;
|
|
3740
|
+
const started = await this.processManager.start(command, cwd);
|
|
3741
|
+
return { id: started.id, pid: started.pid };
|
|
3742
|
+
}
|
|
3731
3743
|
/** Stop a background process by id. Returns a human-readable status string. */
|
|
3732
3744
|
async killBackgroundProcess(id) {
|
|
3733
3745
|
if (!this.processManager)
|
|
@@ -4244,6 +4256,42 @@ export class AgentSession {
|
|
|
4244
4256
|
data: this.opts.completionReview.snapshot(),
|
|
4245
4257
|
});
|
|
4246
4258
|
}
|
|
4259
|
+
/**
|
|
4260
|
+
* A chat row saying where this conversation now works ("Opened on branch x in
|
|
4261
|
+
* its own worktree"), live and on every later restore of the transcript.
|
|
4262
|
+
*/
|
|
4263
|
+
noteCheckout(text) {
|
|
4264
|
+
this.eventBus.emit("checkout_notice", { text });
|
|
4265
|
+
void this.persistAppMarker("checkout", { text }).catch(() => { });
|
|
4266
|
+
}
|
|
4267
|
+
/** The branch and checkout this conversation last recorded, or null. */
|
|
4268
|
+
getCheckoutRecord() {
|
|
4269
|
+
return this.checkoutRecord;
|
|
4270
|
+
}
|
|
4271
|
+
/**
|
|
4272
|
+
* Remember the branch this conversation is on, so resuming it later opens
|
|
4273
|
+
* that branch (see core/checkout-record.ts). Unchanged records write nothing.
|
|
4274
|
+
*/
|
|
4275
|
+
async recordCheckout(record) {
|
|
4276
|
+
const previous = this.checkoutRecord;
|
|
4277
|
+
if (previous?.branch === record.branch && previous.cwd === record.cwd)
|
|
4278
|
+
return;
|
|
4279
|
+
this.checkoutRecord = { ...record };
|
|
4280
|
+
await this.persistCheckoutRecord();
|
|
4281
|
+
}
|
|
4282
|
+
async persistCheckoutRecord() {
|
|
4283
|
+
if (!this.sessionPath || !this.checkoutRecord)
|
|
4284
|
+
return;
|
|
4285
|
+
const entry = {
|
|
4286
|
+
type: "custom",
|
|
4287
|
+
kind: CHECKOUT_RECORD_KIND,
|
|
4288
|
+
id: crypto.randomUUID(),
|
|
4289
|
+
parentId: null,
|
|
4290
|
+
timestamp: new Date().toISOString(),
|
|
4291
|
+
data: { ...this.checkoutRecord },
|
|
4292
|
+
};
|
|
4293
|
+
await this.sessionManager.appendEntry(this.sessionPath, entry);
|
|
4294
|
+
}
|
|
4247
4295
|
async persistVerificationState() {
|
|
4248
4296
|
if (this.opts.completionReview)
|
|
4249
4297
|
await this.persistCompletionReviewState();
|
|
@@ -4435,6 +4483,106 @@ export class AgentSession {
|
|
|
4435
4483
|
}
|
|
4436
4484
|
/** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
|
|
4437
4485
|
claudeCodeLive = null;
|
|
4486
|
+
/**
|
|
4487
|
+
* Context size between runs: the last provider usage plus messages appended
|
|
4488
|
+
* after it, or undefined when there is no usable sample (callers estimate).
|
|
4489
|
+
* Same measurement the pre-run compaction check makes.
|
|
4490
|
+
*/
|
|
4491
|
+
idleActiveContextTokens() {
|
|
4492
|
+
if (!this.providerContext)
|
|
4493
|
+
return undefined;
|
|
4494
|
+
const anchorIndex = this.messages.lastIndexOf(this.providerContext.anchor);
|
|
4495
|
+
if (anchorIndex < 0) {
|
|
4496
|
+
this.providerContext = null;
|
|
4497
|
+
return undefined;
|
|
4498
|
+
}
|
|
4499
|
+
return calculateActiveContextTokens(this.messages, {
|
|
4500
|
+
usage: this.providerContext.usage,
|
|
4501
|
+
pendingMessages: this.messages.slice(anchorIndex + 1),
|
|
4502
|
+
});
|
|
4503
|
+
}
|
|
4504
|
+
/**
|
|
4505
|
+
* Prune stale tool outputs in place once the context is big enough for the
|
|
4506
|
+
* freed tokens to be worth a cache rewrite (a larger share on a warm cache,
|
|
4507
|
+
* see pruneMinimumTokens). In-place mutation preserves usage anchors; the
|
|
4508
|
+
* retained usage is dropped since it counted the pruned content. Shared by
|
|
4509
|
+
* the in-flight context transform and prewarm so both send the same prefix.
|
|
4510
|
+
* Returns the freed tokens (0 when nothing was pruned).
|
|
4511
|
+
*/
|
|
4512
|
+
pruneToolOutputsIfDue(messages, activeTokens, targetTokens) {
|
|
4513
|
+
if (!shouldPruneToolResults(activeTokens, targetTokens))
|
|
4514
|
+
return 0;
|
|
4515
|
+
const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
|
|
4516
|
+
const pruneResult = pruneStaleToolResults(messages, {
|
|
4517
|
+
minimumTokens: pruneMinimumTokens(activeTokens, cacheCold, targetTokens),
|
|
4518
|
+
});
|
|
4519
|
+
if (!pruneResult.pruned)
|
|
4520
|
+
return 0;
|
|
4521
|
+
this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
|
|
4522
|
+
this.providerContext = null;
|
|
4523
|
+
this.pendingCacheAnchor = stablePrefixEnd(messages) ?? null;
|
|
4524
|
+
log("INFO", "compaction", "Pruned stale tool outputs", {
|
|
4525
|
+
prunedResults: String(pruneResult.prunedResults),
|
|
4526
|
+
compactedToolCalls: String(pruneResult.compactedToolCalls),
|
|
4527
|
+
freedTokens: String(pruneResult.freedTokens),
|
|
4528
|
+
});
|
|
4529
|
+
return pruneResult.freedTokens;
|
|
4530
|
+
}
|
|
4531
|
+
/**
|
|
4532
|
+
* Mark where the last prune made history stable (`Message.cacheAnchor`), so
|
|
4533
|
+
* the provider can keep a cache breakpoint there. Without it every prune on a
|
|
4534
|
+
* 5-min route re-sent everything after the last entry the tail's lookback
|
|
4535
|
+
* finds; in live sessions a prune freed ~24K tokens and re-wrote ~400K. gg-ai
|
|
4536
|
+
* decides per route whether the hint is used (not on 1-h routes). Returns
|
|
4537
|
+
* true when the anchor moved.
|
|
4538
|
+
*/
|
|
4539
|
+
applyPendingCacheAnchor(messages) {
|
|
4540
|
+
const next = this.pendingCacheAnchor;
|
|
4541
|
+
this.pendingCacheAnchor = null;
|
|
4542
|
+
if (!next || next === this.cacheAnchored || !messages.includes(next))
|
|
4543
|
+
return false;
|
|
4544
|
+
if (this.cacheAnchored)
|
|
4545
|
+
delete this.cacheAnchored.cacheAnchor;
|
|
4546
|
+
next.cacheAnchor = true;
|
|
4547
|
+
this.cacheAnchored = next;
|
|
4548
|
+
return true;
|
|
4549
|
+
}
|
|
4550
|
+
/**
|
|
4551
|
+
* Apply the next request's context policy before warming: report when its
|
|
4552
|
+
* pre-run check will compact, otherwise prune now exactly as its first model
|
|
4553
|
+
* step would. The cache is cold here (prewarm only runs once it has lapsed),
|
|
4554
|
+
* so the prune uses the cold-cache floor, as the request would without the
|
|
4555
|
+
* prewarm; afterwards the warm cache's larger floor keeps that request from
|
|
4556
|
+
* pruning again. Prewarm is Anthropic-only, so the cached account id never
|
|
4557
|
+
* changes the window.
|
|
4558
|
+
*/
|
|
4559
|
+
prepareContextForPrewarm() {
|
|
4560
|
+
if (!this.settingsManager.get("autoCompact"))
|
|
4561
|
+
return "ready";
|
|
4562
|
+
// A post-turn compaction is about to replace this history.
|
|
4563
|
+
if (this.postTurnCompaction)
|
|
4564
|
+
return "compaction_due";
|
|
4565
|
+
const contextWindow = getContextWindow(this.model, {
|
|
4566
|
+
provider: this.provider,
|
|
4567
|
+
accountId: this.lastAccountId,
|
|
4568
|
+
});
|
|
4569
|
+
const policy = resolveCompactionPolicy({
|
|
4570
|
+
provider: this.provider,
|
|
4571
|
+
model: this.model,
|
|
4572
|
+
contextWindow,
|
|
4573
|
+
threshold: this.settingsManager.get("compactThreshold"),
|
|
4574
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
4575
|
+
accountId: this.lastAccountId,
|
|
4576
|
+
approvedPlanPath: this.approvedPlanPath,
|
|
4577
|
+
});
|
|
4578
|
+
const activeTokens = this.idleActiveContextTokens();
|
|
4579
|
+
if (Date.now() >= this.compactionRetryAfter &&
|
|
4580
|
+
shouldCompact(this.messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens)) {
|
|
4581
|
+
return "compaction_due";
|
|
4582
|
+
}
|
|
4583
|
+
this.pruneToolOutputsIfDue(this.messages, activeTokens ?? calculateActiveContextTokens(this.messages), policy.targetTokens);
|
|
4584
|
+
return "ready";
|
|
4585
|
+
}
|
|
4438
4586
|
/**
|
|
4439
4587
|
* Best-effort Anthropic prompt-cache prewarm before the user's next turn
|
|
4440
4588
|
* (desktop app calls this on the first keystroke after opening a chat or an
|
|
@@ -4472,6 +4620,16 @@ export class AgentSession {
|
|
|
4472
4620
|
return { ok: false, reason: "run_active" };
|
|
4473
4621
|
if (this.prewarmController)
|
|
4474
4622
|
return { ok: false, reason: "in_flight" };
|
|
4623
|
+
// Warm what the next request will actually send. Its pre-run check compacts
|
|
4624
|
+
// an over-trigger history (rewriting the whole prefix, so warming now is
|
|
4625
|
+
// waste), and its first model step prunes stale tool outputs when due:
|
|
4626
|
+
// apply that same in-place prune now, so the request finds nothing left to
|
|
4627
|
+
// prune and the warmed prefix matches it. Measured with a live A/B: a 700K
|
|
4628
|
+
// session wrote its full history at the 1-h price here, then rewrote it on
|
|
4629
|
+
// the very next request.
|
|
4630
|
+
if (this.prepareContextForPrewarm() === "compaction_due") {
|
|
4631
|
+
return { ok: false, reason: "compaction_due" };
|
|
4632
|
+
}
|
|
4475
4633
|
// End at the last user/tool message: the next real turn appends a new user
|
|
4476
4634
|
// message after the trailing assistant reply, and its cache lookback hits
|
|
4477
4635
|
// the entry written at this boundary. A request must end on a user turn.
|
|
@@ -4695,6 +4853,7 @@ export class AgentSession {
|
|
|
4695
4853
|
}
|
|
4696
4854
|
this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
|
|
4697
4855
|
this.verificationTracker.clearBackground();
|
|
4856
|
+
this.checkoutRecord = latestCheckoutRecord(loaded.entries);
|
|
4698
4857
|
if (savedVerification?.type === "custom") {
|
|
4699
4858
|
this.verificationGate.restore(savedVerification.data);
|
|
4700
4859
|
}
|
|
@@ -4850,12 +5009,14 @@ export class AgentSession {
|
|
|
4850
5009
|
if (!this.sessionPath)
|
|
4851
5010
|
return;
|
|
4852
5011
|
const entryId = crypto.randomUUID();
|
|
5012
|
+
// The cache-anchor hint only holds for the live run; never store it.
|
|
5013
|
+
const { cacheAnchor: _cacheAnchor, ...stored } = message;
|
|
4853
5014
|
const entry = {
|
|
4854
5015
|
type: "message",
|
|
4855
5016
|
id: entryId,
|
|
4856
5017
|
parentId: this.currentLeafId,
|
|
4857
5018
|
timestamp: new Date().toISOString(),
|
|
4858
|
-
message,
|
|
5019
|
+
message: stored,
|
|
4859
5020
|
};
|
|
4860
5021
|
await this.sessionManager.appendEntry(this.sessionPath, entry);
|
|
4861
5022
|
this.currentLeafId = entryId;
|