@kenkaiiii/ggcoder 5.93.0 → 5.95.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 (94) hide show
  1. package/README.md +20 -15
  2. package/dist/app-sidecar/auth-routes.js +42 -45
  3. package/dist/app-sidecar/auth-routes.js.map +1 -1
  4. package/dist/app-sidecar/route-context.d.ts +3 -1
  5. package/dist/app-sidecar/run-control-routes.d.ts +1 -1
  6. package/dist/app-sidecar/run-control-routes.js +59 -1
  7. package/dist/app-sidecar/run-control-routes.js.map +1 -1
  8. package/dist/app-sidecar/usage.js +32 -5
  9. package/dist/app-sidecar/usage.js.map +1 -1
  10. package/dist/app-sidecar.js +28 -28
  11. package/dist/app-sidecar.js.map +1 -1
  12. package/dist/cli/auth.js +104 -68
  13. package/dist/cli/auth.js.map +1 -1
  14. package/dist/cli.js +7 -4
  15. package/dist/cli.js.map +1 -1
  16. package/dist/core/agent-session.d.ts +7 -1
  17. package/dist/core/agent-session.js +195 -70
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/auth/index.d.ts +1 -2
  20. package/dist/core/auth/index.js +1 -2
  21. package/dist/core/auth/index.js.map +1 -1
  22. package/dist/core/claude-code/complete.d.ts +33 -0
  23. package/dist/core/claude-code/complete.js +113 -0
  24. package/dist/core/claude-code/complete.js.map +1 -0
  25. package/dist/core/claude-code/events.d.ts +65 -0
  26. package/dist/core/claude-code/events.js +434 -0
  27. package/dist/core/claude-code/events.js.map +1 -0
  28. package/dist/core/claude-code/loop.d.ts +28 -0
  29. package/dist/core/claude-code/loop.js +271 -0
  30. package/dist/core/claude-code/loop.js.map +1 -0
  31. package/dist/core/claude-code/session-sync.d.ts +28 -0
  32. package/dist/core/claude-code/session-sync.js +53 -0
  33. package/dist/core/claude-code/session-sync.js.map +1 -0
  34. package/dist/core/claude-code/tool-bridge.d.ts +43 -0
  35. package/dist/core/claude-code/tool-bridge.js +274 -0
  36. package/dist/core/claude-code/tool-bridge.js.map +1 -0
  37. package/dist/core/codex-request-shape.d.ts +0 -5
  38. package/dist/core/codex-request-shape.js +4 -16
  39. package/dist/core/codex-request-shape.js.map +1 -1
  40. package/dist/core/compaction/compactor.d.ts +8 -2
  41. package/dist/core/compaction/compactor.js +13 -5
  42. package/dist/core/compaction/compactor.js.map +1 -1
  43. package/dist/core/oauth/openai.d.ts +1 -1
  44. package/dist/core/oauth/openai.js +1 -1
  45. package/dist/core/oauth/openai.js.map +1 -1
  46. package/dist/core/settings-manager.d.ts +0 -5
  47. package/dist/core/settings-manager.js +0 -5
  48. package/dist/core/settings-manager.js.map +1 -1
  49. package/dist/core/subagent-policy.js +1 -1
  50. package/dist/core/subagent-policy.js.map +1 -1
  51. package/dist/system-prompt.js +3 -13
  52. package/dist/system-prompt.js.map +1 -1
  53. package/dist/tools/generate-image.d.ts +5 -6
  54. package/dist/tools/generate-image.js +73 -139
  55. package/dist/tools/generate-image.js.map +1 -1
  56. package/dist/tools/side-web-search.d.ts +5 -1
  57. package/dist/tools/side-web-search.js +61 -1
  58. package/dist/tools/side-web-search.js.map +1 -1
  59. package/dist/ui/App.d.ts +0 -2
  60. package/dist/ui/App.js +4 -4
  61. package/dist/ui/App.js.map +1 -1
  62. package/dist/ui/components/Footer.js +2 -0
  63. package/dist/ui/components/Footer.js.map +1 -1
  64. package/dist/ui/hooks/useAgentLoop.d.ts +3 -2
  65. package/dist/ui/hooks/useAgentLoop.js +54 -24
  66. package/dist/ui/hooks/useAgentLoop.js.map +1 -1
  67. package/dist/ui/hooks/useContextCompaction.d.ts +1 -2
  68. package/dist/ui/hooks/useContextCompaction.js +1 -5
  69. package/dist/ui/hooks/useContextCompaction.js.map +1 -1
  70. package/dist/ui/render.d.ts +0 -2
  71. package/dist/ui/render.js +0 -1
  72. package/dist/ui/render.js.map +1 -1
  73. package/dist/utils/plan-steps.d.ts +1 -0
  74. package/dist/utils/plan-steps.js +10 -0
  75. package/dist/utils/plan-steps.js.map +1 -1
  76. package/dist/utils/prompt-enhancer.d.ts +3 -3
  77. package/dist/utils/prompt-enhancer.js +21 -18
  78. package/dist/utils/prompt-enhancer.js.map +1 -1
  79. package/package.json +5 -4
  80. package/dist/core/claude-code-version.d.ts +0 -1
  81. package/dist/core/claude-code-version.js +0 -3
  82. package/dist/core/claude-code-version.js.map +0 -1
  83. package/dist/core/oauth/anthropic.d.ts +0 -1
  84. package/dist/core/oauth/anthropic.js +0 -3
  85. package/dist/core/oauth/anthropic.js.map +0 -1
  86. package/dist/core/oauth/gemini.d.ts +0 -1
  87. package/dist/core/oauth/gemini.js +0 -3
  88. package/dist/core/oauth/gemini.js.map +0 -1
  89. package/dist/core/oauth/kimi.d.ts +0 -1
  90. package/dist/core/oauth/kimi.js +0 -3
  91. package/dist/core/oauth/kimi.js.map +0 -1
  92. package/dist/core/oauth/xai.d.ts +0 -1
  93. package/dist/core/oauth/xai.js +0 -4
  94. package/dist/core/oauth/xai.js.map +0 -1
