@kenkaiiii/ggcoder 5.95.2 → 5.95.4

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 (39) hide show
  1. package/NOTICE +0 -1
  2. package/dist/app-sidecar/auth-routes.js +13 -2
  3. package/dist/app-sidecar/auth-routes.js.map +1 -1
  4. package/dist/app-sidecar/desktop-guidance.d.ts +1 -0
  5. package/dist/app-sidecar/desktop-guidance.js +27 -0
  6. package/dist/app-sidecar/desktop-guidance.js.map +1 -0
  7. package/dist/app-sidecar/poll.d.ts +39 -0
  8. package/dist/app-sidecar/poll.js +184 -0
  9. package/dist/app-sidecar/poll.js.map +1 -0
  10. package/dist/app-sidecar/prompt-routes.js +9 -2
  11. package/dist/app-sidecar/prompt-routes.js.map +1 -1
  12. package/dist/app-sidecar.js +20 -62
  13. package/dist/app-sidecar.js.map +1 -1
  14. package/dist/core/agent-session.d.ts +19 -2
  15. package/dist/core/agent-session.js +115 -15
  16. package/dist/core/agent-session.js.map +1 -1
  17. package/dist/core/ask-user.d.ts +1 -0
  18. package/dist/core/ask-user.js +8 -0
  19. package/dist/core/ask-user.js.map +1 -1
  20. package/dist/core/cache-expiry.d.ts +2 -0
  21. package/dist/core/cache-expiry.js +6 -0
  22. package/dist/core/cache-expiry.js.map +1 -1
  23. package/dist/core/claude-code/complete.js +0 -1
  24. package/dist/core/claude-code/complete.js.map +1 -1
  25. package/dist/core/claude-code/live-session.d.ts +92 -0
  26. package/dist/core/claude-code/live-session.js +519 -0
  27. package/dist/core/claude-code/live-session.js.map +1 -0
  28. package/dist/core/claude-code/loop.d.ts +5 -24
  29. package/dist/core/claude-code/loop.js +6 -273
  30. package/dist/core/claude-code/loop.js.map +1 -1
  31. package/dist/core/claude-code/tool-bridge.d.ts +7 -3
  32. package/dist/core/claude-code/tool-bridge.js +75 -18
  33. package/dist/core/claude-code/tool-bridge.js.map +1 -1
  34. package/dist/system-prompt.js +1 -1
  35. package/dist/system-prompt.js.map +1 -1
  36. package/package.json +4 -4
  37. package/dist/app-sidecar/royale.d.ts +0 -40
  38. package/dist/app-sidecar/royale.js +0 -149
  39. package/dist/app-sidecar/royale.js.map +0 -1
@@ -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,11 @@ 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
+ // Steering whose text the model already read in an ask_user result.
329
+ askAnswerSteering = new WeakSet();
330
+ // Taken into the run but not yet in the transcript. Claude Code takes queued
331
+ // messages at once but reads them at its next turn, so they still show as queued.
332
+ deliveringQueue = [];
328
333
  queueSeq = 0;
329
334
  /** Monotonic count of human-originated prompts; idle-wake budgets reset on it. */
330
335
  humanPromptSeq = 0;
@@ -1004,14 +1009,16 @@ export class AgentSession {
1004
1009
  }
1005
1010
  let sessionId = resume;
1006
1011
  const title = this.sessionPreview?.trim().slice(0, 80);
