@kenkaiiii/ggcoder 5.95.2 → 5.95.3

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.
@@ -39,7 +39,7 @@ import { createSessionStatsTool } from "../tools/session-stats.js";
39
39
  import { createDiagnoseCommand, isInternalDiagnosticsEnabled, SessionDiagnosticsRecorder, } from "./internal-diagnostics.js";
40
40
  import { log } from "./logger.js";
41
41
  import { CacheDiagnostics } from "./cache-diagnostics.js";
42
- import { assessCacheExpiry, resolveCacheTtl } from "./cache-expiry.js";
42
+ import { assessCacheExpiry, CLAUDE_CODE_CACHE_TTL, resolveCacheTtl, } from "./cache-expiry.js";
43
43
  import { setEstimatorModel, calibrateEstimatorFromUsage, estimateConversationTokens, } from "./compaction/token-estimator.js";
44
44
  import { calculateActiveContextTokens } from "./compaction/active-context.js";
45
45
  import { resolveCompactionPolicy } from "./compaction/policy.js";
@@ -51,7 +51,7 @@ import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } fr
51
51
  import { discoverAgents } from "./agents.js";
52
52
  import { enhancePrompt } from "../utils/prompt-enhancer.js";
53
53
  import { assistantText, renderTranscript } from "./claude-code/events.js";
54
- import { claudeCodeLoop } from "./claude-code/loop.js";
54
+ import { ClaudeCodeLiveSession, systemPrompt } from "./claude-code/live-session.js";
55
55
  import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, claudeCodeSessionEntryData, parseClaudeCodeSessionState, } from "./claude-code/session-sync.js";
56
56
  import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
57
57
  import { detectLanguages, detectProjectStack } from "./language-detector.js";
