@coda-console/claude 1.14.1 → 1.14.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.
package/README.md CHANGED
@@ -100,3 +100,27 @@ Claude Code 会自己长出新东西:SDK 升级带来新的消息类型,服
100
100
  | `prewarm` 进入 `/core`;`Settings.permissions.blockWritesOutsideWorkingDirectories / blockReadsExemptPaths / workingDirectoriesAsGiven / denyInsteadOfPrompting`、`disableReplyCheck / disableWindowsBashCommandSplit`;`PushNotificationInput.status` 可省略 | 有意不启用;继续使用现有 `query`、Stop hook 和设置。 |
101
101
 
102
102
  ACP 2.6.0 只使用默认 stable v1。逐项经过真实连接的解析测试:`initialize` 保留 `clientCapabilities._meta.coda.unrecognized`;`new/load` 保留目录、MCP 配置及其环境变量、`systemPrompt`、`_meta`;`prompt` 保留文本及内容块的 `_meta`;配置值与模式照常到达处理器;`_session/steering`、`_coda/wait/stop`、`_coda/session/compact` 沿用原自有解析器。未发现 Coda 用到的字段被新版裁掉,因而没有新增解析器。`new/load` 原注释中“schema 不认识 systemPrompt”在 2.6.0 已不成立。
103
+
104
+ ## 资源页:额度与登录
105
+
106
+ 另带资源页上的资源类型「Claude」:会话报告的套餐额度,以及从 Coda 登录。
107
+
108
+ - **额度从哪来**:只来自这台机器上 Claude SDK 会话自己的报告,不看本机 Claude CLI 的登录(不读 `~/.claude` 的凭据与钥匙串,也不临时启动 CLI 问 `/usage`)。
109
+ Coda 的 Claude 会话常用 setup token,它没有 profile 权限,问不到 `/usage`,也不一定与本机 CLI 是同一个账号;
110
+ 而会话里的 CLI 在套餐窗口的已用比例或重置时间变动时发 `rate_limit_event`,入口从中读出窗口,
111
+ 合并写进插件状态目录的 `limits.json`(每个写入方用自己的临时文件,原子替换),不经过会话、不进会话历史。
112
+ `unifiedWindows`(新版 CLI 的内部字段,升级 SDK 时要复核)每次带全部窗口,旧版只带顶层的 `rateLimitType`、`utilization`、`resetsAt`(当前受限的那个);
113
+ 两处都有时取前者。已用比例是 0 到 1 的小数,超过 1 按剩余 0;重置时间是 Unix 秒。每个窗口只留最近一次,多个会话报告同一窗口时以后到的为准。
114
+ - **显示**:没有会话报告过(没跑过 Claude 会话,或是 API key、Bedrock、Vertex 的会话,没有这些窗口)时输出为空,「Claude」出现在「添加资源」里。
115
+ 报告过就一个资源(不写名字:文件里只有账号的哈希),每个窗口一个读数(5 小时、7 天、Opus · 7 天、Sonnet · 7 天、Fable · 7 天,按这个顺序),条画剩余,时刻是重置时间。
116
+ 过了重置时间的窗口不再显示(重置后用了多少这里看不到,既不当作用满也不当作清空);全部过期时那一行写「额度记录已过期,会话再运行后更新」。每次打开都读文件。
117
+ - **身份**:会话启动时 SDK 报出账号邮箱的,资源带身份 `claude:<邮箱的哈希>`(Coda 的资源页据此合并同一账号;文件里只存哈希)。
118
+ 它跟着最近启动的会话换账号:换了账号旧窗口作废,别的账号的旧会话再报来的额度不写入;拿不到邮箱的会话(如 setup token、API key)不带身份。
119
+ - **登录**:`signIn` 运行 `scripts/login.mjs`,它启动插件依赖的 Claude SDK 自带的 `claude auth login --claudeai`(与会话用的是同一个,不用 `PATH` 上另一份 Claude),
120
+ 运行机不打开浏览器(`BROWSER=/usr/bin/true`),也不导入环境里的 refresh token,而是发起新的网页登录。
121
+ 只把 CLI 输出里官方的授权链接(`claude.ai/oauth/authorize` 或 `claude.com/cai/oauth/authorize`,带 `state` 与 `code_challenge`)交给 Coda,其余输出不传出(可能带着授权码)。
122
+ 用户贴回的授权码须是 `<码>#<state>` 且 `state` 与这次的链接相符,才交给 CLI;不符就结束登录,写「授权码不对」。CLI 没登成时写固定的「Claude 登录没有完成,请重新登录。」,不回显它的输出。
123
+ PKCE、令牌交换、凭据保存和续期都由 Claude CLI 负责,沿用服务账号的 `CLAUDE_CONFIG_DIR`。配置了 token 文件、OAuth token、API key 或云服务商时它们仍然优先,添加窗口里写明。
124
+ SDK 0.3.296 的登录输出与原生二进制包布局是这里的版本边界,升级时复核。
125
+
126
+ 「模型服务」设置的行为见仓库根 README 的「模型服务」。
package/agent/session.mjs CHANGED
@@ -23,6 +23,7 @@ import { toolCallFields, ToolCallCache } from './tools.mjs';
23
23
  import { elicitationForm, questionForm } from './questions.mjs';