1007
- const generator = claudeCodeLoop(loopMessages, {
1012
+ const thinking = this.planModeRef.current || options.capThinking
1013
+ ? clampThinkingForPlanMode(this.thinkingLevel)
1014
+ : this.thinkingLevel;
1015
+ const live = await this.claudeCodeLiveFor(process, loopMessages, resume, thinking, options);
1016
+ const generator = live.run(loopMessages, {
1008
1017
  provider: this.provider,
1009
1018
  model: this.model,
1010
1019
  tools: options.disableTools ? [] : this.tools,
1011
1020
  maxTurns: this.opts.maxTurns,
1012
- thinking: this.planModeRef.current || options.capThinking
1013
- ? clampThinkingForPlanMode(this.thinkingLevel)
1014
- : this.thinkingLevel,
1021
+ thinking,
1015
1022
  signal: this.opts.signal,
1016
1023
  maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, undefined),
1017
1024
  transformToolResult: flagUntrustedToolResult,
@@ -1019,6 +1026,7 @@ export class AgentSession {
1019
1026
  ? {}
1020
1027
  : { resolveTool: (name) => this.promoteDeferredBuiltin(name) }),
1021
1028
  getSteeringMessages: () => this.getHookSteeringMessages(),
1029
+ steeringAlreadyRead: (message) => this.askAnswerSteering.has(message),
1022
1030
  onSteeringAvailable: (listener) => {
1023
1031
  this.steeringListeners.add(listener);
1024
1032
  return () => this.steeringListeners.delete(listener);
@@ -1038,11 +1046,26 @@ export class AgentSession {
1038
1046
  try {
1039
1047
  for await (const event of generator) {
1040
1048
  await this.trackHookEvent(event);
1049
+ // Claude Code sends the requests, so the cache-diagnostics pass never
1050
+ // sees them; without a touch every idle chat read as an expired cache.
1051
+ if (event.type === "turn_end" && event.stopReason !== "error") {
1052
+ this.cacheDiagnostics.noteCacheTouch({
1053
+ at: Date.now(),
1054
+ provider: this.provider,
1055
+ model: this.model,
1056
+ policy: CLAUDE_CODE_CACHE_TTL,
1057
+ });
1058
+ }
1041
1059
  this.eventBus.forwardAgentEvent(event);
1042
1060
  }
1043
1061
  }
1044
1062
  finally {
1063
+ // The SDK counts maxTurns per process, so a capped session runs one process per run.
1064
+ if (live !== this.claudeCodeLive?.session)
1065
+ live.close("one-shot");
1045
1066
  this.activeLoopMessages = null;
1067
+ // A stopped run records unplaced messages without an event.
1068
+ this.settleDeliveredMessages(() => true);
1046
1069
  this.messages = loopMessages;
1047
1070
  for (let i = this.lastPersistedIndex; i < this.messages.length; i++) {
1048
1071
  await this.persistMessage(this.messages[i]);
@@ -1052,6 +1075,50 @@ export class AgentSession {
1052
1075
  await this.recordClaudeCodeSession(sessionId);
1053
1076
  }
1054
1077
  }
1078
+ /**
1079
+ * The Claude Code process for this run: the chat's live one when it holds
1080
+ * exactly our history with the same settings, else a new one (the old one is
1081
+ * closed first, so a chat never keeps two).
1082
+ */
1083
+ async claudeCodeLiveFor(process, messages, resume, thinking, options) {
1084
+ const hash = (value) => crypto.createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
1085
+ const key = {
1086
+ executable: process.executable,
1087
+ cwd: process.cwd,
1088
+ model: this.model,
1089
+ system: hash(systemPrompt(messages, undefined)),
1090
+ thinking: thinking ? "on" : "off",
1091
+ tools: options.disableTools ? "off" : "on",
1092
+ };
1093
+ // Per variable, so a restart log names what moved (names only, never values).
1094
+ for (const [name, value] of Object.entries(process.env)) {
1095
+ // The SDK writes this into the daemon's env on its first query(); it sets it for the child anyway.
1096
+ if (name !== "CLAUDE_AGENT_SDK_VERSION")
1097
+ key[`env:${name}`] = hash(value);
1098
+ }
1099
+ const current = this.claudeCodeLive;
1100
+ const changed = current
1101
+ ? [...new Set([...Object.keys(key), ...Object.keys(current.key)])].filter((name) => current.key[name] !== key[name])
1102
+ : [];
1103
+ if (current &&
1104
+ changed.length === 0 &&
1105
+ current.session.alive &&
1106
+ !current.session.busy &&
1107
+ resume !== undefined &&
1108
+ resume === current.session.sessionId &&
1109
+ (await current.session.setEffort(thinking))) {
1110
+ return current.session;
1111
+ }
1112
+ this.closeClaudeCodeLive(changed.length > 0 ? `changed: ${changed.join(",")}` : "history or effort changed");
1113
+ const session = new ClaudeCodeLiveSession();
1114
+ if (!this.opts.maxTurns)
1115
+ this.claudeCodeLive = { session, key };
1116
+ return session;
1117
+ }
1118
+ closeClaudeCodeLive(reason) {
1119
+ this.claudeCodeLive?.session.close(reason);
1120
+ this.claudeCodeLive = null;
1121
+ }
1055
1122
  async recordClaudeCodeSession(sessionId) {
1056
1123
  const history = this.messages.filter((m) => m.role !== "system");
1057
1124
  const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
@@ -1406,6 +1473,9 @@ export class AgentSession {
1406
1473
  // The assistant message for this turn is now in the array.
1407
1474
  await this.flushPendingMessages();
1408
1475
  break;
1476
+ case "steering_message":
1477
+ this.settleDeliveredMessages((m) => m.content === event.content);
1478
+ break;
1409
1479
  case "checkpoint":
1410
1480
  // Tool results for this step are in the array and their side effects
1411
1481
  // already hit the filesystem. Flushing here is what makes a crash lose
@@ -1415,6 +1485,14 @@ export class AgentSession {
1415
1485
  break;
1416
1486
  }
1417
1487
  }
1488
+ /** Drop delivered queued messages and announce the new queue depth. */
1489
+ settleDeliveredMessages(delivered) {
1490
+ const before = this.deliveringQueue.length;
1491
+ this.deliveringQueue = this.deliveringQueue.filter((m) => !delivered(m));
1492
+ if (this.deliveringQueue.length !== before) {
1493
+ this.eventBus.emit("queue_drained", { count: this.userQueue.length });
1494
+ }
1495
+ }
1418
1496
  /**
1419
1497
  * Count full-file `cat` output from the step that just finished as reads, so
1420
1498
  * an edit after `cat` does not cost a second read. Uses the step's results as
@@ -1528,11 +1606,9 @@ export class AgentSession {
1528
1606
  // agent sees them mid-loop instead of after it stops.
1529
1607
  if (this.userQueue.length > 0) {
1530
1608
  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 });
1609
+ // `queue_drained` fires when each lands in the transcript (its
1610
+ // steering_message event), not here, so clients drop the "queued" look
1611
+ // when the agent reads it, not minutes later at run end.
1536
1612
  // Frame each queued item as concurrent steering — without this wrapper
1537
1613
  // the model treats a mid-run message as a fresh request that supersedes
1538
1614
  // the original task and silently drops it. ONE message per queued item
@@ -1555,6 +1631,12 @@ export class AgentSession {
1555
1631
  ];
1556
1632
  return { role: "user", content: parts, provenance };
1557
1633
  });
1634
+ steeringMessages.forEach((message, index) => {
1635
+ const { id, text, answeredAsk } = queued[index];
1636
+ if (answeredAsk)
1637
+ this.askAnswerSteering.add(message);
1638
+ this.deliveringQueue.push({ id, text, content: message.content });
1639
+ });
1558
1640
  const userShell = this.takeUserShellContext();
1559
1641
  return [
1560
1642
  ...(environmentDelta ? [environmentDelta] : []),
@@ -1973,6 +2055,8 @@ export class AgentSession {
1973
2055
  await this.runClaudeCodeLoop(claudeCode, options);
1974
2056
  return;
1975
2057
  }
2058
+ // Left the Claude subscription route (provider switch, sign-out).
2059
+ this.closeClaudeCodeLive("route changed");
1976
2060
  // Resolve OAuth credentials and run agent loop.
1977
2061
  // On 401, force-refresh the token and retry once — the provider may have
1978
2062
  // revoked the token server-side before the stored expiry (e.g. after a restart).
@@ -2294,6 +2378,7 @@ export class AgentSession {
2294
2378
  }
2295
2379
  finally {
2296
2380
  this.activeLoopMessages = null;
2381
+ this.settleDeliveredMessages(() => true);
2297
2382
  // An in-flight compaction rebinds `this.messages` to the compacted array
2298
2383
  // while the loop keeps appending to `loopMessages`. Resync on every exit
2299
2384
  // — a failed or aborted run included — or the session silently drops
@@ -3006,6 +3091,7 @@ export class AgentSession {
3006
3091
  // into the fresh session (e.g. an accepted plan's build would inherit the
3007
3092
  // whole planning conversation and lose the approved-plan prompt).
3008
3093
  await this.settlePostTurnCompaction();
3094
+ this.closeClaudeCodeLive("new session");
3009
3095
  this.cacheDiagnostics.reset();
3010
3096
  // Approved-plan execution is a clean checkpoint of the same conversation;
3011
3097
  // explicit new sessions reset the conversation identity.
@@ -3053,6 +3139,7 @@ export class AgentSession {
3053
3139
  this.eventBus.emit("session_start", { sessionId: this.sessionId });
3054
3140
  }
3055
3141
  async loadSession(sessionPath) {
3142
+ this.closeClaudeCodeLive("session loaded");
3056
3143
  await this.loadExistingSession(sessionPath);
3057
3144
  this.cacheDiagnostics.reset();
3058
3145
  if (this.sessionId)
@@ -3293,9 +3380,14 @@ export class AgentSession {
3293
3380
  /** Queue a user message (optionally with attachments) to be injected mid-run
3294
3381
  * as steering. Returns the new queue length. No-op semantics are the caller's
3295
3382
  * concern. */
3296
- queueMessage(text, attachments = []) {
3383
+ queueMessage(text, attachments = [], opts = {}) {
3297
3384
  this.queueSeq += 1;
3298
- this.userQueue.push({ id: `q${this.queueSeq}`, text, attachments });
3385
+ this.userQueue.push({
3386
+ id: `q${this.queueSeq}`,
3387
+ text,
3388
+ attachments,
3389
+ ...(opts.answeredAsk ? { answeredAsk: true } : {}),
3390
+ });
3299
3391
  // Instant interrupt: preempt running tools so the steer lands right away.
3300
3392
  for (const listener of [...this.steeringListeners])
3301
3393
  listener();
@@ -3332,9 +3424,13 @@ export class AgentSession {
3332
3424
  this.messages.push(message);
3333
3425
  await this.persistMessage(message);
3334
3426
  }
3335
- /** Pending queued messages (id + text), oldest first, for client display. */
3427
+ /** Pending queued messages (id + text), oldest first, for client display.
3428
+ * `delivering` ones are already with the agent and can no longer be cancelled. */
3336
3429
  listQueuedMessages() {
3337
- return this.userQueue.map((m) => ({ id: m.id, text: m.text }));
3430
+ return [
3431
+ ...this.deliveringQueue.map((m) => ({ id: m.id, text: m.text, delivering: true })),
3432
+ ...this.userQueue.map((m) => ({ id: m.id, text: m.text })),
3433
+ ];
3338
3434
  }
3339
3435
  /** Cancel one pending message by id. Returns true if it was still queued.
3340
3436
  * A false return is the normal race rather than an error: the message drained
@@ -3471,6 +3567,8 @@ export class AgentSession {
3471
3567
  */
3472
3568
  stopBackgroundProcesses() {
3473
3569
  this.processManager?.shutdownAll();
3570
+ // Synchronous, so app quit stops Claude Code even when later teardown hangs.
3571
+ this.closeClaudeCodeLive("shutdown");
3474
3572
  }
3475
3573
  /** Replace a host-owned system prompt in place without resetting conversation history. */
3476
3574
  setCustomSystemPrompt(systemPrompt, promptCacheKeyPrefix) {
@@ -4143,6 +4241,8 @@ export class AgentSession {
4143
4241
  prewarmController = null;
4144
4242
  /** Claude Code session that has seen this history (Claude subscription route). */
4145
4243
  claudeCodeSession = null;
4244
+ /** This chat's running Claude Code process, reused while `key` (its start settings) matches. */
4245
+ claudeCodeLive = null;
4146
4246
  /**
4147
4247
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
4148
4248
  * (desktop app calls this on the first keystroke after opening a chat or an