@kenkaiiii/ggcoder 5.87.2 → 5.88.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.
Files changed (117) hide show
  1. package/dist/app-sidecar.js +36 -7
  2. package/dist/app-sidecar.js.map +1 -1
  3. package/dist/cli.js +26 -4
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +2 -0
  6. package/dist/config.js +5 -0
  7. package/dist/config.js.map +1 -1
  8. package/dist/core/agent-session.d.ts +41 -1
  9. package/dist/core/agent-session.js +232 -38
  10. package/dist/core/agent-session.js.map +1 -1
  11. package/dist/core/cache-diagnostics.d.ts +4 -0
  12. package/dist/core/cache-diagnostics.js +3 -0
  13. package/dist/core/cache-diagnostics.js.map +1 -1
  14. package/dist/core/checkpoint-store.d.ts +17 -0
  15. package/dist/core/checkpoint-store.js +72 -0
  16. package/dist/core/checkpoint-store.js.map +1 -1
  17. package/dist/core/compaction/compactor.d.ts +17 -0
  18. package/dist/core/compaction/compactor.js +124 -7
  19. package/dist/core/compaction/compactor.js.map +1 -1
  20. package/dist/core/compaction/policy.d.ts +18 -0
  21. package/dist/core/compaction/policy.js +24 -5
  22. package/dist/core/compaction/policy.js.map +1 -1
  23. package/dist/core/compaction/tool-result-pruner.d.ts +10 -0
  24. package/dist/core/compaction/tool-result-pruner.js +14 -0
  25. package/dist/core/compaction/tool-result-pruner.js.map +1 -1
  26. package/dist/core/internal-diagnostics.d.ts +17 -0
  27. package/dist/core/internal-diagnostics.js +45 -0
  28. package/dist/core/internal-diagnostics.js.map +1 -1
  29. package/dist/core/logger.d.ts +5 -0
  30. package/dist/core/logger.js +10 -2
  31. package/dist/core/logger.js.map +1 -1
  32. package/dist/core/lsp/edit-telemetry.js +3 -1
  33. package/dist/core/lsp/edit-telemetry.js.map +1 -1
  34. package/dist/core/lsp/manager.d.ts +15 -0
  35. package/dist/core/lsp/manager.js +31 -0
  36. package/dist/core/lsp/manager.js.map +1 -1
  37. package/dist/core/plan-delta.d.ts +23 -0
  38. package/dist/core/plan-delta.js +36 -0
  39. package/dist/core/plan-delta.js.map +1 -0
  40. package/dist/core/process-gate.d.ts +17 -0
  41. package/dist/core/process-gate.js +24 -0
  42. package/dist/core/process-gate.js.map +1 -1
  43. package/dist/core/session-history.js +2 -2
  44. package/dist/core/session-history.js.map +1 -1
  45. package/dist/core/session-manager.d.ts +1 -0
  46. package/dist/core/session-manager.js +34 -6
  47. package/dist/core/session-manager.js.map +1 -1
  48. package/dist/core/session-preview.js +2 -2
  49. package/dist/core/session-preview.js.map +1 -1
  50. package/dist/core/session-summary-index.d.ts +18 -4
  51. package/dist/core/session-summary-index.js +28 -8
  52. package/dist/core/session-summary-index.js.map +1 -1
  53. package/dist/core/settings-manager.d.ts +2 -0
  54. package/dist/core/settings-manager.js +10 -0
  55. package/dist/core/settings-manager.js.map +1 -1
  56. package/dist/core/shell.d.ts +4 -0
  57. package/dist/core/shell.js +15 -1
  58. package/dist/core/shell.js.map +1 -1
  59. package/dist/core/steering.d.ts +4 -0
  60. package/dist/core/steering.js +8 -1
  61. package/dist/core/steering.js.map +1 -1
  62. package/dist/core/stream-diag-level.d.ts +3 -0
  63. package/dist/core/stream-diag-level.js +24 -0
  64. package/dist/core/stream-diag-level.js.map +1 -0
  65. package/dist/core/subagent-manager.d.ts +11 -0
  66. package/dist/core/subagent-manager.js +13 -4
  67. package/dist/core/subagent-manager.js.map +1 -1
  68. package/dist/core/subagent-receipt.d.ts +1 -1
  69. package/dist/core/subagent-receipt.js +1 -1
  70. package/dist/interactive.js +1 -0
  71. package/dist/interactive.js.map +1 -1
  72. package/dist/subagent-entry.d.ts +1 -0
  73. package/dist/subagent-entry.js +50 -0
  74. package/dist/subagent-entry.js.map +1 -0
  75. package/dist/system-prompt.d.ts +2 -0
  76. package/dist/system-prompt.js +2 -2
  77. package/dist/system-prompt.js.map +1 -1
  78. package/dist/tools/bash.js +11 -6
  79. package/dist/tools/bash.js.map +1 -1
  80. package/dist/tools/checklist.js +6 -11
  81. package/dist/tools/checklist.js.map +1 -1
  82. package/dist/tools/debug.js +6 -9
  83. package/dist/tools/debug.js.map +1 -1
  84. package/dist/tools/find.d.ts +9 -0
  85. package/dist/tools/find.js +38 -1
  86. package/dist/tools/find.js.map +1 -1
  87. package/dist/tools/index.d.ts +2 -0
  88. package/dist/tools/index.js +2 -2
  89. package/dist/tools/index.js.map +1 -1
  90. package/dist/tools/overflow.d.ts +2 -0
  91. package/dist/tools/overflow.js +10 -0
  92. package/dist/tools/overflow.js.map +1 -1
  93. package/dist/tools/read.js +3 -3
  94. package/dist/tools/read.js.map +1 -1
  95. package/dist/tools/routine-output.d.ts +9 -0
  96. package/dist/tools/routine-output.js +78 -0
  97. package/dist/tools/routine-output.js.map +1 -1
  98. package/dist/tools/screenshot.js +6 -10
  99. package/dist/tools/screenshot.js.map +1 -1
  100. package/dist/tools/steroids.js +12 -25
  101. package/dist/tools/steroids.js.map +1 -1
  102. package/dist/tools/subagent-control.js +55 -5
  103. package/dist/tools/subagent-control.js.map +1 -1
  104. package/dist/tools/subagent-shared.d.ts +19 -2
  105. package/dist/tools/subagent-shared.js +35 -10
  106. package/dist/tools/subagent-shared.js.map +1 -1
  107. package/dist/tools/subagent.js +19 -3
  108. package/dist/tools/subagent.js.map +1 -1
  109. package/dist/tools/tool-search.js +7 -1
  110. package/dist/tools/tool-search.js.map +1 -1
  111. package/dist/tools/truncate.js +4 -8
  112. package/dist/tools/truncate.js.map +1 -1
  113. package/dist/ui/App.js +8 -18
  114. package/dist/ui/App.js.map +1 -1
  115. package/dist/ui/hooks/useContextCompaction.js +1 -0
  116. package/dist/ui/hooks/useContextCompaction.js.map +1 -1
  117. 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";
