@coda-console/claude 1.12.2 → 1.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  Claude SDK Agent:Coda 基于 Claude Agent SDK 写的 ACP 入口,一个进程一个 SDK 会话;资源页的「Claude」显示会话报告的额度,可从 Coda 登录。
4
4
 
5
+ ## MCP 配置不进命令行
6
+
7
+ Coda 交来的 MCP 服务(含 `coda` 服务 `env` 里的令牌 `CODA_TOKEN`)若交给 SDK 的 `mcpServers`,会被写成 `--mcp-config '<JSON>'` 放进 Claude 进程的命令行参数,同一台机器上别的用户看得见。
8
+ 入口改为:会话打开时在系统临时目录下 `mkdtemp` 建目录(0700),把 `{ mcpServers }` 写进里面的 `mcp.json`(0600),用 `extraArgs` 交 `--mcp-config <路径>`。
9
+ 入口这一侧,令牌不再进命令行,只写进这个文件;会话结束(进程被关、查询自己结束)时连目录一起删。进程崩溃留下的目录不另外清理:令牌随托管记录作废,系统临时目录也会自己回收。没有 MCP 服务的会话不建目录。
10
+
11
+ ## 失败怎样分类
12
+
13
+ 一轮失败时,入口(`agent/errors.mjs` 的 `claudeFailure`,纯函数)只按最终错误标失败类别(协议 `failure.json`),重试策略归 Coda,插件里没有重试或等待。
14
+ Claude Code 自己的重试(`system/api_retry`,登记为隐藏)发生在轮次结果之前;重试用尽后才有带 `error` 类别的合成助手消息和失败的 `result`,只有它们到分类函数,所以重试中的轮次不会提前失败。
15
+
16
+ | 最终错误 | 标记 |
17
+ | --- | --- |
18
+ | 明确的用量或余额用尽(`You've hit your … limit`、`Credit balance is too low` 等) | `quota_exhausted`,上游给出窗口重置时间时带 `resetAt` |
19
+ | 网络:`ECONNRESET`、`ECONNREFUSED`、`ETIMEDOUT`、`ENOTFOUND`、`EAI_AGAIN`、`socket hang up`、`fetch failed`、`Unable to connect to API`、`Request timed out`、TLS 握手失败、传输中断 | `service_unavailable` |
20
+ | 上游:5xx、408、`overloaded_error`、529、`api_error`;Claude Code 的 `overloaded`、`server_error` 类别 | `service_unavailable` |
21
+ | Cloudflare 的拦截或挑战页(状态码加 `cloudflare`、`cf-ray`、`Just a moment`、`Attention Required`),先于「认证失败」判断:Claude Code 把它的 403 页报成 `authentication_failed`,这里不再当认证失败 | `service_unavailable` |
22
+ | 登录凭据明确失效:`Failed to authenticate: OAuth session expired and could not be refreshed`(Claude Code 自己的文案,真实样本);类别须是 `authentication_failed` 或没有类别,且不是用量、服务故障 | `auth_required`,`login: "Anthropic OAuth"` |
23
+ | API key 错或缺失(`Invalid API key`)、权限不足、仅有 401 或 403、上下文超长、账单、请求参数错误、证书错误、普通 429、被中止 | 不标 |
24
+
25
+ 证书与 TLS 配置错误(正文里出现 `certificate` 或 `altnames`,如 `unable to get local issuer certificate`、`certificate has expired`、`Hostname/IP does not match certificate's altnames`;以及不带这个词的 Node 证书错误码,如 `DEPTH_ZERO_SELF_SIGNED_CERT`、`UNABLE_TO_VERIFY_LEAF_SIGNATURE`)先按文字排除,**即使 Claude Code 把它们归在 `server_error`**:它把连接错误合成为 `Unable to connect to API: <原因>` 并标 `server_error`,代理拦截 TLS、没配 `NODE_EXTRA_CA_CERTS` 这类永久性配置错误重试也不会好,照普通错误报,完整原因留给用户。
26
+
27
+ `auth_required` 以普通执行错误(-32603)报,不带 `input`、`retryAfterMs`、`resetAt`。
28
+
29
+ `service_unavailable` 的 `input` 是 `accepted`:失败来自轮次的结果,原生会话已经收下并开始处理这一轮;会话自身失败时仍在排队、从未运行的 prompt 是 `not_accepted`,Coda 重投原输入。文字里有 `Retry-After` 或 `retry after` 时带 `retryAfterMs`(毫秒)。
30
+
5
31
  ## 认不出的东西
6
32
 
7
33
  Claude Code 会自己长出新东西:SDK 升级带来新的消息类型,服务端让模型返回新的内容块,模型多了新的原生工具。