@@ -598,6 +598,11 @@ export declare class AgentSession {
598
598
  */
599
599
  private attachWebSearchIfAsked;
600
600
  private runSideWebSearch;
601
+ /** One run on the Claude subscription route: Claude Code drives the loop with our prompt and tools. */
602
+ private runClaudeCodeLoop;
603
+ private recordClaudeCodeSession;
604
+ /** Claude Code settings when this session runs on a Claude subscription, else null. */
605
+ private claudeCodeProcess;
601
606
  /** Append a deferred built-in to the live tool list (append-only). */
602
607
  private promoteDeferredBuiltin;
603
608
  private wrapToPromote;
@@ -792,7 +797,6 @@ export declare class AgentSession {
792
797
  compact(existingCredentials?: {
793
798
  accessToken: string;
794
799
  accountId?: string;
795
- projectId?: string;
796
800
  baseUrl?: string;
797
801
  }, mode?: "manual" | "automatic" | "forced",
798
802
  /** User-stated focus (`/compact <focus>`): what must survive verbatim. */
@@ -1196,6 +1200,8 @@ export declare class AgentSession {
1196
1200
  */
1197
1201
  private preconnect;
1198
1202
  private prewarmController;
1203
+ /** Claude Code session that has seen this history (Claude subscription route). */
1204
+ private claudeCodeSession;
1199
1205
  /**
1200
1206
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
1201
1207
  * (desktop app calls this on the first keystroke after opening a chat or an
@@ -14,10 +14,7 @@ import { expandPromptCommand } from "./prompt-command-expansion.js";
14
14
  import { SettingsManager } from "./settings-manager.js";
15
15
  import { AuthStorage } from "./auth-storage.js";
16
16
  import { dualAuthProvider } from "@kenkaiiii/gg-core";
17
- import { getClaudeCliUserAgent } from "./claude-code-version.js";
18
- import { runSideWebSearch, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
19
- import { kimiCodingHeaders, isKimiCodingEndpoint } from "./oauth/kimi.js";
20
- import { isGrokCliEndpoint } from "./oauth/xai.js";
17
+ import { runSideWebSearch, runSideWebSearchViaClaudeCode, SIDE_SEARCH_MODEL, } from "../tools/side-web-search.js";
21
18
  import { SessionManager, } from "./session-manager.js";
22
19
  import { ExtensionLoader } from "./extensions/loader.js";
23
20
  import { shouldCompact, compact, } from "./compaction/compactor.js";
@@ -33,7 +30,7 @@ import { buildProcessCompletionFollowUp, mergeCompletionGateFollowUps } from "./
33
30
  import { PLAN_SUBMISSION_NUDGE, shouldNudgePlanSubmission } from "./plan-submission-gate.js";
34
31
  import { buildSubAgentCompletionFollowUp, } from "./subagent-manager.js";
35
32
  import { applyAsyncSubagentPolicy } from "./subagent-policy.js";
36
- import { resolveResponsesLite, resolveStrictTools, } from "./codex-request-shape.js";
33
+ import { resolveStrictTools } from "./codex-request-shape.js";
37
34
  import { subAgentDescription } from "../tools/subagent.js";
38
35
  import { getAllMcpServers } from "./mcp/index.js";
39
36
  import { CONTEXT_LIMITS, resolveSessionContextLimits, } from "./context-limits.js";
@@ -53,6 +50,10 @@ import { clampThinkingForPlanMode } from "./thinking-level.js";
53
50
  import { pruneMinimumTokens, pruneStaleToolResults, shouldPruneToolResults, } from "./compaction/tool-result-pruner.js";
54
51
  import { discoverAgents } from "./agents.js";
55
52
  import { enhancePrompt } from "../utils/prompt-enhancer.js";
53
+ import { assistantText, renderTranscript } from "./claude-code/events.js";
54
+ import { claudeCodeLoop } from "./claude-code/loop.js";
55
+ import { CLAUDE_CODE_SEED_CHARS, CLAUDE_CODE_SESSION_KIND, claudeCodeResumeId, claudeCodeSessionEntryData, parseClaudeCodeSessionState, } from "./claude-code/session-sync.js";
56
+ import { claudeCodeComplete, resolveClaudeCodeProcess, } from "./claude-code/complete.js";
56
57
  import { detectLanguages, detectProjectStack } from "./language-detector.js";
57
58
  import { buildLoopBreakMessage } from "./loop-breaker.js";
58
59
  import { buildRegroundingMessage, requestTextForRegrounding } from "./regrounding.js";
@@ -483,12 +484,6 @@ export class AgentSession {
483
484
  async initialize() {
484
485
  // Set model for accurate token estimation
485
486
  setEstimatorModel(this.model);
486
- // The Anthropic transport needs the current Claude Code version for its
487
- // User-Agent before the first request. Without a fresh on-disk cache that
488
- // is an npm round-trip (~0.3–3s) on the user's first prompt; start it now
489
- // so it overlaps session setup and the user's typing instead.
490
- if (this.provider === "anthropic")
491
- void getClaudeCliUserAgent().catch(() => { });
492
487
  // The prompt's file list is a `git ls-files` (~30 ms on a mid-size repo)
493
488
  // that nothing before buildBasePrompt depends on: start it now so it runs
494
489
  // alongside settings/auth/skills/tools instead of after them.
@@ -976,15 +971,106 @@ export class AgentSession {
976
971
  async runSideWebSearch(request) {
977
972
  if (this.provider !== "anthropic")
978
973
  return null;
974
+ const claudeCode = await this.claudeCodeProcess();
975
+ if (claudeCode)
976
+ return await runSideWebSearchViaClaudeCode(request, claudeCode);
979
977
  const creds = await this.authStorage.resolveCredentials("anthropic", {
980
978
  storageKeys: getAuthStorageKeys("anthropic", SIDE_SEARCH_MODEL),
981
979
  });
982
980
  return await runSideWebSearch(request, {
983
981
  apiKey: creds.accessToken,
984
982
  baseUrl: this.baseUrl ?? creds.baseUrl,
985
- userAgent: await getClaudeCliUserAgent(),
986
983
  });
987
984
  }
985
+ /** One run on the Claude subscription route: Claude Code drives the loop with our prompt and tools. */
986
+ async runClaudeCodeLoop(process, options) {
987
+ let loopMessages = await this.prepareDynamicContext();
988
+ const resume = claudeCodeResumeId(this.claudeCodeSession, loopMessages);
989
+ // A fresh Claude Code session gets our history as text; summarize it first
990
+ // when it would not fit.
991
+ if (!resume &&
992
+ renderTranscript(loopMessages, Number.MAX_SAFE_INTEGER).length > CLAUDE_CODE_SEED_CHARS) {
993
+ try {
994
+ await this.compact(undefined, "automatic");
995
+ }
996
+ catch (error) {
997
+ if (isAbortError(error) || this.opts.signal?.aborted)
998
+ throw error;
999
+ log("WARN", "compaction", "Summary before seeding Claude Code failed", {
1000
+ error: error instanceof Error ? error.message : String(error),
1001
+ });
1002
+ }
1003
+ loopMessages = await this.prepareDynamicContext();
1004
+ }
1005
+ let sessionId = resume;
1006
+ const title = this.sessionPreview?.trim().slice(0, 80);
1007
+ const generator = claudeCodeLoop(loopMessages, {
1008
+ provider: this.provider,
1009
+ model: this.model,
1010
+ tools: options.disableTools ? [] : this.tools,
1011
+ maxTurns: this.opts.maxTurns,
1012
+ thinking: this.planModeRef.current || options.capThinking
1013
+ ? clampThinkingForPlanMode(this.thinkingLevel)
1014
+ : this.thinkingLevel,
1015
+ signal: this.opts.signal,
1016
+ maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, undefined),
1017
+ transformToolResult: flagUntrustedToolResult,
1018
+ ...(options.disableTools
1019
+ ? {}
1020
+ : { resolveTool: (name) => this.promoteDeferredBuiltin(name) }),
1021
+ getSteeringMessages: () => this.getHookSteeringMessages(),
1022
+ onSteeringAvailable: (listener) => {
1023
+ this.steeringListeners.add(listener);
1024
+ return () => this.steeringListeners.delete(listener);
1025
+ },
1026
+ getFollowUpMessages: () => this.getHookFollowUpMessages(),
1027
+ claudeCode: {
1028
+ ...process,
1029
+ maxSeedChars: CLAUDE_CODE_SEED_CHARS,
1030
+ ...(resume ? { resume } : {}),
1031
+ ...(title ? { title } : {}),
1032
+ onSessionId: (id) => {
1033
+ sessionId = id;
1034
+ },
1035
+ },
1036
+ });
1037
+ this.activeLoopMessages = loopMessages;
1038
+ try {
1039
+ for await (const event of generator) {
1040
+ await this.trackHookEvent(event);
1041
+ this.eventBus.forwardAgentEvent(event);
1042
+ }
1043
+ }
1044
+ finally {
1045
+ this.activeLoopMessages = null;
1046
+ this.messages = loopMessages;
1047
+ for (let i = this.lastPersistedIndex; i < this.messages.length; i++) {
1048
+ await this.persistMessage(this.messages[i]);
1049
+ }
1050
+ this.lastPersistedIndex = this.messages.length;
1051
+ if (sessionId)
1052
+ await this.recordClaudeCodeSession(sessionId);
1053
+ }
1054
+ }
1055
+ async recordClaudeCodeSession(sessionId) {
1056
+ const history = this.messages.filter((m) => m.role !== "system");
1057
+ const state = { sessionId, messageCount: history.length, anchor: history.at(-1) };
1058
+ this.claudeCodeSession = state;
1059
+ if (!this.sessionPath)
1060
+ return;
1061
+ await this.sessionManager.appendEntry(this.sessionPath, {
1062
+ type: "custom",
1063
+ kind: CLAUDE_CODE_SESSION_KIND,
1064
+ id: crypto.randomUUID(),
1065
+ parentId: null,
1066
+ timestamp: new Date().toISOString(),
1067
+ data: claudeCodeSessionEntryData(state),
1068
+ });
1069
+ }
1070
+ /** Claude Code settings when this session runs on a Claude subscription, else null. */
1071
+ claudeCodeProcess() {
1072
+ return resolveClaudeCodeProcess(this.authStorage, this.provider, this.cwd);
1073
+ }
988
1074
  /** Append a deferred built-in to the live tool list (append-only). */
989
1075
  promoteDeferredBuiltin(name) {
990
1076
  if (!this.deferredBuiltinToolNames.includes(name))
@@ -1575,6 +1661,24 @@ export class AgentSession {
1575
1661
  throw new Error("Active model has no confirmed image support");
1576
1662
  signal.throwIfAborted();
1577
1663
  try {
1664
+ const messages = [
1665
+ { role: "system", content: request.instruction },
1666
+ { role: "user", content: [{ type: "text", text: request.context }, ...request.images] },
1667
+ ];
1668
+ const claudeCode = await this.claudeCodeProcess();
1669
+ if (claudeCode) {
1670
+ const response = await claudeCodeComplete({
1671
+ ...claudeCode,
1672
+ model,
1673
+ messages,
1674
+ thinking,
1675
+ signal,
1676
+ });
1677
+ const text = assistantText(response.message.content);
1678
+ if (text.length > 32_768)
1679
+ throw new Error("Review response exceeded its limit");
1680
+ return { text, model, provider, thinking };
1681
+ }
1578
1682
  const creds = await this.authStorage.resolveCredentials(provider, {
1579
1683
  storageKeys: this.currentAuthStorageKeys(),
1580
1684
  });
@@ -1582,22 +1686,14 @@ export class AgentSession {
1582
1686
  const result = stream({
1583
1687
  provider,
1584
1688
  model,
1585
- messages: [
1586
- { role: "system", content: request.instruction },
1587
- { role: "user", content: [{ type: "text", text: request.context }, ...request.images] },
1588
- ],
1689
+ messages,
1589
1690
  maxTokens: 4000,
1590
1691
  thinking,
1591
1692
  apiKey: creds.accessToken,
1592
1693
  accountId: creds.accountId,
1593
- projectId: creds.projectId,
1594
1694
  baseUrl,
1595
1695
  signal,
1596
1696
  transportSessionId: this.sessionId || this.transportSessionId,
1597
- defaultHeaders: provider === "moonshot" && isKimiCodingEndpoint(baseUrl)
1598
- ? kimiCodingHeaders()
1599
- : undefined,
1600
- userAgent: provider === "anthropic" ? await getClaudeCliUserAgent() : undefined,
1601
1697
  supportsImages: true,
1602
1698
  });
1603
1699
  const response = await result.response;
@@ -1622,6 +1718,16 @@ export class AgentSession {
1622
1718
  * cheaper routing: judging a model's own failure patterns with a weaker
1623
1719
  * model swaps false negatives for false positives. */
1624
1720
  async callSemanticLoopJudge(prompt) {
1721
+ const claudeCode = await this.claudeCodeProcess();
1722
+ if (claudeCode) {
1723
+ const response = await withJudgeTimeout(claudeCodeComplete({
1724
+ ...claudeCode,
1725
+ model: this.model,
1726
+ messages: [{ role: "user", content: prompt }],
1727
+ signal: this.opts.signal,
1728
+ }), SEMANTIC_LOOP_JUDGE_TIMEOUT_MS);
1729
+ return assistantText(response.message.content);
1730
+ }
1625
1731
  const creds = await this.authStorage.resolveCredentials(this.provider, {
1626
1732
  storageKeys: this.currentAuthStorageKeys(),
1627
1733
  });
@@ -1632,7 +1738,6 @@ export class AgentSession {
1632
1738
  maxTokens: 500,
1633
1739
  apiKey: creds.accessToken,
1634
1740
  accountId: creds.accountId,
1635
- projectId: creds.projectId,
1636
1741
  baseUrl: this.baseUrl ?? creds.baseUrl,
1637
1742
  signal: this.opts.signal,
1638
1743
  });
@@ -1861,6 +1966,13 @@ export class AgentSession {
1861
1966
  .reverse()
1862
1967
  .find((m) => m.role === "user" && m.provenance?.kind !== "notification");
1863
1968
  this.resetHookState(requestTextForRegrounding(lastUser));
1969
+ // A Claude subscription runs through Claude Code, which does its own
1970
+ // retries, compaction and caching.
1971
+ const claudeCode = await this.claudeCodeProcess();
1972
+ if (claudeCode) {
1973
+ await this.runClaudeCodeLoop(claudeCode, options);
1974
+ return;
1975
+ }
1864
1976
  // Resolve OAuth credentials and run agent loop.
1865
1977
  // On 401, force-refresh the token and retry once — the provider may have
1866
1978
  // revoked the token server-side before the stored expiry (e.g. after a restart).
@@ -1938,11 +2050,10 @@ export class AgentSession {
1938
2050
  }
1939
2051
  }
1940
2052
  }
1941
- const userAgent = this.provider === "anthropic" ? await getClaudeCliUserAgent() : undefined;
1942
2053
  const loopMessages = await this.prepareDynamicContext();
1943
2054
  // Re-read every run so rule-file edits apply on the next turn; a few small files.
1944
2055
  const streamRules = await loadStreamRules(this.cwd);
1945
- const runAgentLoop = async (apiKey, accountId, projectId) => {
2056
+ const runAgentLoop = async (apiKey, accountId) => {
1946
2057
  lastResolvedAccessToken = apiKey;
1947
2058
  const modelInfo = getModel(this.model);
1948
2059
  const effectiveBaseUrl = this.baseUrl ?? creds.baseUrl;
@@ -1980,24 +2091,16 @@ export class AgentSession {
1980
2091
  return {
1981
2092
  apiKey: live.accessToken,
1982
2093
  ...(live.accountId !== undefined ? { accountId: live.accountId } : {}),
1983
- ...(live.projectId !== undefined ? { projectId: live.projectId } : {}),
1984
2094
  };
1985
2095
  },
1986
2096
  baseUrl: effectiveBaseUrl,
1987
2097
  signal: this.opts.signal,
1988
2098
  accountId,
1989
2099
  transportSessionId: this.sessionId || this.transportSessionId,
1990
- projectId,
1991
- // Kimi For Coding gates the managed endpoint on coding-agent identity
1992
- // headers; attach them only when the Kimi OAuth token is in use.
1993
- defaultHeaders: this.provider === "moonshot" && isKimiCodingEndpoint(effectiveBaseUrl)
1994
- ? kimiCodingHeaders()
1995
- : undefined,
1996
2100
  // speedProfile "optimized": 1-h cache TTL (survives turns >5 min apart)
1997
2101
  // + pre-warm before the first turn. "baseline": current 5-min default.
1998
2102
  cacheRetention: this.isSpeedOptimized() ? "long" : "short",
1999
2103
  promptCacheKey: this.getPromptCacheKey(),
2000
- responsesLite: resolveResponsesLite(this.codexShapeSetting("codexResponsesLite"), this.provider, this.model),
2001
2104
  strictTools: resolveStrictTools(this.codexShapeSetting("codexStrictTools"), this.provider),
2002
2105
  onContextPrepared: (context) => {
2003
2106
  const report = this.cacheDiagnostics.prepare(context, {
@@ -2033,7 +2136,6 @@ export class AgentSession {
2033
2136
  },
2034
2137
  supportsImages: modelInfo?.supportsImages,
2035
2138
  supportsVideo: modelInfo?.supportsVideo,
2036
- userAgent,
2037
2139
  // Codex caps each tool output at 10K tokens. Other transports retain the
2038
2140
  // generic 30%-of-context allowance used before this provider policy.
2039
2141
  maxToolResultChars: resolveSessionToolResultCharLimit(this.model, this.provider, accountId),
@@ -2162,7 +2264,6 @@ export class AgentSession {
2162
2264
  await this.compact({
2163
2265
  accessToken: apiKey,
2164
2266
  accountId,
2165
- projectId,
2166
2267
  baseUrl: effectiveBaseUrl,
2167
2268
  }, force ? "forced" : "automatic");
2168
2269
  }
@@ -2216,34 +2317,31 @@ export class AgentSession {
2216
2317
  return true;
2217
2318
  };
2218
2319
  try {
2219
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2320
+ await runAgentLoop(creds.accessToken, creds.accountId);
2220
2321
  }
2221
2322
  catch (err) {
2222
2323
  // Abort errors are expected (user cancellation) — don't retry or re-throw
2223
2324
  if (isAbortError(err) || this.opts.signal?.aborted) {
2224
2325
  return;
2225
2326
  }
2226
- // A subscription OAuth plan ran out of usage (hard usage-limit stop, or an
2227
- // HTTP 402 billing stop). If the user ALSO configured that provider's API
2228
- // key, mark the OAuth credential usage-exhausted (honoring the
2229
- // provider-stated reset time when present) and retry this turn on the API
2230
- // key — OAuth stays the preferred credential and resumes automatically once
2327
+ // The ChatGPT plan ran out of usage (hard usage-limit stop, or an HTTP 402
2328
+ // billing stop). If the user ALSO configured an OpenAI API key, mark the
2329
+ // plan usage-exhausted (honoring a stated reset time when present) and
2330
+ // retry this turn on the key — the plan stays preferred and resumes once
2231
2331
  // the mark lapses. A generic 429 is deliberately excluded: it may be a
2232
- // transient rate limit and must not silently switch the user to a billed
2233
- // API key.
2332
+ // transient rate limit and must not silently switch the user to a billed key.
2234
2333
  //
2235
- // Grok adds one case Kimi doesn't have: xAI gates its CLI chat proxy by
2236
- // subscription tier, so an entitled-looking account can be refused outright
2237
- // with a 403. That means "OAuth cannot serve this", not a transient error,
2238
- // so it counts as exhausted too — otherwise a dual-configured user would
2239
- // hard-fail while holding a perfectly good API key.
2334
+ // An account or workspace that isn't eligible for plan use is refused with
2335
+ // a 403; that means "the plan cannot serve this", so it counts too.
2240
2336
  //
2241
- // Guarded on the subscription endpoint actually being in use: if the API key
2242
- // was already active, the same error means BOTH are out and must surface.
2337
+ // Guarded on the plan route actually being in use: if the API key was
2338
+ // already active, the same error means BOTH are out and must surface.
2243
2339
  const dualAuth = dualAuthProvider(this.provider);
2244
- const onSubscriptionEndpoint = (this.provider === "moonshot" && isKimiCodingEndpoint(creds.baseUrl)) ||
2245
- (this.provider === "xai" && isGrokCliEndpoint(creds.baseUrl));
2246
- const tierRefusal = this.provider === "xai" && err instanceof ProviderError && err.statusCode === 403;
2340
+ const onSubscriptionEndpoint = this.provider === "openai" && Boolean(creds.accountId);
2341
+ const tierRefusal = this.provider === "openai" &&
2342
+ err instanceof ProviderError &&
2343
+ err.statusCode === 403 &&
2344
+ /ChatGPT plan use isn't available/.test(err.message);
2247
2345
  const oauthIsOut = isUsageLimitError(err) ||
2248
2346
  (err instanceof ProviderError && err.statusCode === 402) ||
2249
2347
  tierRefusal;
@@ -2259,11 +2357,10 @@ export class AgentSession {
2259
2357
  storageKeys: this.currentAuthStorageKeys(),
2260
2358
  });
2261
2359
  this.lastAccountId = creds.accountId;
2262
- // The runAgentLoop closure re-reads `creds`, so the retry picks up the
2263
- // API key's public baseUrl (api.moonshot.ai / api.x.ai) and drops the
2264
- // subscription endpoint's client-identity headers.
2360
+ // The runAgentLoop closure re-reads `creds`, so the retry runs on the
2361
+ // API key without the plan's account.
2265
2362
  try {
2266
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2363
+ await runAgentLoop(creds.accessToken, creds.accountId);
2267
2364
  }
2268
2365
  catch (fallbackErr) {
2269
2366
  // The fallback is inside this catch branch, so its errors do not pass
@@ -2283,7 +2380,7 @@ export class AgentSession {
2283
2380
  });
2284
2381
  this.lastAccountId = creds.accountId;
2285
2382
  try {
2286
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2383
+ await runAgentLoop(creds.accessToken, creds.accountId);
2287
2384
  }
2288
2385
  catch (retryErr) {
2289
2386
  await clearInvalidStaticApiKey(retryErr);
@@ -2310,7 +2407,7 @@ export class AgentSession {
2310
2407
  rejectedToken: lastResolvedAccessToken,
2311
2408
  });
2312
2409
  this.lastAccountId = creds.accountId;
2313
- await runAgentLoop(creds.accessToken, creds.accountId, creds.projectId);
2410
+ await runAgentLoop(creds.accessToken, creds.accountId);
2314
2411
  }
2315
2412
  else {
2316
2413
  throw err;
@@ -2744,10 +2841,13 @@ export class AgentSession {
2744
2841
  const compactionSignal = abortSignal && this.opts.signal
2745
2842
  ? AbortSignal.any([this.opts.signal, abortSignal])
2746
2843
  : (abortSignal ?? this.opts.signal);
2844
+ const claudeCode = existingCredentials ? null : await this.claudeCodeProcess();
2747
2845
  const creds = existingCredentials ??
2748
- (await this.authStorage.resolveCredentials(this.provider, {
2749
- storageKeys: this.currentAuthStorageKeys(),
2750
- }));
2846
+ (claudeCode
2847
+ ? { accessToken: "" }
2848
+ : await this.authStorage.resolveCredentials(this.provider, {
2849
+ storageKeys: this.currentAuthStorageKeys(),
2850
+ }));
2751
2851
  const contextWindow = getContextWindow(this.model, {
2752
2852
  provider: this.provider,
2753
2853
  accountId: creds.accountId,
@@ -2771,13 +2871,17 @@ export class AgentSession {
2771
2871
  model: this.model,
2772
2872
  apiKey: creds.accessToken,
2773
2873
  accountId: creds.accountId,
2774
- projectId: creds.projectId,
2775
2874
  baseUrl: this.baseUrl ?? creds.baseUrl,
2776
2875
  contextWindow,
2777
2876
  targetTokens: policy.targetTokens,
2778
2877
  signal: compactionSignal,
2779
2878
  approvedPlanPath: this.approvedPlanPath,
2780
2879
  focus,
2880
+ ...(claudeCode
2881
+ ? {
2882
+ complete: (req) => claudeCodeComplete({ ...claudeCode, ...req }),
2883
+ }
2884
+ : {}),
2781
2885
  });
2782
2886
  contextSelection = output.result.contextSelection;
2783
2887
  return output;
@@ -3938,9 +4042,12 @@ export class AgentSession {
3938
4042
  // if the user switches models while credential resolution is pending.
3939
4043
  const { provider, model, thinkingLevel, baseUrl } = this;
3940
4044
  const threshold = this.settingsManager.get("compactThreshold");
3941
- const creds = await this.authStorage.resolveCredentials(provider, {
3942
- storageKeys: this.currentAuthStorageKeys(),
3943
- });
4045
+ const claudeCode = await this.claudeCodeProcess();
4046
+ const creds = claudeCode
4047
+ ? { accessToken: "" }
4048
+ : await this.authStorage.resolveCredentials(provider, {
4049
+ storageKeys: this.currentAuthStorageKeys(),
4050
+ });
3944
4051
  const maxTokens = outputCapForRequest({
3945
4052
  provider,
3946
4053
  model,
@@ -3962,14 +4069,23 @@ export class AgentSession {
3962
4069
  model,
3963
4070
  thinking: thinkingLevel,
3964
4071
  maxTokens,
3965
- userAgent: provider === "anthropic" ? await getClaudeCliUserAgent() : undefined,
3966
- projectId: creds.projectId,
3967
4072
  prompt: text,
3968
4073
  stack,
3969
4074
  apiKey: creds.accessToken,
3970
4075
  baseUrl: baseUrl ?? creds.baseUrl,
3971
4076
  accountId: creds.accountId,
3972
4077
  signal: this.opts.signal,
4078
+ ...(claudeCode
4079
+ ? {
4080
+ complete: (messages) => claudeCodeComplete({
4081
+ ...claudeCode,
4082
+ model,
4083
+ messages,
4084
+ thinking: thinkingLevel,
4085
+ signal: this.opts.signal,
4086
+ }),
4087
+ }
4088
+ : {}),
3973
4089
  });
3974
4090
  }
3975
4091
  /** Current reasoning/thinking level, or undefined when thinking is off. */
@@ -4025,6 +4141,8 @@ export class AgentSession {
4025
4141
  .catch(() => { });
4026
4142
  }
4027
4143
  prewarmController = null;
4144
+ /** Claude Code session that has seen this history (Claude subscription route). */
4145
+ claudeCodeSession = null;
4028
4146
  /**
4029
4147
  * Best-effort Anthropic prompt-cache prewarm before the user's next turn
4030
4148
  * (desktop app calls this on the first keystroke after opening a chat or an
@@ -4033,6 +4151,9 @@ export class AgentSession {
4033
4151
  * first real reply is a cache read instead of a cold write.
4034
4152
  */
4035
4153
  async prewarm(signal) {
4154
+ // Claude Code keeps its own cache; there is no request prefix of ours to warm.
4155
+ if (await this.claudeCodeProcess().catch(() => null))
4156
+ return { ok: false, reason: "claude_code" };
4036
4157
  // Every provider: the user is typing, so the first request is seconds away.
4037
4158
  this.preconnect();
4038
4159
  if (this.provider !== "anthropic")
@@ -4108,7 +4229,6 @@ export class AgentSession {
4108
4229
  promptCacheKey: this.getPromptCacheKey(),
4109
4230
  supportsImages: modelInfo?.supportsImages,
4110
4231
  supportsVideo: modelInfo?.supportsVideo,
4111
- userAgent: await getClaudeCliUserAgent(),
4112
4232
  prewarm: true,
4113
4233
  signal: controller.signal,
4114
4234
  });
@@ -4259,13 +4379,17 @@ export class AgentSession {
4259
4379
  // One backward scan for both latest host checkpoints (no full copies).
4260
4380
  let savedCompletionReview;
4261
4381
  let savedVerification;
4382
+ let savedClaudeCode;
4262
4383
  for (let i = loaded.entries.length - 1; i >= 0; i--) {
4263
- if (savedCompletionReview && savedVerification)
4384
+ if (savedCompletionReview && savedVerification && savedClaudeCode)
4264
4385
  break;
4265
4386
  const entry = loaded.entries[i];
4266
4387
  if (entry?.type !== "custom")
4267
4388
  continue;
4268
- if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
4389
+ if (!savedClaudeCode && entry.kind === CLAUDE_CODE_SESSION_KIND) {
4390
+ savedClaudeCode = entry;
4391
+ }
4392
+ else if (!savedCompletionReview && entry.kind === COMPLETION_REVIEW_STATE_KIND) {
4269
4393
  savedCompletionReview = entry;
4270
4394
  }
4271
4395
  else if (!savedVerification && entry.kind === VERIFICATION_STATE_KIND) {
@@ -4315,6 +4439,7 @@ export class AgentSession {
4315
4439
  // not fail when Anthropic's stricter many-image limit activates later.
4316
4440
  const systemMsg = this.messages[0]; // Already built
4317
4441
  this.messages = [systemMsg, ...loadedMessages];
4442
+ this.claudeCodeSession = parseClaudeCodeSessionState(savedClaudeCode?.type === "custom" ? savedClaudeCode.data : null, loadedMessages);
4318
4443
  // Reads recorded for the previous conversation don't carry over.
4319
4444
  this.clearReadTracker?.();
4320
4445
  const normalizedImageCount = await normalizeMessageImages(this.messages);