@@ -127,6 +128,26 @@ export { resolveSessionToolResultCharLimit, resolveSessionTurnToolResultCharLimi
127
128
  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
129
  /** Distinct security rows one run may add to the chat (and session file). */
129
130
  const MAX_SECURITY_ROWS_PER_RUN = 20;
131
+ /** How long dispose waits for a post-turn compaction before aborting it. */
132
+ export const DISPOSE_COMPACTION_WAIT_MS = 2_500;
133
+ /** Grace after aborting it, for the compaction to unwind. */
134
+ const DISPOSE_COMPACTION_ABORT_GRACE_MS = 500;
135
+ /** Resolves true if `promise` settles within `ms`, else false. Never rejects. */
136
+ async function settleWithin(promise, ms) {
137
+ let timer;
138
+ const timeout = new Promise((resolve) => {
139
+ timer = setTimeout(() => resolve(false), ms);
140
+ });
141
+ try {
142
+ return await Promise.race([
143
+ promise.then(() => true, () => true),
144
+ timeout,
145
+ ]);
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ }
150
+ }
130
151
  /**
131
152
  * A chat row's target: first line, no control or bidi-override characters
132
153
  * (they could make a command look like another), at most 120 chars.
@@ -220,6 +241,8 @@ export class AgentSession {
220
241
  renderedEnvironment = {};
221
242
  /** Project files as of the first prompt build (undefined until then). */
222
243
  projectFiles;
244
+ /** `git ls-files` started at the top of initialize(), overlapping the rest of setup. */
245
+ projectFilesPending;
223
246
  /** Wall-clock start of the current run; scopes the background-process gate. */
224
247
  runStartedAt = 0;
225
248
  /** Gate injections spent this run, capped by MAX_PROCESS_GATE_INJECTIONS. */
@@ -243,6 +266,8 @@ export class AgentSession {
243
266
  compactionArmedForNextRun = false;
244
267
  /** In-flight post-turn (background) compaction, if any. */
245
268
  postTurnCompaction;
269
+ /** Aborts the in-flight post-turn compaction (dispose caps its wait). */
270
+ postTurnCompactionAbort;
246
271
  lastCompactionCompacted = false;
247
272
  compactionRetryAfter = 0;
248
273
  /**
@@ -310,6 +335,10 @@ export class AgentSession {
310
335
  * can discover and promote them; a promoted name drops out of this list.
311
336
  */
312
337
  deferredBuiltinToolNames = [];
338
+ /** Deferred built-ins in tier order, fixed at session start. Sent as the
339
+ * provider's on-demand catalog (see gg-ai `deferredTools`) so promoting one
340
+ * loads it through the transcript and the cached tools block stays put. */
341
+ deferredToolCatalog = [];
313
342
  provider;
314
343
  model;
315
344
  cwd;
@@ -326,6 +355,14 @@ export class AgentSession {
326
355
  agentPrompt;
327
356
  /** Stable prompt prefix retained separately from the volatile uncached tail. */
328
357
  baseSystemPrompt = "";
358
+ /** Plan state rendered into the cached system prompt. */
359
+ promptPlanState = { planMode: false, approvedPlanPath: undefined };
360
+ /** Plan state the model has been told (prompt or appended notice). */
361
+ seenPlanState = { planMode: false, approvedPlanPath: undefined };
362
+ /** Plan notice waiting for the next request, with the state it describes. */
363
+ pendingPlanNotice = null;
364
+ /** Latest plan notice appended — re-announced if compaction drops it. */
365
+ lastPlanNotice = null;
329
366
  /**
330
367
  * Project languages whose style packs and verify commands are in the
331
368
  * standard prompt. Only ever grows within a session (same policy as the
@@ -431,6 +468,12 @@ export class AgentSession {
431
468
  // so it overlaps session setup and the user's typing instead.
432
469
  if (this.provider === "anthropic")
433
470
  void getClaudeCliUserAgent().catch(() => { });
471
+ // The prompt's file list is a `git ls-files` (~30 ms on a mid-size repo)
472
+ // that nothing before buildBasePrompt depends on: start it now so it runs
473
+ // alongside settings/auth/skills/tools instead of after them.
474
+ if (!this.customSystemPrompt && this.projectFiles === undefined) {
475
+ this.projectFilesPending = listProjectFiles(this.cwd);
476
+ }
434
477
  const paths = await ensureAppDirs();
435
478
  // Load settings & auth
436
479
  this.settingsManager = new SettingsManager(paths.settingsFile);
@@ -500,6 +543,7 @@ export class AgentSession {
500
543
  additionalRoots: this.additionalRoots,
501
544
  }),
502
545
  getPackageCooldownDays: () => this.settingsManager.get("packageCooldownDays"),
546
+ getBashPath: () => this.settingsManager.get("bashPath"),
503
547
  getNetworkPolicy: () => ({
504
548
  mode: this.settingsManager.get("networkMode"),
505
549
  allow: this.settingsManager.get("networkAllow"),
@@ -597,6 +641,7 @@ export class AgentSession {
597
641
  // sits inside the cached prefix stays byte-stable across turns.
598
642
  this.tools = core;
599
643
  this.deferredBuiltinToolNames = deferred.map((t) => t.name);
644
+ this.deferredToolCatalog = [...deferred];
600
645
  this.mcp.addDeferred(deferred);
601
646
  }
602
647
  }
@@ -734,6 +779,7 @@ export class AgentSession {
734
779
  await this.extensionLoader.loadAll(paths.extensionsDir, extContext);
735
780
  }
736
781
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
782
+ this.preconnect();
737
783
  }
738
784
  /**
739
785
  * Whether a tool name is permitted for this session. With no `allowedTools`
@@ -923,8 +969,17 @@ export class AgentSession {
923
969
  const result = await tool.execute(args, context);
924
970
  if (when(args)) {
925
971
  const missing = followUps.filter((name) => !this.tools.some((t) => t.name === name));
926
- if (missing.length > 0)
927
- this.tools.push(...this.mcp.promote(missing));
972
+ const promoted = missing.length > 0 ? this.mcp.promote(missing) : [];
973
+ if (promoted.length > 0) {
974
+ this.tools.push(...promoted);
975
+ // The trigger's result is where the follow-ups load (cache-safe
976
+ // transports load them in the transcript, not the tools block).
977
+ const structured = typeof result === "string" ? { content: result } : result;
978
+ return {
979
+ ...structured,
980
+ loadedTools: [...(structured.loadedTools ?? []), ...promoted.map((t) => t.name)],
981
+ };
982
+ }
928
983
  }
929
984
  return result;
930
985
  },
@@ -1290,6 +1345,11 @@ export class AgentSession {
1290
1345
  // never been told about. The note states the facts outright rather than
1291
1346
  // referring to a section such a prompt does not have.
1292
1347
  const environmentDelta = buildEnvDeltaMessage(this.renderedEnvironment, this.promptEnvironment());
1348
+ // Plan mode toggled / plan approved mid-run: appended, never re-rendered.
1349
+ const planNotice = this.takePlanNotice();
1350
+ if (planNotice) {
1351
+ log("INFO", "session", "Injecting plan state update instead of rebuilding the prompt");
1352
+ }
1293
1353
  if (environmentDelta) {
1294
1354
  // The model has now been told; only a further change re-triggers this.
1295
1355
  this.renderedEnvironment = this.promptEnvironment();
@@ -1355,13 +1415,15 @@ export class AgentSession {
1355
1415
  });
1356
1416
  return [
1357
1417
  ...(environmentDelta ? [environmentDelta] : []),
1418
+ ...(planNotice ? [planNotice] : []),
1358
1419
  ...steeringMessages,
1359
1420
  ...(notificationMessage ? [notificationMessage] : []),
1360
1421
  ];
1361
1422
  }
1362
- if (environmentDelta || notificationMessage) {
1423
+ if (environmentDelta || planNotice || notificationMessage) {
1363
1424
  return [
1364
1425
  ...(environmentDelta ? [environmentDelta] : []),
1426
+ ...(planNotice ? [planNotice] : []),
1365
1427
  ...(notificationMessage ? [notificationMessage] : []),
1366
1428
  ];
1367
1429
  }
@@ -1596,22 +1658,22 @@ export class AgentSession {
1596
1658
  },
1597
1659
  ]
1598
1660
  : [];
1599
- const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager);
1600
- if (childCompletionFollowUp)
1601
- return [...diagnosticMessages, ...childCompletionFollowUp];
1661
+ const childCompletionFollowUp = buildSubAgentCompletionFollowUp(this.subAgentManager) ?? [];
1602
1662
  // Background processes started this run and never read block completion:
1603
1663
  // their progress/exit checkpoints only land on the steering path, which an
1604
- // agent about to stop never reaches.
1605
- const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected);
1606
- if (processFollowUp) {
1664
+ // agent about to stop never reaches. Sent in the same follow-up as the
1665
+ // child-agent gate: one forced turn can collect both, where returning them
1666
+ // one per stop cost a separate model round-trip each.
1667
+ const processFollowUp = buildProcessCompletionFollowUp(this.processManager?.list() ?? [], this.runStartedAt, this.processGateInjected) ?? [];
1668
+ if (processFollowUp.length > 0) {
1607
1669
  this.processGateInjected += 1;
1608
1670
  log("INFO", "process-gate", "Injecting background-process completion gate", {
1609
1671
  injected: String(this.processGateInjected),
1610
1672
  });
1611
- return [...diagnosticMessages, ...processFollowUp];
1612
1673
  }
1613
- if (diagnosticMessages.length > 0)
1614
- return diagnosticMessages;
1674
+ const gateMessages = mergeCompletionGateFollowUps(diagnosticMessages, childCompletionFollowUp, processFollowUp);
1675
+ if (gateMessages)
1676
+ return gateMessages;
1615
1677
  await this.rerunRefusedCheck();
1616
1678
  if (shouldNudgePlanSubmission({
1617
1679
  enabled: this.opts.planSubmissionGate === true,
@@ -1773,6 +1835,7 @@ export class AgentSession {
1773
1835
  model: this.model,
1774
1836
  contextWindow,
1775
1837
  threshold: this.settingsManager.get("compactThreshold"),
1838
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
1776
1839
  accountId: creds.accountId,
1777
1840
  approvedPlanPath: this.approvedPlanPath,
1778
1841
  });
@@ -1830,6 +1893,7 @@ export class AgentSession {
1830
1893
  provider: this.provider,
1831
1894
  model: this.model,
1832
1895
  tools: options.disableTools ? [] : this.tools,
1896
+ ...(options.disableTools ? {} : { deferredTools: this.deferredToolCatalog }),
1833
1897
  webSearch: options.disableTools ? false : () => this.nativeWebSearchOn(),
1834
1898
  maxTokens: this.requestMaxTokens(accountId),
1835
1899
  maxTurns: this.opts.maxTurns,
@@ -1892,10 +1956,15 @@ export class AgentSession {
1892
1956
  promptCacheKey: this.getPromptCacheKey(),
1893
1957
  },
1894
1958
  });
1895
- log("INFO", "cache", "Prepared context", {
1896
- sessionId: this.sessionId || this.transportSessionId,
1897
- data: JSON.stringify(report),
1898
- });
1959
+ // "Context cache outcome" (persistTurnMetric) repeats this whole report
1960
+ // with usage attached, so only log the prepared report on its own when
1961
+ // it carries a cache-relevant change or risk worth seeing pre-response.
1962
+ if (report.changes.length > 0 || report.thinkingPrefixRiskBlocks > 0) {
1963
+ log("INFO", "cache", "Prepared context", {
1964
+ sessionId: this.sessionId || this.transportSessionId,
1965
+ data: JSON.stringify(report),
1966
+ });
1967
+ }
1899
1968
  if (report.thinkingPrefixRiskBlocks > 0) {
1900
1969
  log("WARN", "cache", "Possible signed-thinking prefix mismatch; not server verified", {
1901
1970
  sessionId: this.sessionId || this.transportSessionId,
@@ -1958,6 +2027,7 @@ export class AgentSession {
1958
2027
  model: this.model,
1959
2028
  contextWindow,
1960
2029
  threshold: this.settingsManager.get("compactThreshold"),
2030
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
1961
2031
  accountId,
1962
2032
  approvedPlanPath: this.approvedPlanPath,
1963
2033
  });
@@ -1984,7 +2054,10 @@ export class AgentSession {
1984
2054
  // anchors; drop the retained usage afterwards since it counted the
1985
2055
  // pruned content.
1986
2056
  if (shouldPruneToolResults(activeTokens, policy.targetTokens)) {
1987
- const pruneResult = pruneStaleToolResults(messages);
2057
+ const cacheCold = this.getCacheExpiryStatus()?.expired ?? false;
2058
+ const pruneResult = pruneStaleToolResults(messages, {
2059
+ minimumTokens: pruneMinimumTokens(activeTokens, cacheCold),
2060
+ });
1988
2061
  if (pruneResult.pruned) {
1989
2062
  this.cacheDiagnostics.noteEdit("tool_prune", pruneResult.freedTokens);
1990
2063
  this.providerContext = null;
@@ -2007,6 +2080,8 @@ export class AgentSession {
2007
2080
  // An approved plan runs as ONE run, so step boundaries are only
2008
2081
  // visible here, between model steps — not after the run ends.
2009
2082
  const planStep = this.observePlanStepProgress(messages, contextWindow, activeTokens);
2083
+ // The decision line carries the outcome (compact=) next to its inputs.
2084
+ const overLimit = shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens);
2010
2085
  log("INFO", "compaction", "In-flight compaction decision", {
2011
2086
  provider: this.provider,
2012
2087
  model: this.model,
@@ -2014,10 +2089,10 @@ export class AgentSession {
2014
2089
  contextWindow: String(contextWindow),
2015
2090
  activeTokens: String(activeTokens),
2016
2091
  triggerLimit: String(policy.targetTokens),
2092
+ compact: String(overLimit || Boolean(planStep?.compact)),
2017
2093
  ...(planStep ? { planStep: `${planStep.compact} (${planStep.reason})` } : {}),
2018
2094
  });
2019
- if (!shouldCompact(messages, contextWindow, policy.threshold, activeTokens, policy.targetTokens) &&
2020
- !planStep?.compact)
2095
+ if (!overLimit && !planStep?.compact)
2021
2096
  return messages;
2022
2097
  }
2023
2098
  // compact() operates on this.messages, while an earlier transform may
@@ -2211,6 +2286,8 @@ export class AgentSession {
2211
2286
  // booted on e.g. Kimi (256K) keeps sending that cap after switching to a
2212
2287
  // smaller model (Opus 128K), which the provider rejects.
2213
2288
  this.maxTokens = this.resolveMaxTokens(model);
2289
+ if (changed)
2290
+ this.preconnect();
2214
2291
  this.eventBus.emit("model_change", {
2215
2292
  provider: this.provider,
2216
2293
  model: this.model,
@@ -2535,6 +2612,7 @@ export class AgentSession {
2535
2612
  model: this.model,
2536
2613
  contextWindow,
2537
2614
  threshold: this.settingsManager.get("compactThreshold"),
2615
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2538
2616
  accountId: creds.accountId,
2539
2617
  approvedPlanPath: this.approvedPlanPath,
2540
2618
  });
@@ -2561,9 +2639,11 @@ export class AgentSession {
2561
2639
  activeTokens: activeTokens === undefined ? "estimated" : String(activeTokens),
2562
2640
  triggerLimit: String(policy.targetTokens),
2563
2641
  });
2642
+ const postTurnAbort = new AbortController();
2643
+ this.postTurnCompactionAbort = postTurnAbort;
2564
2644
  this.postTurnCompaction = (async () => {
2565
2645
  try {
2566
- await this.compact(creds, "automatic");
2646
+ await this.compact(creds, "automatic", undefined, postTurnAbort.signal);
2567
2647
  if (this.lastCompactionCompacted) {
2568
2648
  // Arm re-grounding for the next turn. resetHookState clears
2569
2649
  // compactionOccurred at run start, before the injection point, so
@@ -2583,13 +2663,20 @@ export class AgentSession {
2583
2663
  }
2584
2664
  finally {
2585
2665
  this.postTurnCompaction = undefined;
2666
+ if (this.postTurnCompactionAbort === postTurnAbort)
2667
+ this.postTurnCompactionAbort = undefined;
2586
2668
  }
2587
2669
  })();
2588
2670
  }
2589
2671
  async compact(existingCredentials, mode = "manual",
2590
2672
  /** User-stated focus (`/compact <focus>`): what must survive verbatim. */
2591
- focus) {
2673
+ focus,
2674
+ /** Extra abort source (post-turn compaction, cancelled by dispose). */
2675
+ abortSignal) {
2592
2676
  this.lastCompactionCompacted = false;
2677
+ const compactionSignal = abortSignal && this.opts.signal
2678
+ ? AbortSignal.any([this.opts.signal, abortSignal])
2679
+ : (abortSignal ?? this.opts.signal);
2593
2680
  const creds = existingCredentials ??
2594
2681
  (await this.authStorage.resolveCredentials(this.provider, {
2595
2682
  storageKeys: this.currentAuthStorageKeys(),
@@ -2603,6 +2690,7 @@ export class AgentSession {
2603
2690
  model: this.model,
2604
2691
  contextWindow,
2605
2692
  threshold: this.settingsManager.get("compactThreshold"),
2693
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
2606
2694
  accountId: creds.accountId,
2607
2695
  approvedPlanPath: this.approvedPlanPath,
2608
2696
  });
@@ -2620,7 +2708,7 @@ export class AgentSession {
2620
2708
  baseUrl: this.baseUrl ?? creds.baseUrl,
2621
2709
  contextWindow,
2622
2710
  targetTokens: policy.targetTokens,
2623
- signal: this.opts.signal,
2711
+ signal: compactionSignal,
2624
2712
  approvedPlanPath: this.approvedPlanPath,
2625
2713
  focus,
2626
2714
  });
@@ -2641,7 +2729,7 @@ export class AgentSession {
2641
2729
  }
2642
2730
  else {
2643
2731
  const conversationId = this.conversationId;
2644
- await this.sessionManager.withCompactionLease(conversationId, this.opts.signal, async () => {
2732
+ await this.sessionManager.withCompactionLease(conversationId, compactionSignal, async () => {
2645
2733
  let sourceFingerprint = computeSourceFingerprint(this.messages);
2646
2734
  const canonicalPath = await this.sessionManager.resolveCanonicalSession(conversationId, this.cwd);
2647
2735
  if (canonicalPath && canonicalPath !== this.sessionPath) {
@@ -3214,7 +3302,7 @@ export class AgentSession {
3214
3302
  // is about to be drafted); exiting keeps it (set explicitly via accept).
3215
3303
  if (active)
3216
3304
  this.approvedPlanPath = undefined;
3217
- await this.rebuildSystemPromptInPlace();
3305
+ await this.applyPlanStateChange();
3218
3306
  }
3219
3307
  /**
3220
3308
  * Bake an approved plan into the system prompt so the model is told to emit
@@ -3224,7 +3312,45 @@ export class AgentSession {
3224
3312
  */
3225
3313
  async setApprovedPlan(approvedPlanPath) {
3226
3314
  this.approvedPlanPath = approvedPlanPath;
3227
- await this.rebuildSystemPromptInPlace();
3315
+ await this.applyPlanStateChange();
3316
+ }
3317
+ /**
3318
+ * Before the conversation starts, render plan state into the prompt. After,
3319
+ * the prompt is a cached prefix: queue an appended notice instead, so the
3320
+ * cached bytes stay identical (a rebuild re-sent the whole history).
3321
+ */
3322
+ async applyPlanStateChange() {
3323
+ if (this.customSystemPrompt || this.agentPrompt !== undefined)
3324
+ return;
3325
+ if (!this.messages.some((message) => message.role !== "system")) {
3326
+ this.pendingPlanNotice = null;
3327
+ await this.rebuildSystemPromptInPlace();
3328
+ return;
3329
+ }
3330
+ const state = {
3331
+ planMode: this.planModeRef.current,
3332
+ approvedPlanPath: this.approvedPlanPath,
3333
+ };
3334
+ const message = await buildPlanStateMessage(this.seenPlanState, state);
3335
+ this.pendingPlanNotice = message ? { message, state } : null;
3336
+ }
3337
+ /** The plan notice to append now, if any (pending, or a compacted-away one). */
3338
+ takePlanNotice() {
3339
+ if (this.pendingPlanNotice) {
3340
+ const { message, state } = this.pendingPlanNotice;
3341
+ this.pendingPlanNotice = null;
3342
+ this.seenPlanState = state;
3343
+ this.lastPlanNotice = message;
3344
+ return message;
3345
+ }
3346
+ if (this.lastPlanNotice &&
3347
+ !samePlanState(this.seenPlanState, this.promptPlanState) &&
3348
+ !this.messages.includes(this.lastPlanNotice)) {
3349
+ const again = { ...this.lastPlanNotice };
3350
+ this.lastPlanNotice = again;
3351
+ return again;
3352
+ }
3353
+ return null;
3228
3354
  }
3229
3355
  /** Extra workspace roots added with `/add-dir`, in the order added. */
3230
3356
  getAdditionalRoots() {
@@ -3334,8 +3460,11 @@ export class AgentSession {
3334
3460
  return this.customSystemPrompt;
3335
3461
  // Listed once: a rebuild (plan mode, /add-dir, compaction) must not churn the
3336
3462
  // prompt as the agent adds files.
3337
- if (this.projectFiles === undefined)
3338
- this.projectFiles = await listProjectFiles(this.cwd);
3463
+ if (this.projectFiles === undefined) {
3464
+ const pending = this.projectFilesPending;
3465
+ this.projectFilesPending = undefined;
3466
+ this.projectFiles = await (pending ?? listProjectFiles(this.cwd));
3467
+ }
3339
3468
  const toolNames = this.tools.map((tool) => tool.name);
3340
3469
  const deferredToolNames = this.deferredToolNamesForPrompt(toolNames);
3341
3470
  // Whatever is rendered now is what the model has been told.
@@ -3381,6 +3510,13 @@ export class AgentSession {
3381
3510
  * update is saved in order with the rest of the conversation.
3382
3511
  */
3383
3512
  async announceNewLanguages() {
3513
+ const planNotice = this.takePlanNotice();
3514
+ if (planNotice) {
3515
+ this.messages.push(planNotice);
3516
+ await this.persistMessage(planNotice);
3517
+ this.lastPersistedIndex = this.messages.length;
3518
+ log("INFO", "session", "Appended plan state update instead of rebuilding the prompt");
3519
+ }
3384
3520
  if (!this.hasReply())
3385
3521
  return; // the next request rebuilds the prompt instead
3386
3522
  this.refreshActiveLanguages();
@@ -3446,6 +3582,13 @@ export class AgentSession {
3446
3582
  return;
3447
3583
  const rebuilt = await this.buildBasePrompt(this.planModeRef.current, this.approvedPlanPath);
3448
3584
  this.baseSystemPrompt = rebuilt;
3585
+ this.promptPlanState = {
3586
+ planMode: this.planModeRef.current,
3587
+ approvedPlanPath: this.approvedPlanPath,
3588
+ };
3589
+ this.seenPlanState = this.promptPlanState;
3590
+ this.pendingPlanNotice = null;
3591
+ this.lastPlanNotice = null;
3449
3592
  const content = this.withSystemPromptTail(rebuilt);
3450
3593
  if (this.messages[0]?.role === "system") {
3451
3594
  this.messages[0] = { role: "system", content };
@@ -3753,6 +3896,33 @@ export class AgentSession {
3753
3896
  runLoopDepth = 0;
3754
3897
  lastRealRequestAt = 0;
3755
3898
  lastPrewarmAt = 0;
3899
+ /** Last connection pre-open per provider origin (see {@link preconnect}). */
3900
+ preconnectedAt = new Map();
3901
+ /**
3902
+ * Fire-and-forget: open the TLS connection to the active provider before the
3903
+ * first request, through the shared keep-alive pool. Zero tokens — an
3904
+ * unauthenticated HEAD; skipped for local endpoints and throttled per origin.
3905
+ * Transient sessions (one-shot tools) and test runs never touch the network here.
3906
+ */
3907
+ preconnect() {
3908
+ const enabled = this.opts.preconnect ?? (this.opts.transient !== true && !process.env.VITEST);
3909
+ if (!enabled)
3910
+ return;
3911
+ const provider = this.provider;
3912
+ void this.authStorage
3913
+ .resolveCredentials(provider, { storageKeys: this.currentAuthStorageKeys() })
3914
+ .then((creds) => {
3915
+ if (provider !== this.provider)
3916
+ return;
3917
+ preconnectProvider({
3918
+ provider,
3919
+ baseUrl: this.baseUrl ?? creds.baseUrl,
3920
+ accountId: creds.accountId,
3921
+ warmedAt: this.preconnectedAt,
3922
+ });
3923
+ })
3924
+ .catch(() => { });
3925
+ }
3756
3926
  prewarmController = null;
3757
3927
  /**
3758
3928
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
@@ -3762,6 +3932,8 @@ export class AgentSession {
3762
3932
  * first real reply is a cache read instead of a cold write.
3763
3933
  */
3764
3934
  async prewarm(signal) {
3935
+ // Every provider: the user is typing, so the first request is seconds away.
3936
+ this.preconnect();
3765
3937
  if (this.provider !== "anthropic")
3766
3938
  return { ok: false, reason: "provider" };
3767
3939
  if (this.settingsManager?.get("cachePrewarm") === false) {
@@ -3820,6 +3992,7 @@ export class AgentSession {
3820
3992
  model: this.model,
3821
3993
  messages,
3822
3994
  tools: this.tools,
3995
+ deferredTools: this.deferredToolCatalog,
3823
3996
  webSearch: this.nativeWebSearchOn(),
3824
3997
  maxTokens: this.requestMaxTokens(creds.accountId),
3825
3998
  thinking: this.planModeRef.current
@@ -3921,8 +4094,18 @@ export class AgentSession {
3921
4094
  // the background compact() snapshots and replaces `this.messages`, so
3922
4095
  // letting it run past this point would checkpoint a near-empty history
3923
4096
  // and leak a junk session file after teardown.
3924
- if (this.postTurnCompaction)
3925
- await this.postTurnCompaction;
4097
+ // Capped: a hung summary call must not hold MCP/LSP/sub-agent teardown and
4098
+ // window close hostage. Past the cap it is aborted (compact() checks the
4099
+ // signal before replacing history), with a short grace to unwind.
4100
+ if (this.postTurnCompaction) {
4101
+ const pending = this.postTurnCompaction;
4102
+ const settledInTime = await settleWithin(pending, DISPOSE_COMPACTION_WAIT_MS);
4103
+ if (!settledInTime) {
4104
+ log("WARN", "compaction", "Post-turn compaction still running at dispose — aborting");
4105
+ this.postTurnCompactionAbort?.abort();
4106
+ await settleWithin(pending, DISPOSE_COMPACTION_ABORT_GRACE_MS);
4107
+ }
4108
+ }
3926
4109
  this.cacheDiagnostics.reset();
3927
4110
  this.diagnosticsRecorder?.finalize();
3928
4111
  this.managerAbortSignal?.removeEventListener("abort", this.managerAbortHandler);
@@ -3971,14 +4154,24 @@ export class AgentSession {
3971
4154
  : await this.sessionManager.load(sessionPath);
3972
4155
  // Use the leaf from the header to walk the correct branch
3973
4156
  const loadedMessages = this.sessionManager.getMessages(loaded.entries, loaded.header.leafId);
3974
- const savedCompletionReview = [...loaded.entries]
3975
- .reverse()
3976
- .find((entry) => entry.type === "custom" && entry.kind === COMPLETION_REVIEW_STATE_KIND);
4157
+ // One backward scan for both latest host checkpoints (no full copies).
4158
+ let savedCompletionReview;
4159
+ let savedVerification;
4160
+ for (let i = loaded.entries.length - 1; i >= 0; i--) {
4161
+ if (savedCompletionReview && savedVerification)
4162
+ break;
4163
+ const entry = loaded.entries[i];
4164
+ if (entry?.type !== "custom")
4165
+ continue;
4166
+ if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
4167
+ savedCompletionReview = entry;
4168
+ }
4169
+ else if (!savedVerification && entry.kind === VERIFICATION_STATE_KIND) {
4170
+ savedVerification = entry;
4171
+ }
4172
+ }
3977
4173
  this.opts.completionReview?.restore(savedCompletionReview?.type === "custom" ? savedCompletionReview.data : null);
3978
4174
  this.verificationTracker.clearBackground();
3979
- const savedVerification = [...loaded.entries]
3980
- .reverse()
3981
- .find((entry) => entry.type === "custom" && entry.kind === VERIFICATION_STATE_KIND);
3982
4175
  if (savedVerification?.type === "custom") {
3983
4176
  this.verificationGate.restore(savedVerification.data);
3984
4177
  }
@@ -4047,6 +4240,7 @@ export class AgentSession {
4047
4240
  model: this.model,
4048
4241
  contextWindow,
4049
4242
  threshold: this.settingsManager.get("compactThreshold"),
4243
+ compactAtTokens: this.settingsManager.get("compactAtTokens"),
4050
4244
  accountId: creds.accountId,
4051
4245
  approvedPlanPath: this.approvedPlanPath,
4052
4246
  });