@kenkaiiii/ggcoder 5.87.3 → 5.88.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/dist/app-sidecar.js +45 -7
- package/dist/app-sidecar.js.map +1 -1
- package/dist/cli.js +26 -4
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +2 -0
- package/dist/config.js +5 -0
- package/dist/config.js.map +1 -1
- package/dist/core/agent-session.d.ts +44 -1
- package/dist/core/agent-session.js +257 -39
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/cache-diagnostics.d.ts +4 -0
- package/dist/core/cache-diagnostics.js +3 -0
- package/dist/core/cache-diagnostics.js.map +1 -1
- package/dist/core/checkpoint-store.d.ts +17 -0
- package/dist/core/checkpoint-store.js +72 -0
- package/dist/core/checkpoint-store.js.map +1 -1
- package/dist/core/compaction/compactor.d.ts +17 -0
- package/dist/core/compaction/compactor.js +124 -7
- package/dist/core/compaction/compactor.js.map +1 -1
- package/dist/core/compaction/policy.d.ts +18 -0
- package/dist/core/compaction/policy.js +24 -5
- package/dist/core/compaction/policy.js.map +1 -1
- package/dist/core/compaction/tool-result-pruner.d.ts +10 -0
- package/dist/core/compaction/tool-result-pruner.js +14 -0
- package/dist/core/compaction/tool-result-pruner.js.map +1 -1
- package/dist/core/internal-diagnostics.d.ts +17 -0
- package/dist/core/internal-diagnostics.js +45 -0
- package/dist/core/internal-diagnostics.js.map +1 -1
- package/dist/core/logger.d.ts +5 -0
- package/dist/core/logger.js +10 -2
- package/dist/core/logger.js.map +1 -1
- package/dist/core/lsp/edit-telemetry.js +3 -1
- package/dist/core/lsp/edit-telemetry.js.map +1 -1
- package/dist/core/lsp/manager.d.ts +15 -0
- package/dist/core/lsp/manager.js +31 -0
- package/dist/core/lsp/manager.js.map +1 -1
- package/dist/core/plan-delta.d.ts +23 -0
- package/dist/core/plan-delta.js +36 -0
- package/dist/core/plan-delta.js.map +1 -0
- package/dist/core/process-gate.d.ts +17 -0
- package/dist/core/process-gate.js +24 -0
- package/dist/core/process-gate.js.map +1 -1
- package/dist/core/session-history.js +2 -2
- package/dist/core/session-history.js.map +1 -1
- package/dist/core/session-manager.d.ts +1 -0
- package/dist/core/session-manager.js +34 -6
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/session-preview.js +2 -2
- package/dist/core/session-preview.js.map +1 -1
- package/dist/core/session-summary-index.d.ts +18 -4
- package/dist/core/session-summary-index.js +28 -8
- package/dist/core/session-summary-index.js.map +1 -1
- package/dist/core/settings-manager.d.ts +2 -0
- package/dist/core/settings-manager.js +10 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/shell.d.ts +4 -0
- package/dist/core/shell.js +15 -1
- package/dist/core/shell.js.map +1 -1
- package/dist/core/steering.d.ts +4 -0
- package/dist/core/steering.js +8 -1
- package/dist/core/steering.js.map +1 -1
- package/dist/core/stream-diag-level.d.ts +3 -0
- package/dist/core/stream-diag-level.js +24 -0
- package/dist/core/stream-diag-level.js.map +1 -0
- package/dist/core/subagent-manager.d.ts +11 -0
- package/dist/core/subagent-manager.js +16 -4
- package/dist/core/subagent-manager.js.map +1 -1
- package/dist/core/subagent-receipt.d.ts +1 -1
- package/dist/core/subagent-receipt.js +1 -1
- package/dist/interactive.js +1 -0
- package/dist/interactive.js.map +1 -1
- package/dist/subagent-entry.d.ts +1 -0
- package/dist/subagent-entry.js +50 -0
- package/dist/subagent-entry.js.map +1 -0
- package/dist/system-prompt.d.ts +2 -0
- package/dist/system-prompt.js +2 -2
- package/dist/system-prompt.js.map +1 -1
- package/dist/tools/bash.js +11 -6
- package/dist/tools/bash.js.map +1 -1
- package/dist/tools/checklist.js +6 -11
- package/dist/tools/checklist.js.map +1 -1
- package/dist/tools/debug.js +6 -9
- package/dist/tools/debug.js.map +1 -1
- package/dist/tools/find.d.ts +9 -0
- package/dist/tools/find.js +38 -1
- package/dist/tools/find.js.map +1 -1
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +2 -2
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/overflow.d.ts +2 -0
- package/dist/tools/overflow.js +10 -0
- package/dist/tools/overflow.js.map +1 -1
- package/dist/tools/read.js +3 -3
- package/dist/tools/read.js.map +1 -1
- package/dist/tools/routine-output.d.ts +9 -0
- package/dist/tools/routine-output.js +78 -0
- package/dist/tools/routine-output.js.map +1 -1
- package/dist/tools/screenshot.js +6 -10
- package/dist/tools/screenshot.js.map +1 -1
- package/dist/tools/steroids.js +12 -25
- package/dist/tools/steroids.js.map +1 -1
- package/dist/tools/subagent-control.js +55 -5
- package/dist/tools/subagent-control.js.map +1 -1
- package/dist/tools/subagent-shared.d.ts +19 -2
- package/dist/tools/subagent-shared.js +35 -10
- package/dist/tools/subagent-shared.js.map +1 -1
- package/dist/tools/subagent.js +19 -3
- package/dist/tools/subagent.js.map +1 -1
- package/dist/tools/tool-search.js +7 -1
- package/dist/tools/tool-search.js.map +1 -1
- package/dist/tools/truncate.js +4 -8
- package/dist/tools/truncate.js.map +1 -1
- package/dist/ui/App.js +8 -18
- package/dist/ui/App.js.map +1 -1
- package/dist/ui/hooks/useContextCompaction.js +1 -0
- package/dist/ui/hooks/useContextCompaction.js.map +1 -1
- package/package.json +4 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { agentLoop, isAbortError, isUsageLimitError, repairToolPairingAdjacent, } from "@kenkaiiii/gg-agent";
|
|
2
|
-
import { ProviderError, resolveToolSchema, stream, } from "@kenkaiiii/gg-ai";
|
|
2
|
+
import { ProviderError, resolveToolSchema, stream, preconnectProvider, } from "@kenkaiiii/gg-ai";
|
|
3
3
|
import { EventBus } from "./event-bus.js";
|
|
4
4
|
import { flagUntrustedToolResult } from "./injection-detect.js";
|
|
5
5
|
import { sameStamp, scanProjectLockfiles, stampProjectLockfiles, } from "./installed-threats.js";
|
|
@@ -28,7 +28,7 @@ import { ensureAppDirs } from "../config.js";
|
|
|
28
28
|
import { buildSubAgentSystemPrompt, buildSystemPrompt, } from "../system-prompt.js";
|
|
29
29
|
import { createTools, createWebSearchTool, } from "../tools/index.js";
|
|
30
30
|
import { partitionToolsByTier } from "../tools/tool-tiers.js";
|
|
31
|
-
import { buildProcessCompletionFollowUp } from "./process-gate.js";
|
|
31
|
+
import { buildProcessCompletionFollowUp, mergeCompletionGateFollowUps } from "./process-gate.js";
|
|
32
32
|
import { PLAN_SUBMISSION_NUDGE, shouldNudgePlanSubmission } from "./plan-submission-gate.js";
|
|
33
33
|
import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
|
|
34
34
|
import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
|
|
@@ -49,7 +49,7 @@ import { decidePlanStepCompaction, DEFAULT_CACHE_WRITE_READ_RATIO, PLAN_STEP_KEE
|
|
|
49
49
|
import { extractPlanSteps, findCompletedMarkers } from "../utils/plan-steps.js";
|
|
50
50
|
import { readFileSync } from "node:fs";
|
|
51
51
|
import { clampThinkingForPlanMode } from "./thinking-level.js";
|
|
52
|
-
import { pruneStaleToolResults, shouldPruneToolResults } from "./compaction/tool-result-pruner.js";
|
|
52
|
+
import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
|
|
53
53
|
import { discoverAgents } from "./agents.js";
|
|
54
54
|
import { enhancePrompt } from "../utils/prompt-enhancer.js";
|
|
55
55
|
import { detectLanguages, detectProjectStack } from "./language-detector.js";
|
|
@@ -57,6 +57,7 @@ import { buildLoopBreakMessage } from "./loop-breaker.js";
|
|
|
57
57
|
import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
|
|
58
58
|
import { buildSemanticLoopJudgePrompt, buildSemanticLoopMessage, parseSemanticLoopVerdict, SEMANTIC_LOOP_JUDGE_TIMEOUT_MS, withJudgeTimeout, } from "./semantic-loop-check.js";
|
|
59
59
|
import { buildEnvDeltaMessage, buildLanguageUpdateMessage } from "./env-delta.js";
|
|
60
|
+
import { buildPlanStateMessage, samePlanState } from "./plan-delta.js";
|
|
60
61
|
import { listProjectFiles } from "./project-files.js";
|
|
61
62
|
import { wrapSteeringText, buildNotificationSteeringText, buildIdleWakeNotificationText, STEERING_PREFIX, } from "./steering.js";
|
|
62
63
|
import { AgentNotificationQueue } from "./agent-notifications.js";
|
|
@@ -124,9 +125,46 @@ export class PaidModelConfirmationError extends Error {
|
|
|
124
125
|
export { resolveSessionToolResultCharLimit, resolveSessionTurnToolResultCharLimit, } from "./agent-session/helpers.js";
|
|
125
126
|
// ── Agent Session ──────────────────────────────────────────
|
|
126
127
|
/** A prompt that asks for the live web (see AgentSession.attachWebSearchIfAsked). */
|
|
128
|
+
/** True when the transcript holds a native (server-side) `web_search` call. */
|
|
129
|
+
export function historyUsesNativeWebSearch(messages) {
|
|
130
|
+
for (const message of messages) {
|
|
131
|
+
if (message.role !== "assistant" || !Array.isArray(message.content))
|
|
132
|
+
continue;
|
|
133
|
+
for (const part of message.content) {
|
|
134
|
+
if (part.type === "server_tool_call" && part.name === "web_search")
|
|
135
|
+
return true;
|
|
136
|
+
if (part.type === "raw") {
|
|
137
|
+
const data = part.data;
|
|
138
|
+
if (data?.type === "server_tool_use" && data.name === "web_search")
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
127
145
|
const WEB_INTENT = /\b(?:web|internet|online|google|googling|website|look (?:it |this |that )?up|(?:latest|newest|current) (?:version|release|news|docs?|documentation)|release notes|news)\b/i;
|
|
128
146
|
/** Distinct security rows one run may add to the chat (and session file). */
|
|
129
147
|
const MAX_SECURITY_ROWS_PER_RUN = 20;
|
|
148
|
+
/** How long dispose waits for a post-turn compaction before aborting it. */
|
|
149
|
+
export const DISPOSE_COMPACTION_WAIT_MS = 2_500;
|
|
150
|
+
/** Grace after aborting it, for the compaction to unwind. */
|
|
151
|
+
const DISPOSE_COMPACTION_ABORT_GRACE_MS = 500;
|
|
152
|
+
/** Resolves true if `promise` settles within `ms`, else false. Never rejects. */
|
|
153
|
+
async function settleWithin(promise, ms) {
|
|
154
|
+
let timer;
|
|
155
|
+
const timeout = new Promise((resolve) => {
|
|
156
|
+
timer = setTimeout(() => resolve(false), ms);
|
|
157
|
+
});
|
|
158
|
+
try {
|
|
159
|
+
return await Promise.race([
|
|
160
|
+
promise.then(() => true, () => true),
|
|
161
|
+
timeout,
|
|
162
|
+
]);
|
|
163
|
+
}
|
|
164
|
+
finally {
|
|
165
|
+
clearTimeout(timer);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
130
168
|
/**
|
|
131
169
|
* A chat row's target: first line, no control or bidi-override characters
|
|
132
170
|
* (they could make a command look like another), at most 120 chars.
|
|
@@ -220,6 +258,8 @@ export class AgentSession {
|
|
|
220
258
|
renderedEnvironment = {};
|
|
221
259
|
/** Project files as of the first prompt build (undefined until then). */
|
|
222
260
|
projectFiles;
|
|
261
|
+
/** `git ls-files` started at the top of initialize(), overlapping the rest of setup. */
|
|
262
|
+
projectFilesPending;
|
|
223
263
|
/** Wall-clock start of the current run; scopes the background-process gate. */
|
|
224
264
|
runStartedAt = 0;
|
|
225
265
|
/** Gate injections spent this run, capped by MAX_PROCESS_GATE_INJECTIONS. */
|
|
@@ -243,6 +283,8 @@ export class AgentSession {
|
|
|
243
283
|
compactionArmedForNextRun = false;
|
|
244
284
|
/** In-flight post-turn (background) compaction, if any. */
|
|
245
285
|
postTurnCompaction;
|
|
286
|
+
/** Aborts the in-flight post-turn compaction (dispose caps its wait). */
|
|
287
|
+
postTurnCompactionAbort;
|
|
246
288
|
lastCompactionCompacted = false;
|
|
247
289
|
compactionRetryAfter = 0;
|
|
248
290
|
/**
|
|
@@ -310,6 +352,10 @@ export class AgentSession {
|
|
|
310
352
|
* can discover and promote them; a promoted name drops out of this list.
|
|
311
353
|
*/
|
|
312
354
|
deferredBuiltinToolNames = [];
|
|
355
|
+
/** Deferred built-ins in tier order, fixed at session start. Sent as the
|
|
356
|
+
* provider's on-demand catalog (see gg-ai `deferredTools`) so promoting one
|
|
357
|
+
* loads it through the transcript and the cached tools block stays put. */
|
|
358
|
+
deferredToolCatalog = [];
|
|
313
359
|
provider;
|
|
314
360
|
model;
|
|
315
361
|
cwd;
|
|
@@ -326,6 +372,14 @@ export class AgentSession {
|
|
|
326
372
|
agentPrompt;
|
|
327
373
|
/** Stable prompt prefix retained separately from the volatile uncached tail. */
|
|
328
374
|
baseSystemPrompt = "";
|
|
375
|
+
/** Plan state rendered into the cached system prompt. */
|
|
376
|
+
promptPlanState = { planMode: false, approvedPlanPath: undefined };
|
|
377
|
+
/** Plan state the model has been told (prompt or appended notice). */
|
|
378
|
+
seenPlanState = { planMode: false, approvedPlanPath: undefined };
|
|
379
|
+
/** Plan notice waiting for the next request, with the state it describes. */
|
|
380
|
+
pendingPlanNotice = null;
|
|
381
|
+
/** Latest plan notice appended — re-announced if compaction drops it. */
|
|
382
|
+
lastPlanNotice = null;
|
|
329
383
|
/**
|
|
330
384
|
* Project languages whose style packs and verify commands are in the
|
|
331
385
|
* standard prompt. Only ever grows within a session (same policy as the
|
|
@@ -431,6 +485,12 @@ export class AgentSession {
|
|
|
431
485
|
// so it overlaps session setup and the user's typing instead.
|
|
432
486
|
if (this.provider === "anthropic")
|
|
433
487
|
void getClaudeCliUserAgent().catch(() => { });
|
|
488
|
+
// The prompt's file list is a `git ls-files` (~30 ms on a mid-size repo)
|
|
489
|
+
// that nothing before buildBasePrompt depends on: start it now so it runs
|
|
490
|
+
// alongside settings/auth/skills/tools instead of after them.
|
|
491
|
+
if (!this.customSystemPrompt && this.projectFiles === undefined) {
|
|
492
|
+
this.projectFilesPending = listProjectFiles(this.cwd);
|
|
493
|
+
}
|
|
434
494
|
const paths = await ensureAppDirs();
|
|
435
495
|
// Load settings & auth
|
|
436
496
|
this.settingsManager = new SettingsManager(paths.settingsFile);
|
|
@@ -500,6 +560,7 @@ export class AgentSession {
|
|
|
500
560
|
additionalRoots: this.additionalRoots,
|
|
501
561
|
}),
|
|
502
562
|
getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
|
|
563
|
+
getBashPath: () => this.settingsManager.get("bashPath"),
|
|
503
564
|
getNetworkPolicy: () => ({
|
|
504
565
|
mode: this.settingsManager.get("networkMode"),
|
|
505
566
|
allow: this.settingsManager.get("networkAllow"),
|
|
@@ -597,6 +658,7 @@ export class AgentSession {
|
|
|
597
658
|
// sits inside the cached prefix stays byte-stable across turns.
|
|
598
659
|
this.tools = core;
|
|
599
660
|
this.deferredBuiltinToolNames = deferred.map((t) => t.name);
|
|
661
|
+
this.deferredToolCatalog = [...deferred];
|
|
600
662
|
this.mcp.addDeferred(deferred);
|
|
601
663
|
}
|
|
602
664
|
}
|
|
@@ -734,6 +796,7 @@ export class AgentSession {
|
|
|
734
796
|
await this.extensionLoader.loadAll(paths.extensionsDir, extContext);
|
|
735
797
|
}
|
|
736
798
|
this.eventBus.emit("session_start", { sessionId: this.sessionId });
|
|
799
|
+
this.preconnect();
|
|
737
800
|
}
|
|
738
801
|
/**
|
|
739
802
|
* Whether a tool name is permitted for this session. With no `allowedTools`
|
|
@@ -877,7 +940,14 @@ export class AgentSession {
|
|
|
877
940
|
return true;
|
|
878
941
|
if (!this.deferredBuiltinToolNames.includes("web_search"))
|
|
879
942
|
return true;
|
|
880
|
-
|
|
943
|
+
if (this.tools.some((t) => t.name === "web_search"))
|
|
944
|
+
return true;
|
|
945
|
+
// A restored, branched or compacted conversation can already hold native
|
|
946
|
+
// `web_search` blocks from when the tool was attached. Anthropic rejects
|
|
947
|
+
// any request whose history references a server tool that is not declared
|
|
948
|
+
// (400 "`server_tool_use` block references `web_search`…"), so the history
|
|
949
|
+
// itself keeps native search on.
|
|
950
|
+
return historyUsesNativeWebSearch(this.messages);
|
|
881
951
|
}
|
|
882
952
|
/**
|
|
883
953
|
* A human prompt that plainly asks for the web gets native web search from
|
|
@@ -923,8 +993,17 @@ export class AgentSession {
|
|
|
923
993
|
const result = await tool.execute(args, context);
|
|
924
994
|
if (when(args)) {
|
|
925
995
|
const missing = followUps.filter((name) => !this.tools.some((t) => t.name === name));
|
|
926
|
-
|
|
927
|
-
|
|
996
|
+
const promoted = missing.length > 0 ? this.mcp.promote(missing) : [];
|
|
997
|
+
if (promoted.length > 0) {
|
|
998
|
+
this.tools.push(...promoted);
|
|
999
|
+
// The trigger's result is where the follow-ups load (cache-safe
|
|
1000
|
+
// transports load them in the transcript, not the tools block).
|
|
1001
|
+
const structured = typeof result === "string" ? { content: result } : result;
|
|
1002
|
+
return {
|
|
1003
|
+
...structured,
|
|
1004
|
+
loadedTools: [...(structured.loadedTools ?? []), ...promoted.map((t) => t.name)],
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
928
1007
|
}
|
|
929
1008
|
return result;
|
|
930
1009
|
},
|
|
@@ -1290,6 +1369,11 @@ export class AgentSession {
|
|
|
1290
1369
|
// never been told about. The note states the facts outright rather than
|
|
1291
1370
|
// referring to a section such a prompt does not have.
|
|
1292
1371
|
const environmentDelta = buildEnvDeltaMessage(this.renderedEnvironment, this.promptEnvironment());
|
|
1372
|
+
// Plan mode toggled / plan approved mid-run: appended, never re-rendered.
|
|
1373
|
+
const planNotice = this.takePlanNotice();
|
|
1374
|
+
if (planNotice) {
|
|
1375
|
+
log("INFO", "session", "Injecting plan state update instead of rebuilding the prompt");
|
|
1376
|
+
}
|
|
1293
1377
|
if (environmentDelta) {
|
|
1294
1378
|
// The model has now been told; only a further change re-triggers this.
|
|
1295
1379
|
this.renderedEnvironment = this.promptEnvironment();
|
|
@@ -1355,13 +1439,15 @@ export class AgentSession {
|
|
|
1355
1439
|
});
|
|
1356
1440
|
return [
|
|
1357
1441
|
...(environmentDelta ? [environmentDelta] : []),
|
|
1442
|
+
...(planNotice ? [planNotice] : []),
|
|
1358
1443
|
...steeringMessages,
|
|
1359
1444
|
...(notificationMessage ? [notificationMessage] : []),
|
|
1360
1445
|
];
|
|
1361
1446
|
}
|
|
1362
|
-
if (environmentDelta || notificationMessage) {
|
|
1447
|
+
if (environmentDelta || planNotice || notificationMessage) {
|
|
1363
1448
|
return [
|
|
1364
1449
|
...(environmentDelta ? [environmentDelta] : []),
|
|
1450
|
+
...(planNotice ? [planNotice] : []),
|
|
1365
1451
|
...(notificationMessage ? [notificationMessage] : []),
|
|
1366
1452
|
];
|
|
1367
1453
|
}
|
|
@@ -1596,22 +1682,22 @@ export class AgentSession {
|
|
|
1596
1682
|
},
|
|
1597
1683
|
]
|
|
1598
1684
|
: [];
|
|
1599
|
-
const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager);
|
|
1600
|
-
if (childCompletionFollowUp)
|
|
1601
|
-
return [...diagnosticMessages, ...childCompletionFollowUp];
|
|
1685
|
+
const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager) ?? [];
|
|
1602
1686
|
// Background processes started this run and never read block completion:
|
|
1603
1687
|
// their progress/exit checkpoints only land on the steering path, which an
|
|
1604
|
-
// agent about to stop never reaches.
|
|
1605
|
-
|
|
1606
|
-
|
|
1688
|
+
// agent about to stop never reaches. Sent in the same follow-up as the
|
|
1689
|
+
// child-agent gate: one forced turn can collect both, where returning them
|
|
1690
|
+
// one per stop cost a separate model round-trip each.
|
|
1691
|
+
const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected) ?? [];
|
|
1692
|
+
if (processFollowUp.length > 0) {
|
|
1607
1693
|
this.processGateInjected += 1;
|
|
1608
1694
|
log("INFO", "process-gate", "Injecting background-process completion gate", {
|
|
1609
1695
|
injected: String(this.processGateInjected),
|
|
1610
1696
|
});
|
|
1611
|
-
return [...diagnosticMessages, ...processFollowUp];
|
|
1612
1697
|
}
|
|
1613
|
-
|
|
1614
|
-
|
|
1698
|
+
const gateMessages = mergeCompletionGateFollowUps(diagnosticMessages, childCompletionFollowUp, processFollowUp);
|
|
1699
|
+
if (gateMessages)
|
|
1700
|
+
return gateMessages;
|
|
1615
1701
|
await this.rerunRefusedCheck();
|
|
1616
1702
|
if (shouldNudgePlanSubmission({
|
|
1617
1703
|
enabled: this.opts.planSubmissionGate === true,
|
|
@@ -1773,6 +1859,7 @@ export class AgentSession {
|
|
|
1773
1859
|
model: this.model,
|
|
1774
1860
|
contextWindow,
|
|
1775
1861
|
threshold: this.settingsManager.get("compactThreshold"),
|
|
1862
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
1776
1863
|
accountId: creds.accountId,
|
|
1777
1864
|
approvedPlanPath: this.approvedPlanPath,
|
|
1778
1865
|
});
|
|
@@ -1830,6 +1917,7 @@ export class AgentSession {
|
|
|
1830
1917
|
provider: this.provider,
|
|
1831
1918
|
model: this.model,
|
|
1832
1919
|
tools: options.disableTools ? [] : this.tools,
|
|
1920
|
+
...(options.disableTools ? {} : { deferredTools: this.deferredToolCatalog }),
|
|
1833
1921
|
webSearch: options.disableTools ? false : () => this.nativeWebSearchOn(),
|
|
1834
1922
|
maxTokens: this.requestMaxTokens(accountId),
|
|
1835
1923
|
maxTurns: this.opts.maxTurns,
|
|
@@ -1892,10 +1980,15 @@ export class AgentSession {
|
|
|
1892
1980
|
promptCacheKey: this.getPromptCacheKey(),
|
|
1893
1981
|
},
|
|
1894
1982
|
});
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1983
|
+
// "Context cache outcome" (persistTurnMetric) repeats this whole report
|
|
1984
|
+
// with usage attached, so only log the prepared report on its own when
|
|
1985
|
+
// it carries a cache-relevant change or risk worth seeing pre-response.
|
|
1986
|
+
if (report.changes.length > 0 || report.thinkingPrefixRiskBlocks > 0) {
|
|
1987
|
+
log("INFO", "cache", "Prepared context", {
|
|
1988
|
+
sessionId: this.sessionId || this.transportSessionId,
|
|
1989
|
+
data: JSON.stringify(report),
|
|
1990
|
+
});
|
|
1991
|
+
}
|
|
1899
1992
|
if (report.thinkingPrefixRiskBlocks > 0) {
|
|
1900
1993
|
log("WARN", "cache", "Possible signed-thinking prefix mismatch; not server verified", {
|
|
1901
1994
|
sessionId: this.sessionId || this.transportSessionId,
|
|
@@ -1958,6 +2051,7 @@ export class AgentSession {
|
|
|
1958
2051
|
model: this.model,
|
|
1959
2052
|
contextWindow,
|
|
1960
2053
|
threshold: this.settingsManager.get("compactThreshold"),
|
|
2054
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
1961
2055
|
accountId,
|
|
1962
2056
|
approvedPlanPath: this.approvedPlanPath,
|
|
1963
2057
|
});
|
|
@@ -1984,7 +2078,10 @@ export class AgentSession {
|
|
|
1984
2078
|
// anchors; drop the retained usage afterwards since it counted the
|
|
1985
2079
|
// pruned content.
|
|
1986
2080
|
if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
|
|
1987
|
-
const
|
|
2081
|
+
const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
|
|
2082
|
+
const pruneResult = pruneStaleToolResults(messages, {
|
|
2083
|
+
minimumTokens: pruneMinimumTokens(activeTokens, cacheCold),
|
|
2084
|
+
});
|
|
1988
2085
|
if (pruneResult.pruned) {
|
|
1989
2086
|
this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
|
|
1990
2087
|
this.providerContext = null;
|
|
@@ -2007,6 +2104,8 @@ export class AgentSession {
|
|
|
2007
2104
|
// An approved plan runs as ONE run, so step boundaries are only
|
|
2008
2105
|
// visible here, between model steps — not after the run ends.
|
|
2009
2106
|
const planStep = this.observePlanStepProgress(messages, contextWindow, activeTokens);
|
|
2107
|
+
// The decision line carries the outcome (compact=) next to its inputs.
|
|
2108
|
+
const overLimit = shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens);
|
|
2010
2109
|
log("INFO", "compaction", "In-flight compaction decision", {
|
|
2011
2110
|
provider: this.provider,
|
|
2012
2111
|
model: this.model,
|
|
@@ -2014,10 +2113,10 @@ export class AgentSession {
|
|
|
2014
2113
|
contextWindow: String(contextWindow),
|
|
2015
2114
|
activeTokens: String(activeTokens),
|
|
2016
2115
|
triggerLimit: String(policy.targetTokens),
|
|
2116
|
+
compact: String(overLimit || Boolean(planStep?.compact)),
|
|
2017
2117
|
...(planStep ? { planStep: `${planStep.compact} (${planStep.reason})` } : {}),
|
|
2018
2118
|
});
|
|
2019
|
-
if (!
|
|
2020
|
-
!planStep?.compact)
|
|
2119
|
+
if (!overLimit && !planStep?.compact)
|
|
2021
2120
|
return messages;
|
|
2022
2121
|
}
|
|
2023
2122
|
// compact() operates on this.messages, while an earlier transform may
|
|
@@ -2211,6 +2310,8 @@ export class AgentSession {
|
|
|
2211
2310
|
// booted on e.g. Kimi (256K) keeps sending that cap after switching to a
|
|
2212
2311
|
// smaller model (Opus 128K), which the provider rejects.
|
|
2213
2312
|
this.maxTokens = this.resolveMaxTokens(model);
|
|
2313
|
+
if (changed)
|
|
2314
|
+
this.preconnect();
|
|
2214
2315
|
this.eventBus.emit("model_change", {
|
|
2215
2316
|
provider: this.provider,
|
|
2216
2317
|
model: this.model,
|
|
@@ -2535,6 +2636,7 @@ export class AgentSession {
|
|
|
2535
2636
|
model: this.model,
|
|
2536
2637
|
contextWindow,
|
|
2537
2638
|
threshold: this.settingsManager.get("compactThreshold"),
|
|
2639
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
2538
2640
|
accountId: creds.accountId,
|
|
2539
2641
|
approvedPlanPath: this.approvedPlanPath,
|
|
2540
2642
|
});
|
|
@@ -2561,9 +2663,11 @@ export class AgentSession {
|
|
|
2561
2663
|
activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
|
|
2562
2664
|
triggerLimit: String(policy.targetTokens),
|
|
2563
2665
|
});
|
|
2666
|
+
const postTurnAbort = new AbortController();
|
|
2667
|
+
this.postTurnCompactionAbort = postTurnAbort;
|
|
2564
2668
|
this.postTurnCompaction = (async () => {
|
|
2565
2669
|
try {
|
|
2566
|
-
await this.compact(creds, "automatic");
|
|
2670
|
+
await this.compact(creds, "automatic", undefined, postTurnAbort.signal);
|
|
2567
2671
|
if (this.lastCompactionCompacted) {
|
|
2568
2672
|
// Arm re-grounding for the next turn. resetHookState clears
|
|
2569
2673
|
// compactionOccurred at run start, before the injection point, so
|
|
@@ -2583,13 +2687,20 @@ export class AgentSession {
|
|
|
2583
2687
|
}
|
|
2584
2688
|
finally {
|
|
2585
2689
|
this.postTurnCompaction = undefined;
|
|
2690
|
+
if (this.postTurnCompactionAbort === postTurnAbort)
|
|
2691
|
+
this.postTurnCompactionAbort = undefined;
|
|
2586
2692
|
}
|
|
2587
2693
|
})();
|
|
2588
2694
|
}
|
|
2589
2695
|
async compact(existingCredentials, mode = "manual",
|
|
2590
2696
|
/** User-stated focus (`/compact <focus>`): what must survive verbatim. */
|
|
2591
|
-
focus
|
|
2697
|
+
focus,
|
|
2698
|
+
/** Extra abort source (post-turn compaction, cancelled by dispose). */
|
|
2699
|
+
abortSignal) {
|
|
2592
2700
|
this.lastCompactionCompacted = false;
|
|
2701
|
+
const compactionSignal = abortSignal && this.opts.signal
|
|
2702
|
+
? AbortSignal.any([this.opts.signal, abortSignal])
|
|
2703
|
+
: (abortSignal ?? this.opts.signal);
|
|
2593
2704
|
const creds = existingCredentials ??
|
|
2594
2705
|
(await this.authStorage.resolveCredentials(this.provider, {
|
|
2595
2706
|
storageKeys: this.currentAuthStorageKeys(),
|
|
@@ -2603,6 +2714,7 @@ export class AgentSession {
|
|
|
2603
2714
|
model: this.model,
|
|
2604
2715
|
contextWindow,
|
|
2605
2716
|
threshold: this.settingsManager.get("compactThreshold"),
|
|
2717
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
2606
2718
|
accountId: creds.accountId,
|
|
2607
2719
|
approvedPlanPath: this.approvedPlanPath,
|
|
2608
2720
|
});
|
|
@@ -2620,7 +2732,7 @@ export class AgentSession {
|
|
|
2620
2732
|
baseUrl: this.baseUrl ?? creds.baseUrl,
|
|
2621
2733
|
contextWindow,
|
|
2622
2734
|
targetTokens: policy.targetTokens,
|
|
2623
|
-
signal:
|
|
2735
|
+
signal: compactionSignal,
|
|
2624
2736
|
approvedPlanPath: this.approvedPlanPath,
|
|
2625
2737
|
focus,
|
|
2626
2738
|
});
|
|
@@ -2641,7 +2753,7 @@ export class AgentSession {
|
|
|
2641
2753
|
}
|
|
2642
2754
|
else {
|
|
2643
2755
|
const conversationId = this.conversationId;
|
|
2644
|
-
await this.sessionManager.withCompactionLease(conversationId,
|
|
2756
|
+
await this.sessionManager.withCompactionLease(conversationId, compactionSignal, async () => {
|
|
2645
2757
|
let sourceFingerprint = computeSourceFingerprint(this.messages);
|
|
2646
2758
|
const canonicalPath = await this.sessionManager.resolveCanonicalSession(conversationId, this.cwd);
|
|
2647
2759
|
if (canonicalPath && canonicalPath !== this.sessionPath) {
|
|
@@ -3214,7 +3326,7 @@ export class AgentSession {
|
|
|
3214
3326
|
// is about to be drafted); exiting keeps it (set explicitly via accept).
|
|
3215
3327
|
if (active)
|
|
3216
3328
|
this.approvedPlanPath = undefined;
|
|
3217
|
-
await this.
|
|
3329
|
+
await this.applyPlanStateChange();
|
|
3218
3330
|
}
|
|
3219
3331
|
/**
|
|
3220
3332
|
* Bake an approved plan into the system prompt so the model is told to emit
|
|
@@ -3224,7 +3336,45 @@ export class AgentSession {
|
|
|
3224
3336
|
*/
|
|
3225
3337
|
async setApprovedPlan(approvedPlanPath) {
|
|
3226
3338
|
this.approvedPlanPath = approvedPlanPath;
|
|
3227
|
-
await this.
|
|
3339
|
+
await this.applyPlanStateChange();
|
|
3340
|
+
}
|
|
3341
|
+
/**
|
|
3342
|
+
* Before the conversation starts, render plan state into the prompt. After,
|
|
3343
|
+
* the prompt is a cached prefix: queue an appended notice instead, so the
|
|
3344
|
+
* cached bytes stay identical (a rebuild re-sent the whole history).
|
|
3345
|
+
*/
|
|
3346
|
+
async applyPlanStateChange() {
|
|
3347
|
+
if (this.customSystemPrompt || this.agentPrompt !== undefined)
|
|
3348
|
+
return;
|
|
3349
|
+
if (!this.messages.some((message) => message.role !== "system")) {
|
|
3350
|
+
this.pendingPlanNotice = null;
|
|
3351
|
+
await this.rebuildSystemPromptInPlace();
|
|
3352
|
+
return;
|
|
3353
|
+
}
|
|
3354
|
+
const state = {
|
|
3355
|
+
planMode: this.planModeRef.current,
|
|
3356
|
+
approvedPlanPath: this.approvedPlanPath,
|
|
3357
|
+
};
|
|
3358
|
+
const message = await buildPlanStateMessage(this.seenPlanState, state);
|
|
3359
|
+
this.pendingPlanNotice = message ? { message, state } : null;
|
|
3360
|
+
}
|
|
3361
|
+
/** The plan notice to append now, if any (pending, or a compacted-away one). */
|
|
3362
|
+
takePlanNotice() {
|
|
3363
|
+
if (this.pendingPlanNotice) {
|
|
3364
|
+
const { message, state } = this.pendingPlanNotice;
|
|
3365
|
+
this.pendingPlanNotice = null;
|
|
3366
|
+
this.seenPlanState = state;
|
|
3367
|
+
this.lastPlanNotice = message;
|
|
3368
|
+
return message;
|
|
3369
|
+
}
|
|
3370
|
+
if (this.lastPlanNotice &&
|
|
3371
|
+
!samePlanState(this.seenPlanState, this.promptPlanState) &&
|
|
3372
|
+
!this.messages.includes(this.lastPlanNotice)) {
|
|
3373
|
+
const again = { ...this.lastPlanNotice };
|
|
3374
|
+
this.lastPlanNotice = again;
|
|
3375
|
+
return again;
|
|
3376
|
+
}
|
|
3377
|
+
return null;
|
|
3228
3378
|
}
|
|
3229
3379
|
/** Extra workspace roots added with `/add-dir`, in the order added. */
|
|
3230
3380
|
getAdditionalRoots() {
|
|
@@ -3334,8 +3484,11 @@ export class AgentSession {
|
|
|
3334
3484
|
return this.customSystemPrompt;
|
|
3335
3485
|
// Listed once: a rebuild (plan mode, /add-dir, compaction) must not churn the
|
|
3336
3486
|
// prompt as the agent adds files.
|
|
3337
|
-
if (this.projectFiles === undefined)
|
|
3338
|
-
|
|
3487
|
+
if (this.projectFiles === undefined) {
|
|
3488
|
+
const pending = this.projectFilesPending;
|
|
3489
|
+
this.projectFilesPending = undefined;
|
|
3490
|
+
this.projectFiles = await (pending ?? listProjectFiles(this.cwd));
|
|
3491
|
+
}
|
|
3339
3492
|
const toolNames = this.tools.map((tool) => tool.name);
|
|
3340
3493
|
const deferredToolNames = this.deferredToolNamesForPrompt(toolNames);
|
|
3341
3494
|
// Whatever is rendered now is what the model has been told.
|
|
@@ -3381,6 +3534,13 @@ export class AgentSession {
|
|
|
3381
3534
|
* update is saved in order with the rest of the conversation.
|
|
3382
3535
|
*/
|
|
3383
3536
|
async announceNewLanguages() {
|
|
3537
|
+
const planNotice = this.takePlanNotice();
|
|
3538
|
+
if (planNotice) {
|
|
3539
|
+
this.messages.push(planNotice);
|
|
3540
|
+
await this.persistMessage(planNotice);
|
|
3541
|
+
this.lastPersistedIndex = this.messages.length;
|
|
3542
|
+
log("INFO", "session", "Appended plan state update instead of rebuilding the prompt");
|
|
3543
|
+
}
|
|
3384
3544
|
if (!this.hasReply())
|
|
3385
3545
|
return; // the next request rebuilds the prompt instead
|
|
3386
3546
|
this.refreshActiveLanguages();
|
|
@@ -3446,6 +3606,13 @@ export class AgentSession {
|
|
|
3446
3606
|
return;
|
|
3447
3607
|
const rebuilt = await this.buildBasePrompt(this.planModeRef.current, this.approvedPlanPath);
|
|
3448
3608
|
this.baseSystemPrompt = rebuilt;
|
|
3609
|
+
this.promptPlanState = {
|
|
3610
|
+
planMode: this.planModeRef.current,
|
|
3611
|
+
approvedPlanPath: this.approvedPlanPath,
|
|
3612
|
+
};
|
|
3613
|
+
this.seenPlanState = this.promptPlanState;
|
|
3614
|
+
this.pendingPlanNotice = null;
|
|
3615
|
+
this.lastPlanNotice = null;
|
|
3449
3616
|
const content = this.withSystemPromptTail(rebuilt);
|
|
3450
3617
|
if (this.messages[0]?.role === "system") {
|
|
3451
3618
|
this.messages[0] = { role: "system", content };
|
|
@@ -3753,6 +3920,33 @@ export class AgentSession {
|
|
|
3753
3920
|
runLoopDepth = 0;
|
|
3754
3921
|
lastRealRequestAt = 0;
|
|
3755
3922
|
lastPrewarmAt = 0;
|
|
3923
|
+
/** Last connection pre-open per provider origin (see {@link preconnect}). */
|
|
3924
|
+
preconnectedAt = new Map();
|
|
3925
|
+
/**
|
|
3926
|
+
* Fire-and-forget: open the TLS connection to the active provider before the
|
|
3927
|
+
* first request, through the shared keep-alive pool. Zero tokens — an
|
|
3928
|
+
* unauthenticated HEAD; skipped for local endpoints and throttled per origin.
|
|
3929
|
+
* Transient sessions (one-shot tools) and test runs never touch the network here.
|
|
3930
|
+
*/
|
|
3931
|
+
preconnect() {
|
|
3932
|
+
const enabled = this.opts.preconnect ?? (this.opts.transient !== true && !process.env.VITEST);
|
|
3933
|
+
if (!enabled)
|
|
3934
|
+
return;
|
|
3935
|
+
const provider = this.provider;
|
|
3936
|
+
void this.authStorage
|
|
3937
|
+
.resolveCredentials(provider, { storageKeys: this.currentAuthStorageKeys() })
|
|
3938
|
+
.then((creds) => {
|
|
3939
|
+
if (provider !== this.provider)
|
|
3940
|
+
return;
|
|
3941
|
+
preconnectProvider({
|
|
3942
|
+
provider,
|
|
3943
|
+
baseUrl: this.baseUrl ?? creds.baseUrl,
|
|
3944
|
+
accountId: creds.accountId,
|
|
3945
|
+
warmedAt: this.preconnectedAt,
|
|
3946
|
+
});
|
|
3947
|
+
})
|
|
3948
|
+
.catch(() => { });
|
|
3949
|
+
}
|
|
3756
3950
|
prewarmController = null;
|
|
3757
3951
|
/**
|
|
3758
3952
|
* Best-effort Anthropic prompt-cache prewarm before the user's next turn
|
|
@@ -3762,6 +3956,8 @@ export class AgentSession {
|
|
|
3762
3956
|
* first real reply is a cache read instead of a cold write.
|
|
3763
3957
|
*/
|
|
3764
3958
|
async prewarm(signal) {
|
|
3959
|
+
// Every provider: the user is typing, so the first request is seconds away.
|
|
3960
|
+
this.preconnect();
|
|
3765
3961
|
if (this.provider !== "anthropic")
|
|
3766
3962
|
return { ok: false, reason: "provider" };
|
|
3767
3963
|
if (this.settingsManager?.get("cachePrewarm") === false) {
|
|
@@ -3820,6 +4016,7 @@ export class AgentSession {
|
|
|
3820
4016
|
model: this.model,
|
|
3821
4017
|
messages,
|
|
3822
4018
|
tools: this.tools,
|
|
4019
|
+
deferredTools: this.deferredToolCatalog,
|
|
3823
4020
|
webSearch: this.nativeWebSearchOn(),
|
|
3824
4021
|
maxTokens: this.requestMaxTokens(creds.accountId),
|
|
3825
4022
|
thinking: this.planModeRef.current
|
|
@@ -3921,8 +4118,18 @@ export class AgentSession {
|
|
|
3921
4118
|
// the background compact() snapshots and replaces `this.messages`, so
|
|
3922
4119
|
// letting it run past this point would checkpoint a near-empty history
|
|
3923
4120
|
// and leak a junk session file after teardown.
|
|
3924
|
-
|
|
3925
|
-
|
|
4121
|
+
// Capped: a hung summary call must not hold MCP/LSP/sub-agent teardown and
|
|
4122
|
+
// window close hostage. Past the cap it is aborted (compact() checks the
|
|
4123
|
+
// signal before replacing history), with a short grace to unwind.
|
|
4124
|
+
if (this.postTurnCompaction) {
|
|
4125
|
+
const pending = this.postTurnCompaction;
|
|
4126
|
+
const settledInTime = await settleWithin(pending, DISPOSE_COMPACTION_WAIT_MS);
|
|
4127
|
+
if (!settledInTime) {
|
|
4128
|
+
log("WARN", "compaction", "Post-turn compaction still running at dispose — aborting");
|
|
4129
|
+
this.postTurnCompactionAbort?.abort();
|
|
4130
|
+
await settleWithin(pending, DISPOSE_COMPACTION_ABORT_GRACE_MS);
|
|
4131
|
+
}
|
|
4132
|
+
}
|
|
3926
4133
|
this.cacheDiagnostics.reset();
|
|
3927
4134
|
this.diagnosticsRecorder?.finalize();
|
|
3928
4135
|
this.managerAbortSignal?.removeEventListener("abort", this.managerAbortHandler);
|
|
@@ -3971,14 +4178,24 @@ export class AgentSession {
|
|
|
3971
4178
|
: await this.sessionManager.load(sessionPath);
|
|
3972
4179
|
// Use the leaf from the header to walk the correct branch
|
|
3973
4180
|
const loadedMessages = this.sessionManager.getMessages(loaded.entries, loaded.header.leafId);
|
|
3974
|
-
|
|
3975
|
-
|
|
3976
|
-
|
|
4181
|
+
// One backward scan for both latest host checkpoints (no full copies).
|
|
4182
|
+
let savedCompletionReview;
|
|
4183
|
+
let savedVerification;
|
|
4184
|
+
for (let i = loaded.entries.length - 1; i >= 0; i--) {
|
|
4185
|
+
if (savedCompletionReview && savedVerification)
|
|
4186
|
+
break;
|
|
4187
|
+
const entry = loaded.entries[i];
|
|
4188
|
+
if (entry?.type !== "custom")
|
|
4189
|
+
continue;
|
|
4190
|
+
if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
|
|
4191
|
+
savedCompletionReview = entry;
|
|
4192
|
+
}
|
|
4193
|
+
else if (!savedVerification && entry.kind === VERIFICATION_STATE_KIND) {
|
|
4194
|
+
savedVerification = entry;
|
|
4195
|
+
}
|
|
4196
|
+
}
|
|
3977
4197
|
this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
|
|
3978
4198
|
this.verificationTracker.clearBackground();
|
|
3979
|
-
const savedVerification = [...loaded.entries]
|
|
3980
|
-
.reverse()
|
|
3981
|
-
.find((entry) => entry.type === "custom" && entry.kind === VERIFICATION_STATE_KIND);
|
|
3982
4199
|
if (savedVerification?.type === "custom") {
|
|
3983
4200
|
this.verificationGate.restore(savedVerification.data);
|
|
3984
4201
|
}
|
|
@@ -4047,6 +4264,7 @@ export class AgentSession {
|
|
|
4047
4264
|
model: this.model,
|
|
4048
4265
|
contextWindow,
|
|
4049
4266
|
threshold: this.settingsManager.get("compactThreshold"),
|
|
4267
|
+
compactAtTokens: this.settingsManager.get("compactAtTokens"),
|
|
4050
4268
|
accountId: creds.accountId,
|
|
4051
4269
|
approvedPlanPath: this.approvedPlanPath,
|
|
4052
4270
|
});
|