24
24
  import { ClaudeWaits } from './waits.mjs';
25
25
  import { CacheUse } from './compaction.mjs';
26
+ import { PromptUsage } from './usage.mjs';
26
27
  import { ASSISTANT_BLOCKS, MESSAGES, USER_BLOCKS, Unrecognized, messageName } from './registry.mjs';
27
28
 
28
29
  // The Claude Agent SDK this entry runs, as the handshake's `agentInfo` names it (Coda's protocol「Agent 版本」).
@@ -104,6 +105,8 @@ export class ClaudeSession {
104
105
  // what the native turn going said of compacting (its boundary, its failure, its command's output), the compaction's once
105
106
  // that turn's result names its input.
106
107
  this.cacheUse = new CacheUse({ now }); this.compacting = null; this.turnCompaction = {};
108
+ // What the prompts use, from the SDK's cumulative modelUsage (usage.mjs): told in the prompt's response as `usage`.
109
+ this.usage = new PromptUsage();
107
110
  this.unrecognized = new Unrecognized(params => this.notify('_coda/unrecognized', { sessionId: this.sessionId, ...params }));
108
111
  }
109
112
  connect(stream) {
@@ -230,7 +233,7 @@ export class ClaudeSession {
230
233
  const settings = { ...this.launch.settings, ...(this.current.effort ? { effortLevel: this.current.effort } : {}),
231
234
  ...(this.current.ultracode === true ? { ultracode: true } : {}),
232
235
  ...(entry ? serviceSettings(this.services.find(service => service.ref === entry.service), entry.model) : {}) };
233
- this.serviceModel = entry ? model : null; this.cacheUse.restarted();
236
+ this.serviceModel = entry ? model : null; this.cacheUse.restarted(); this.usage.restarted(!!at.resume);
234
237
  // A compaction in the query moved off ends with it.
235
238
  this.compacting?.answer({ compacted: false, reason: '会话换到另一个模型,压缩没有做完' }); this.compacting = null;
236
239
  this.query = this.sdk.query({ prompt: this.input, options: { ...this.launch, ...at, settings,
@@ -383,10 +386,10 @@ export class ClaudeSession {
383
386
  settle(id, { stopReason, failure: error }) {
384
387
  const prompt = this.prompts.get(id);
385
388
  this.prompts.delete(id); this.held = null; this.ending = null; this.steering.clear();
386
- if (!prompt) return;
389
+ if (!prompt) { this.usage.drop(); return; }
387
390
  // What ended before this turn ended was taken in by it.
388
391
  this.waits.settled();
389
- if (error) prompt.reject(error); else prompt.resolve({ stopReason });
392
+ if (error) { this.usage.drop(); prompt.reject(error); } else prompt.resolve({ stopReason, ...this.usage.take() });
390
393
  }
391
394
  // Coda asks the session compacted (the plugin's lifecycle process decides when, compaction.mjs): it compacts as /compact
392
395
  // would, in a turn that is neither Coda's nor Claude's own (result), and answers with the context before and after. One not
@@ -474,7 +477,7 @@ export class ClaudeSession {
474
477
  first = false;
475
478
  reject(new RequestError(-32603, `Claude 会话已结束:${this.endReason}`, { _meta: { coda: { failure: { kind: 'session_ended', ...(input && { input }) } } } }));
476
479
  }
477
- this.prompts.clear();
480
+ this.prompts.clear(); this.usage.drop();
478
481
  try { query?.close(); } catch {}
479
482
  this.dropMcpConfig();
480
483
  if (!intended) this.onEnded(error);
@@ -664,6 +667,8 @@ export class ClaudeSession {
664
667
  }
665
668
  }
666
669
  result(m) {
670
+ // What this turn used; the base moves with every result, whose turn it is told as (below) or not.
671
+ const spent = this.usage.measure(m);
667
672
  const windows = Object.values(m.modelUsage ?? {});
668
673
  const ids = takenIn(m);
669
674
  // The compaction Coda asked for (compact) is the turn that names its input. Any other is the session's own, whose cache runs
@@ -707,6 +712,7 @@ export class ClaudeSession {
707
712
  const own = this.waits.handling || this.waits.unclaimed;
708
713
  if (own) this.waits.finished(error ? { error: error.message, title: error.data?._meta?.coda?.failure?.kind === 'quota_exhausted' ? '额度不足' : undefined } : {});
709
714
  if (id) {
715
+ this.usage.hold(spent);
710
716
  const outcome = this.ending ?? (failed ? { failure: error } : { stopReason: cancelled ? 'cancelled' : 'end_turn' });
711
717
  if (this.ending || !this.steering.size) this.settle(id, outcome);
712
718
  else { this.held = id; if (cancelled || failed) this.dropRest(outcome); }
@@ -718,7 +724,7 @@ export class ClaudeSession {
718
724
  const unsent = failure?.kind === 'service_unavailable' ? new RequestError(error.code, error.message,
719
725
  { _meta: { coda: { failure: { ...failure, input: 'not_accepted' } } } }) : error;
720
726
  for (const prompt of this.prompts.values()) prompt.reject(unsent);
721
- this.prompts.clear();
727
+ this.prompts.clear(); this.usage.drop();
722
728
  }
723
729
  void this.title?.refresh(!failed && !cancelled);
724
730
  }
@@ -0,0 +1,96 @@
1
+ // What a prompt used, as `PromptResponse.usage` says it (Coda's per-turn token collection): this turn's increment only, `inputTokens`
2
+ // the uncached input (the cached reads and writes not in it), the cache reads and writes beside it, and `breakdown` by model
3
+ // where the models are known (when it is there, it is the whole of what Coda counts; the top level is its sum).
4
+ //
5
+ // The SDK's result carries `modelUsage`, per model and cumulative over the query() call: main loop, Task subagents and all. This
6
+ // keeps what the last result said (`base`) and answers each result with the difference, so that a turn says what it used.
7
+ // - A new session's query starts at 0: its first result is the first turn's own.
8
+ // - A resumed one (session/load, or a query started again for another model's service) carries its transcript's totals in its
9
+ // first result. Those are the history, not the turn: they become the base, and that turn goes by the result's `usage` (the main
10
+ // loop of that turn alone, with no model told) in place of the difference. From the second result the differences hold again.
11
+ // - A counter that went down is a reset (/clear): the model's turn is what it says now.
12
+ // - A crash or startup failure says zeros with a subtype other than success: it says nothing, and the base stays as it was.
13
+ // A result no prompt of Coda's owns (a compaction Coda asked for, a turn Claude began on its own) moves the base and is not told
14
+ // as any prompt's: its tokens belong to no turn of the user's. What a prompt used is held from its results until it is answered
15
+ // (steering may take several results to answer one prompt); one that fails reports none.
16
+ const FIELDS = ['inputTokens', 'outputTokens', 'cachedReadTokens', 'cachedWriteTokens'];
17
+ const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
18
+ const total = counts => FIELDS.reduce((sum, field) => sum + (counts[field] ?? 0), 0);
19
+ const none = counts => total(counts) === 0;
20
+ const plus = (a, b) => ({
21
+ inputTokens: a.inputTokens + b.inputTokens, outputTokens: a.outputTokens + b.outputTokens,
22
+ // Unreported (null) stays so until something reports it.
23
+ cachedReadTokens: a.cachedReadTokens === null && b.cachedReadTokens === null ? null : (a.cachedReadTokens ?? 0) + (b.cachedReadTokens ?? 0),
24
+ cachedWriteTokens: a.cachedWriteTokens === null && b.cachedWriteTokens === null ? null : (a.cachedWriteTokens ?? 0) + (b.cachedWriteTokens ?? 0),
25
+ });
26
+ // A model's counts from the SDK's ModelUsage; null where it says none of them.
27
+ function fromModelUsage(usage) {
28
+ if (!usage || typeof usage !== 'object') return null;
29
+ const counts = [usage.inputTokens, usage.outputTokens, usage.cacheReadInputTokens, usage.cacheCreationInputTokens].map(count);
30
+ if (counts.every(value => value === null)) return null;
31
+ const [inputTokens, outputTokens, cachedReadTokens, cachedWriteTokens] = counts.map(value => value ?? 0);
32
+ return { inputTokens, outputTokens, cachedReadTokens, cachedWriteTokens };
33
+ }
34
+ // The main loop's counts from a result's `usage` (the API's field names); null where it says none of them.
35
+ function fromApiUsage(usage) {
36
+ if (!usage || typeof usage !== 'object') return null;
37
+ const [inputTokens, outputTokens, cachedReadTokens, cachedWriteTokens] = [usage.input_tokens, usage.output_tokens, usage.cache_read_input_tokens, usage.cache_creation_input_tokens].map(count);
38
+ if (inputTokens === null && outputTokens === null && cachedReadTokens === null && cachedWriteTokens === null) return null;
39
+ return { inputTokens: inputTokens ?? 0, outputTokens: outputTokens ?? 0, cachedReadTokens, cachedWriteTokens };
40
+ }
41
+ const increase = (now, before) => !before || FIELDS.some(field => now[field] < before[field]) ? now
42
+ : Object.fromEntries(FIELDS.map(field => [field, now[field] - before[field]]));
43
+
44
+ // What was used, by model name, and what no model is told of.
45
+ class Spent {
46
+ models = new Map(); loose = null;
47
+ addModel(model, counts) { this.models.set(model, this.models.has(model) ? plus(this.models.get(model), counts) : counts); }
48
+ addLoose(counts) { this.loose = this.loose ? plus(this.loose, counts) : counts; }
49
+ merge(other) {
50
+ for (const [model, counts] of other.models) this.addModel(model, counts);
51
+ if (other.loose) this.addLoose(other.loose);
52
+ }
53
+ // `usage` for the response, or nothing where no token was used.
54
+ report() {
55
+ const models = [...this.models].filter(([, counts]) => !none(counts));
56
+ const all = [...models.map(([, counts]) => counts), ...(this.loose && !none(this.loose) ? [this.loose] : [])];
57
+ if (!all.length) return {};
58
+ const sum = all.reduce(plus);
59
+ const usage = { totalTokens: total(sum), inputTokens: sum.inputTokens, outputTokens: sum.outputTokens,
60
+ ...(sum.cachedReadTokens === null ? {} : { cachedReadTokens: sum.cachedReadTokens }),
61
+ ...(sum.cachedWriteTokens === null ? {} : { cachedWriteTokens: sum.cachedWriteTokens }) };
62
+ // The breakdown is all that Coda counts when it is there: one that leaves out a part is not told.
63
+ if (!this.loose || none(this.loose)) usage.breakdown = models.map(([model, counts]) => ({ model, ...counts }));
64
+ return { usage };
65
+ }
66
+ }
67
+
68
+ export class PromptUsage {
69
+ base = new Map(); held = new Spent();
70
+ // A query begins: a new session's from nothing, a resumed one's with its history (its first result says it).
71
+ restarted(resumed) { this.base = resumed ? null : new Map(); this.held = new Spent(); }
72
+ // What this result's turn used (never throws: the result is handled whatever this makes of it).
73
+ measure(m) {
74
+ const spent = new Spent();
75
+ try {
76
+ const entries = Object.entries(m.modelUsage ?? {}).map(([key, usage]) => ({ key, usage, counts: fromModelUsage(usage) })).filter(entry => entry.counts);
77
+ if (m.subtype !== 'success' && entries.every(entry => none(entry.counts))) return spent;
78
+ if (this.base === null) {
79
+ this.base = new Map(entries.map(entry => [entry.key, entry.counts]));
80
+ const counts = fromApiUsage(m.usage);
81
+ if (counts) spent.addLoose(counts);
82
+ return spent;
83
+ }
84
+ for (const { key, usage, counts } of entries) {
85
+ spent.addModel(typeof usage.canonicalModel === 'string' && usage.canonicalModel ? usage.canonicalModel : key, increase(counts, this.base.get(key)));
86
+ this.base.set(key, counts);
87
+ }
88
+ } catch {}
89
+ return spent;
90
+ }
91
+ // The turn of a prompt of Coda's used this; told when the prompt is answered.
92
+ hold(spent) { this.held.merge(spent); }
93
+ // The prompt is answered with what it used (`usage` of the response, or nothing), or failed: it reports none.
94
+ take() { const usage = this.held.report(); this.held = new Spent(); return usage; }
95
+ drop() { this.held = new Spent(); }
96
+ }
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.14.1",
6
+ "version": "1.14.3",
7
7
  "categories": [
8
8
  "Agent"
9
9
  ],