@@ -325,6 +325,9 @@ export class AgentSession {
325
325
  // every turn boundary, so an index captured by the UI can point at a
326
326
  // different message (or past the end) by the time the cancel arrives.
327
327
  userQueue = [];
328
+ // Taken into the run but not yet in the transcript. Claude Code takes queued
329
+ // messages at once but reads them at its next turn, so they still show as queued.
330
+ deliveringQueue = [];
328
331
  queueSeq = 0;
329
332
  /** Monotonic count of human-originated prompts; idle-wake budgets reset on it. */
330
333
  humanPromptSeq = 0;
@@ -1004,14 +1007,16 @@ export class AgentSession {
1004
1007
  }
1005
1008
  let sessionId = resume;
1006
1009
  const title = this.sessionPreview?.trim().slice(0, 80);
1007
- const generator = claudeCodeLoop(loopMessages, {
1010
+ const thinking = this.planModeRef.current || options.capThinking
1011
+ ? clampThinkingForPlanMode(this.thinkingLevel)
1012
+ : this.thinkingLevel;
1013
+ const live = await this.claudeCodeLiveFor(process, loopMessages, resume, thinking, options);
1014
+ const generator = live.run(loopMessages, {
1008
1015
  provider: this.provider,
1009
1016
  model: this.model,
1010
1017
  tools: options.disableTools ? [] : this.tools,
1011
1018
  maxTurns: this.opts.maxTurns,
1012
- thinking: this.planModeRef.current || options.capThinking
1013
- ? clampThinkingForPlanMode(this.thinkingLevel)
1014
- : this.thinkingLevel,
1019
+ thinking,
1015
1020
  signal: this.opts.signal,
1016
1021
  maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, undefined),
1017
1022
  transformToolResult: flagUntrustedToolResult,
@@ -1038,11 +1043,26 @@ export class AgentSession {
1038
1043
  try {
1039
1044
  for await (const event of generator) {
1040
1045
  await this.trackHookEvent(event);
1046
+ // Claude Code sends the requests, so the cache-diagnostics pass never
1047
+ // sees them; without a touch every idle chat read as an expired cache.
1048
+ if (event.type === "turn_end" && event.stopReason !== "error") {
1049
+ this.cacheDiagnostics.noteCacheTouch({
1050
+ at: Date.now(),
1051
+ provider: this.provider,
1052
+ model: this.model,
1053
+ policy: CLAUDE_CODE_CACHE_TTL,
1054
+ });
1055
+ }
1041
1056
  this.eventBus.forwardAgentEvent(event);
1042
1057
  }
1043
1058
  }
1044
1059
  finally {
1060
+ // The SDK counts maxTurns per process, so a capped session runs one process per run.
1061
+ if (live !== this.claudeCodeLive?.session)
1062
+ live.close("one-shot");
1045
1063
  this.activeLoopMessages = null;
1064
+ // A stopped run records unplaced messages without an event.
1065
+ this.settleDeliveredMessages(() => true);
1046
1066
  this.messages = loopMessages;
1047
1067
  for (let i = this.lastPersistedIndex; i < this.messages.length; i++) {
1048
1068
  await this.persistMessage(this.messages[i]);
@@ -1052,6 +1072,50 @@ export class AgentSession {
1052
1072
  await this.recordClaudeCodeSession(sessionId);
1053
1073
  }
1054
1074
  }
1075
+ /**
1076
+ * The Claude Code process for this run: the chat's live one when it holds
1077
+ * exactly our history with the same settings, else a new one (the old one is
1078
+ * closed first, so a chat never keeps two).
1079
+ */
1080
+ async claudeCodeLiveFor(process, messages, resume, thinking, options) {
1081
+ const hash = (value) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
1082
+ const key = {
1083
+ executable: process.executable,
1084
+ cwd: process.cwd,
1085
+ model: this.model,
1086
+ system: hash(systemPrompt(messages, undefined)),
1087
+ thinking: thinking ? "on" : "off",
1088
+ tools: options.disableTools ? "off" : "on",
1089
+ };
1090
+ // Per variable, so a restart log names what moved (names only, never values).
1091
+ for (const [name, value] of Object.entries(process.env)) {
1092
+ // The SDK writes this into the daemon's env on its first query(); it sets it for the child anyway.
1093
+ if (name !== "CLAUDE_AGENT_SDK_VERSION")
1094
+ key[`env:${name}`] = hash(value);
1095
+ }
1096
+ const current = this.claudeCodeLive;
1097
+ const changed = current
1098
+ ? [...new Set([...Object.keys(key), ...Object.keys(current.key)])].filter((name) => current.key[name] !== key[name])
1099
+ : [];
1100
+ if (current &&
1101
+ changed.length === 0 &&
1102
+ current.session.alive &&
1103
+ !current.session.busy &&
1104
+ resume !== undefined &&
1105
+ resume === current.session.sessionId &&
1106
+ (await current.session.setEffort(thinking))) {
1107
+ return current.session;
1108
+ }
1109
+ this.closeClaudeCodeLive(changed.length > 0 ? `changed: ${changed.join(",")}` : "history or effort changed");
1110
+ const session = new ClaudeCodeLiveSession();
1111
+ if (!this.opts.maxTurns)
1112
+ this.claudeCodeLive = { session, key };
1113
+ return session;
1114
+ }
1115
+ closeClaudeCodeLive(reason) {
1116
+ this.claudeCodeLive?.session.close(reason);
1117
+ this.claudeCodeLive = null;
1118
+ }
1055
1119
  async recordClaudeCodeSession(sessionId) {
1056
1120
  const history = this.messages.filter((m) => m.role !== "system");
1057
1121
  const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
@@ -1406,6 +1470,9 @@ export class AgentSession {
1406
1470
  // The assistant message for this turn is now in the array.
1407
1471
  await this.flushPendingMessages();
1408
1472
  break;
1473
+ case "steering_message":
1474
+ this.settleDeliveredMessages((m) => m.content === event.content);
1475
+ break;
1409
1476
  case "checkpoint":
1410
1477
  // Tool results for this step are in the array and their side effects
1411
1478
  // already hit the filesystem. Flushing here is what makes a crash lose
@@ -1415,6 +1482,14 @@ export class AgentSession {
1415
1482
  break;
1416
1483
  }
1417
1484
  }
1485
+ /** Drop delivered queued messages and announce the new queue depth. */
1486
+ settleDeliveredMessages(delivered) {
1487
+ const before = this.deliveringQueue.length;
1488
+ this.deliveringQueue = this.deliveringQueue.filter((m) => !delivered(m));
1489
+ if (this.deliveringQueue.length !== before) {
1490
+ this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1491
+ }
1492
+ }
1418
1493
  /**
1419
1494
  * Count full-file `cat` output from the step that just finished as reads, so
1420
1495
  * an edit after `cat` does not cost a second read. Uses the step's results as
@@ -1528,11 +1603,9 @@ export class AgentSession {
1528
1603
  // agent sees them mid-loop instead of after it stops.
1529
1604
  if (this.userQueue.length > 0) {
1530
1605
  const queued = this.userQueue.splice(0);
1531
- // The agent has now consumed these. Announce the new depth immediately so
1532
- // clients can drop the "queued" affordance at the turn boundary rather
1533
- // than holding it until the whole run ends — the message is already in
1534
- // the loop, and showing it as still-pending for minutes is a lie.
1535
- this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1606
+ // `queue_drained` fires when each lands in the transcript (its
1607
+ // steering_message event), not here, so clients drop the "queued" look
1608
+ // when the agent reads it, not minutes later at run end.
1536
1609
  // Frame each queued item as concurrent steering — without this wrapper
1537
1610
  // the model treats a mid-run message as a fresh request that supersedes
1538
1611
  // the original task and silently drops it. ONE message per queued item
@@ -1555,6 +1628,10 @@ export class AgentSession {
1555
1628
  ];
1556
1629
  return { role: "user", content: parts, provenance };
1557
1630
  });
1631
+ steeringMessages.forEach((message, index) => {
1632
+ const { id, text } = queued[index];
1633
+ this.deliveringQueue.push({ id, text, content: message.content });
1634
+ });
1558
1635
  const userShell = this.takeUserShellContext();
1559
1636
  return [
1560
1637
  ...(environmentDelta ? [environmentDelta] : []),
@@ -1973,6 +2050,8 @@ export class AgentSession {
1973
2050
  await this.runClaudeCodeLoop(claudeCode, options);
1974
2051
  return;
1975
2052
  }
2053
+ // Left the Claude subscription route (provider switch, sign-out).
2054
+ this.closeClaudeCodeLive("route changed");
1976
2055
  // Resolve OAuth credentials and run agent loop.
1977
2056
  // On 401, force-refresh the token and retry once — the provider may have
1978
2057
  // revoked the token server-side before the stored expiry (e.g. after a restart).
@@ -2294,6 +2373,7 @@ export class AgentSession {
2294
2373
  }
2295
2374
  finally {
2296
2375
  this.activeLoopMessages = null;
2376
+ this.settleDeliveredMessages(() => true);
2297
2377
  // An in-flight compaction rebinds `this.messages` to the compacted array
2298
2378
  // while the loop keeps appending to `loopMessages`. Resync on every exit
2299
2379
  // — a failed or aborted run included — or the session silently drops
@@ -3006,6 +3086,7 @@ export class AgentSession {
3006
3086
  // into the fresh session (e.g. an accepted plan's build would inherit the
3007
3087
  // whole planning conversation and lose the approved-plan prompt).
3008
3088
  await this.settlePostTurnCompaction();
3089
+ this.closeClaudeCodeLive("new session");
3009
3090
  this.cacheDiagnostics.reset();
3010
3091
  // Approved-plan execution is a clean checkpoint of the same conversation;
3011
3092
  // explicit new sessions reset the conversation identity.
@@ -3053,6 +3134,7 @@ export class AgentSession {
3053
3134
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
3054
3135
  }
3055
3136
  async loadSession(sessionPath) {
3137
+ this.closeClaudeCodeLive("session loaded");
3056
3138
  await this.loadExistingSession(sessionPath);
3057
3139
  this.cacheDiagnostics.reset();
3058
3140
  if (this.sessionId)
@@ -3332,9 +3414,13 @@ export class AgentSession {
3332
3414
  this.messages.push(message);
3333
3415
  await this.persistMessage(message);
3334
3416
  }
3335
- /** Pending queued messages (id + text), oldest first, for client display. */
3417
+ /** Pending queued messages (id + text), oldest first, for client display.
3418
+ * `delivering` ones are already with the agent and can no longer be cancelled. */
3336
3419
  listQueuedMessages() {
3337
- return this.userQueue.map((m) => ({ id: m.id, text: m.text }));
3420
+ return [
3421
+ ...this.deliveringQueue.map((m) => ({ id: m.id, text: m.text, delivering: true })),
3422
+ ...this.userQueue.map((m) => ({ id: m.id, text: m.text })),
3423
+ ];
3338
3424
  }
3339
3425
  /** Cancel one pending message by id. Returns true if it was still queued.
3340
3426
  * A false return is the normal race rather than an error: the message drained
@@ -3471,6 +3557,8 @@ export class AgentSession {
3471
3557
  */
3472
3558
  stopBackgroundProcesses() {
3473
3559
  this.processManager?.shutdownAll();
3560
+ // Synchronous, so app quit stops Claude Code even when later teardown hangs.
3561
+ this.closeClaudeCodeLive("shutdown");
3474
3562
  }
3475
3563
  /** Replace a host-owned system prompt in place without resetting conversation history. */
3476
3564
  setCustomSystemPrompt(systemPrompt, promptCacheKeyPrefix) {
@@ -4143,6 +4231,8 @@ export class AgentSession {
4143
4231
  prewarmController = null;
4144
4232
  /** Claude Code session that has seen this history (Claude subscription route). */
4145
4233
  claudeCodeSession = null;
4234
+ /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4235
+ claudeCodeLive = null;
4146
4236
  /**
4147
4237
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
4148
4238
  * (desktop app calls this on the first keystroke after opening a chat or an