package/agent/errors.mjs CHANGED
@@ -13,10 +13,44 @@ const windowReset = /^(You've (?:hit|reached) your [^·]+ · resets )[^·()]+ \(
13
13
  const resetTime = window => window?.status === 'rejected' && Number.isSafeInteger(window.resetsAt) && window.resetsAt > 0 &&
14
14
  window.resetsAt <= 253402300799 ? new Date(window.resetsAt * 1000).toISOString() : undefined;
15
15
 
16
+ // The service or the way to it failing, which can pass (docs/agent-protocol.md「服务暂不可用」): the network (a connection reset,
17
+ // refused or timed out, DNS, a TLS handshake, a transfer cut off) and the service itself (5xx, overloaded, 529, a request that
18
+ // timed out). The retry policy is Coda's. A certificate that is wrong (`certificate`) is not one, and neither is a bare
19
+ // "Connection closed", which an MCP server says as well.
20
+ const network = /\b(?:ECONN(?:RESET|REFUSED|ABORTED)|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH|EPROTO)\b|\bUND_ERR_[A-Z_]+|\bERR_SSL_[A-Z_]+|socket hang up|fetch failed|other side closed|premature close|unexpected EOF|Request timed out|Unable to connect to API|\b(?:TLS|SSL)\b[^\n]{0,40}\bhandshake|\bhandshake (?:failed|timed out)|\bnetwork (?:error|connection (?:lost|error))/i;
21
+ const upstream = /\b(?:API Error:|HTTP|status(?: code)?)\s*:?\s*(?:408|5\d\d)\b|\boverloaded_error\b|\bapi_error\b|Repeated 529|\b(?:Bad Gateway|Service Unavailable|Gateway Time-?out|Internal Server Error)\b/i;
22
+ // A certificate or TLS configuration that is wrong ("Unable to connect to API: unable to get local issuer certificate", an expired
23
+ // certificate, a proxy's certificate whose altnames do not match) stays wrong when retried. Claude Code files these connection errors
24
+ // under `server_error`, so the words rule them out before the category counts: any "certificate" or "altnames", and Node's error codes
25
+ // that carry CERT without saying it.
26
+ const certificate = /certificate|altnames|\bCERT_[A-Z_]+|\b[A-Z_]+_CERT(?:_[A-Z_]+)?\b|\bUNABLE_TO_VERIFY_LEAF_SIGNATURE\b/i;
27
+ // A page of Cloudflare's in place of the API's answer, whatever the status: its 403 is no authentication failure.
28
+ const cloudflare = message => /\b[45]\d\d\b/.test(message) && /cloudflare|cf-ray|Just a moment|Attention Required/i.test(message);
29
+ // The login itself gone (docs/agent-protocol.md「需要重新登录」): Claude Code's own "Failed to authenticate: OAuth session expired and
30
+ // could not be refreshed". A bad or missing API key, a missing permission and a bare 401 or 403 are configuration, which logging in
31
+ // again does not mend.
32
+ const loginLost = /\bOAuth session expired and could not be refreshed\b/;
33
+ // The wait the service asked for, in ms: `Retry-After: 30` is seconds, `retry-after-ms: 1500` or `retry after 1500 ms` milliseconds.
34
+ const waited = message => {
35
+ const [, ms, number, unit] = message.match(/\bretry[-_ ]after(-ms)?\b[":=\s]*(\d+(?:\.\d+)?)\s*(ms|milliseconds?)?/i) ?? [];
36
+ return number === undefined ? undefined : Math.round(Number(number) * (ms || unit ? 1 : 1000));
37
+ };
38
+
16
39
  export function claudeFailure(message, { error, limits, window } = {}) {
17
40
  const quota = (!error || ['rate_limit', 'billing_error'].includes(error)) &&
18
41
  (exhausted(message) || (error === 'rate_limit' && limits?.status === 'rejected'));
19
42
  const resetAt = quota ? resetTime(window) : undefined;
20
- const data = quota ? { _meta: { coda: { failure: { kind: 'quota_exhausted', ...(resetAt ? { resetAt } : {}) } } } } : undefined;
21
- return new RequestError(-32603, resetAt ? message.replace(windowReset, (_, said) => `${said}<t:${resetAt}>`) : message, data);
43
+ // This is the final error: Claude Code's own retries (system/api_retry) are over before a turn's result comes, and the native
44
+ // session has the input by then, so it is always `accepted`. Of the categories Claude Code names, overloaded and server_error
45
+ // are the service's; the words tell for the unnamed (rate_limit, unknown). The rest (authentication, billing, invalid
46
+ // request, ...) are never this, except a Cloudflare page, which Claude Code takes for an authentication failure.
47
+ const unavailable = !quota && !certificate.test(message) && (cloudflare(message) || ['overloaded', 'server_error'].includes(error) ||
48
+ (!error || ['rate_limit', 'unknown'].includes(error)) && (network.test(message) || upstream.test(message)));
49
+ const retryAfterMs = unavailable ? waited(message) : undefined;
50
+ const reauth = !quota && !unavailable && (!error || error === 'authentication_failed') && loginLost.test(message);
51
+ const failure = quota ? { kind: 'quota_exhausted', ...(resetAt ? { resetAt } : {}) } :
52
+ reauth ? { kind: 'auth_required', login: 'Anthropic OAuth' } :
53
+ unavailable ? { kind: 'service_unavailable', input: 'accepted', ...(retryAfterMs === undefined ? {} : { retryAfterMs }) } : undefined;
54
+ return new RequestError(-32603, resetAt ? message.replace(windowReset, (_, said) => `${said}<t:${resetAt}>`) : message,
55
+ failure && { _meta: { coda: { failure } } });
22
56
  }
package/agent/session.mjs CHANGED
@@ -7,8 +7,9 @@
7
7
  // that is to go on later is compacted before its cache expires, as the plugin's lifecycle process asks (compaction.mjs).
8
8
  // What the SDK sends that is not registered, and native tools not known, are told to Coda (registry.mjs).
9
9
  import { randomUUID } from 'node:crypto';
10
- import { readFileSync } from 'node:fs';
10
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
11
  import { realpath, stat } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
12
13
  import { join } from 'node:path';
13
14
  import { agent, PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';
14
15
  import { ClaudeSessionLimits, accountHash } from './limits.mjs';
@@ -163,7 +164,7 @@ export class ClaudeSession {
163
164
  // message would start a turn Coda cannot attribute. Continuing a native subagent is in-process and unaffected.
164
165
  settings: { crossSessionInbound: 'refuse' },
165
166
  includePartialMessages: true, forwardSubagentText: true, cwd: dir,
166
- ...(Object.keys(servers).length ? { mcpServers: servers } : {}), ...(additionalDirectories.length ? { additionalDirectories } : {}),
167
+ ...(Object.keys(servers).length ? { extraArgs: { 'mcp-config': this.mcpConfig({ mcpServers: servers }) } } : {}), ...(additionalDirectories.length ? { additionalDirectories } : {}),
167
168
  // Identify Coda even when a parent supplied an SDK label (anthropics/claude-code#97074).
168
169
  // Claude Code reports running and idle only when asked: idle is what ends a task's wait.
169
170
  env: { ...environment, CLAUDE_CODE_ENTRYPOINT: 'coda', CLAUDE_CODE_EMIT_SESSION_STATE_EVENTS: '1' },
@@ -196,6 +197,18 @@ export class ClaudeSession {
196
197
  throw error instanceof RequestError ? error : failure(error?.message || 'Claude 会话启动失败');
197
198
  }
198
199
  }
200
+ // The SDK would put `mcpServers` in Claude's command line, where the servers' environment (Coda's token) shows to every user of
201
+ // the machine. They go in a file only this user reads, by path, which stays until the session ends (`dropMcpConfig`).
202
+ mcpConfig(config) {
203
+ this.mcpDir = mkdtempSync(join(tmpdir(), 'coda-claude-mcp-'));
204
+ const file = join(this.mcpDir, 'mcp.json');
205
+ writeFileSync(file, JSON.stringify(config), { mode: 0o600 });
206
+ return file;
207
+ }
208
+ dropMcpConfig() {
209
+ if (this.mcpDir) rmSync(this.mcpDir, { recursive: true, force: true });
210
+ this.mcpDir = null;
211
+ }
199
212
  // A query of the session, reading a prompt stream of its own: on Claude's own models, or on `model` of a chosen
200
213
  // service, which it runs with that service as its API and that model for every role. One started after the session
201
214
  // opened goes on with the model, mode and effort chosen.
@@ -436,6 +449,7 @@ export class ClaudeSession {
436
449
  for (const { reject } of this.prompts.values()) reject(failure(error?.message ?? 'Claude 会话已结束'));
437
450
  this.prompts.clear();
438
451
  try { query?.close(); } catch {}
452
+ this.dropMcpConfig();
439
453
  if (!intended) this.onEnded(error);
440
454
  }
441
455
  receive(m) {
@@ -671,8 +685,12 @@ export class ClaudeSession {
671
685
  else { this.held = id; if (cancelled || failed) this.dropRest(outcome); }
672
686
  } else if (!own && failed && this.prompts.size && !(m.queued_turn_count > 0)) {
673
687
  // A failure of the session itself names no input: none of those given can be said to have run. Those still queued
674
- // (queued_turn_count) run after it, each to a result of its own.
675
- for (const prompt of this.prompts.values()) prompt.reject(error);
688
+ // (queued_turn_count) run after it, each to a result of its own. For the service failing that is `not_accepted`: Coda
689
+ // sends the input again rather than asking to carry on.
690
+ const failure = error.data?._meta?.coda?.failure;
691
+ const unsent = failure?.kind === 'service_unavailable' ? new RequestError(error.code, error.message,
692
+ { _meta: { coda: { failure: { ...failure, input: 'not_accepted' } } } }) : error;
693
+ for (const prompt of this.prompts.values()) prompt.reject(unsent);
676
694
  this.prompts.clear();
677
695
  }
678
696
  void this.title?.refresh(!failed && !cancelled);
@@ -683,5 +701,6 @@ export class ClaudeSession {
683
701
  for (const withdrawn of this.withdrawals) withdrawn.abort();
684
702
  try { this.query?.close(); } catch {}
685
703
  if (this.pump) await this.pump; else this.phase = 'ended';
704
+ this.dropMcpConfig();
686
705
  }
687
706
  }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "id": "claude",
4
4
  "displayName": "Claude",
5
5
  "description": "用 Claude Agent SDK 跑会话",
6
- "version": "1.12.2",
6
+ "version": "1.13.2",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],