@coda-console/claude 1.14.0 → 1.14.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 +10 -0
- package/agent/session.mjs +41 -10
- package/agent/usage.mjs +96 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -20,6 +20,16 @@ Coda 给会话一个临时目录时(环境变量 `CODA_SESSION_TMP`,绝对
|
|
|
20
20
|
- 已经留在 `/private/tmp/claude-*` 下的存量目录不在这里处理。
|
|
21
21
|
- 上一节的 `coda-claude-mcp-*` 会话结束时由入口自己删,不在这个目录里。
|
|
22
22
|
|
|
23
|
+
## 会话怎样结束、结束后怎么答
|
|
24
|
+
|
|
25
|
+
SDK 的查询自己结束(Claude 进程被杀、崩溃、正常退出)时,入口把原因记下来:查询抛的错误文字(SDK 已把原生进程的退出码或信号和 stderr 末尾几行写在里面),没有错误就写「Claude SDK 查询结束,没有给出错误」。
|
|
26
|
+
原因写进插件的 stderr 日志(`Claude 会话结束:…`),并放进还在进行的那一轮的错误信息(`Claude 会话已结束:…`)。Coda 主动关闭的会话不写日志。
|
|
27
|
+
|
|
28
|
+
这些错误都标 `session_ended`(原生会话或进程已结束,不是上游服务的问题,Coda 不按服务故障重试)。`input` 只写插件能确定的:正在跑的那一轮的输入是 `accepted`,排在它后面没跑过的是 `not_accepted`,没有一轮在跑时输入有没有被读走说不准,不写。
|
|
29
|
+
|
|
30
|
+
会话已结束后再来的 `session/prompt` 当场拒绝,错误文字是 `Claude 会话未在运行:<原因>`,标 `session_ended`、`input: "not_accepted"`(输入没有进原生会话,Coda 整条重发)。
|
|
31
|
+
换模型服务时重启查询失败、输入还没交给新查询的,同样是 `session_ended` + `not_accepted`;失败本身已带别的类别(如额度、服务)的保留原类别,类别允许 `input` 时补上 `not_accepted`(`auth_required` 不带 `input`,原样保留)。设置项请求(`session/set_config_option`)只带原因,不带标记。
|
|
32
|
+
|
|
23
33
|
## 失败怎样分类
|
|
24
34
|
|
|
25
35
|
一轮失败时,入口(`agent/errors.mjs` 的 `claudeFailure`,纯函数)只按最终错误标失败类别(协议 `failure.json`),重试策略归 Coda,插件里没有重试或等待。
|
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 版本」).
|
|
@@ -51,6 +52,16 @@ const takenIn = m => m.user_message_uuids ?? (m.user_message_uuid ? [m.user_mess
|
|
|
51
52
|
const conversing = m => !m.parent_tool_use_id && (['assistant', 'stream_event'].includes(m.type)
|
|
52
53
|
|| (m.type === 'user' && (!!m.origin || (Array.isArray(m.message?.content) && m.message.content.some(block => block?.type === 'tool_result')))));
|
|
53
54
|
const failure = (message, code = -32603) => new RequestError(code, message);
|
|
55
|
+
// A request for a session not running, with why (what ended it, `endReason`).
|
|
56
|
+
const notRunning = reason => failure(`Claude 会话未在运行${reason ? `:${reason}` : ''}`, -32001);
|
|
57
|
+
// An input refused before it went into the native session: nothing ran it, so Coda may send it again (docs/agent-protocol.md
|
|
58
|
+
// 「原生会话已结束」: `session_ended`, `not_accepted`). A failure the error already names (a quota, a service) keeps its kind,
|
|
59
|
+
// with `not_accepted` where the kind takes an input (not `auth_required`).
|
|
60
|
+
const refused = error => {
|
|
61
|
+
const own = error.data?._meta?.coda?.failure;
|
|
62
|
+
const failure = !own ? { kind: 'session_ended', input: 'not_accepted' } : own.kind === 'auth_required' ? own : { ...own, input: 'not_accepted' };
|
|
63
|
+
return new RequestError(error.code ?? -32603, error.message, { _meta: { coda: { failure } } });
|
|
64
|
+
};
|
|
54
65
|
const denied = { behavior: 'deny', message: 'Coda 没有在请求结束前给出审批' };
|
|
55
66
|
// A child session's output that comes before its task, kept until the task names that session: all of it, since what streamed
|
|
56
67
|
// counts as said, a message's streamed pieces as one.
|
|
@@ -94,6 +105,8 @@ export class ClaudeSession {
|
|
|
94
105
|
// what the native turn going said of compacting (its boundary, its failure, its command's output), the compaction's once
|
|
95
106
|
// that turn's result names its input.
|
|
96
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();
|
|
97
110
|
this.unrecognized = new Unrecognized(params => this.notify('_coda/unrecognized', { sessionId: this.sessionId, ...params }));
|
|
98
111
|
}
|
|
99
112
|
connect(stream) {
|
|
@@ -220,7 +233,7 @@ export class ClaudeSession {
|
|
|
220
233
|
const settings = { ...this.launch.settings, ...(this.current.effort ? { effortLevel: this.current.effort } : {}),
|
|
221
234
|
...(this.current.ultracode === true ? { ultracode: true } : {}),
|
|
222
235
|
...(entry ? serviceSettings(this.services.find(service => service.ref === entry.service), entry.model) : {}) };
|
|
223
|
-
this.serviceModel = entry ? model : null; this.cacheUse.restarted();
|
|
236
|
+
this.serviceModel = entry ? model : null; this.cacheUse.restarted(); this.usage.restarted(!!at.resume);
|
|
224
237
|
// A compaction in the query moved off ends with it.
|
|
225
238
|
this.compacting?.answer({ compacted: false, reason: '会话换到另一个模型,压缩没有做完' }); this.compacting = null;
|
|
226
239
|
this.query = this.sdk.query({ prompt: this.input, options: { ...this.launch, ...at, settings,
|
|
@@ -246,7 +259,7 @@ export class ClaudeSession {
|
|
|
246
259
|
this.query = null; this.input.close();
|
|
247
260
|
try { previous.close(); } catch {}
|
|
248
261
|
await this.pump;
|
|
249
|
-
if (this.phase !== 'running') throw
|
|
262
|
+
if (this.phase !== 'running') throw notRunning(this.endReason);
|
|
250
263
|
// One that cannot be started, or does not start, ends the session, as one that ends of itself does: no later turn waits on it.
|
|
251
264
|
try {
|
|
252
265
|
const said = await this.sdk.getSessionInfo(this.sessionId, { dir: this.cwd });
|
|
@@ -270,7 +283,7 @@ export class ClaudeSession {
|
|
|
270
283
|
// Whether the next turn runs in another query than this one: on another service's model, or back on Claude's own.
|
|
271
284
|
rerouted() { return (this.served(this.current.model)?.id ?? null) !== this.serviceModel; }
|
|
272
285
|
async configure(configId, value) {
|
|
273
|
-
if (this.phase !== 'running') throw
|
|
286
|
+
if (this.phase !== 'running') throw notRunning(this.endReason);
|
|
274
287
|
if (configId === 'mode') {
|
|
275
288
|
if (!MODES.some(mode => mode.id === value)) throw failure('审批模式不可用', -32602);
|
|
276
289
|
await this.query.setPermissionMode(value); this.current.mode = value;
|
|
@@ -298,10 +311,11 @@ export class ClaudeSession {
|
|
|
298
311
|
}
|
|
299
312
|
// Answered when the native result that names this input arrives; accepting it into the input says nothing yet.
|
|
300
313
|
async prompt({ prompt }) {
|
|
301
|
-
if (this.phase !== 'running') throw
|
|
314
|
+
if (this.phase !== 'running') throw refused(notRunning(this.endReason));
|
|
302
315
|
if (this.rerouted()) {
|
|
303
316
|
if (!this.rerouting) { this.cancelling = false; this.rerouting = this.reroute().finally(() => { this.rerouting = null; }); }
|
|
304
|
-
|
|
317
|
+
// A query that cannot be moved to fails here, before the input is pushed.
|
|
318
|
+
try { await this.rerouting; } catch (error) { throw refused(error); }
|
|
305
319
|
// Stopped while it moved: the input is not given to the new query.
|
|
306
320
|
if (this.cancelling) { this.cancelling = false; return { stopReason: 'cancelled' }; }
|
|
307
321
|
}
|
|
@@ -372,10 +386,10 @@ export class ClaudeSession {
|
|
|
372
386
|
settle(id, { stopReason, failure: error }) {
|
|
373
387
|
const prompt = this.prompts.get(id);
|
|
374
388
|
this.prompts.delete(id); this.held = null; this.ending = null; this.steering.clear();
|
|
375
|
-
if (!prompt) return;
|
|
389
|
+
if (!prompt) { this.usage.drop(); return; }
|
|
376
390
|
// What ended before this turn ended was taken in by it.
|
|
377
391
|
this.waits.settled();
|
|
378
|
-
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() });
|
|
379
393
|
}
|
|
380
394
|
// Coda asks the session compacted (the plugin's lifecycle process decides when, compaction.mjs): it compacts as /compact
|
|
381
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
|
|
@@ -445,11 +459,25 @@ export class ClaudeSession {
|
|
|
445
459
|
end(query, error) {
|
|
446
460
|
if (this.phase === 'ended') return;
|
|
447
461
|
const intended = this.phase === 'closing';
|
|
462
|
+
// What ended it, kept for the turns that go on asking and written to the log: a query that ends without an error says so.
|
|
463
|
+
this.endReason = intended ? 'Coda 关闭了会话' : error?.message || 'Claude SDK 查询结束,没有给出错误';
|
|
464
|
+
if (!intended) process.stderr.write(`Claude 会话结束:${this.endReason}\n`);
|
|
465
|
+
const held = this.held, compacting = this.compacting;
|
|
448
466
|
this.phase = 'ended'; this.input.close(); this.steering.clear(); this.held = null; this.ending = null;
|
|
449
467
|
this.compacting?.answer({ compacted: false, reason: error?.message ?? 'Claude 会话已结束' }); this.compacting = null;
|
|
450
468
|
for (const withdrawn of this.withdrawals) withdrawn.abort();
|
|
451
|
-
|
|
452
|
-
|
|
469
|
+
// Each prompt says whether the native session had its input, where that is known: the one a native turn of Coda's is running
|
|
470
|
+
// (or whose turn ended with messages left to take) was taken, those queued behind it never ran. With no such turn going, an
|
|
471
|
+
// input may or may not have been read before the session ended: not said. A compaction Coda asked for came before any prompt
|
|
472
|
+
// that waits (compact), and the turn going is its: those prompts have not run.
|
|
473
|
+
const running = !compacting && this.turning && !this.opening && !this.waits.handling && !this.waits.unclaimed;
|
|
474
|
+
let first = true;
|
|
475
|
+
for (const [id, { reject }] of this.prompts) {
|
|
476
|
+
const input = id === held || running && first ? 'accepted' : running || held || compacting ? 'not_accepted' : undefined;
|
|
477
|
+
first = false;
|
|
478
|
+
reject(new RequestError(-32603, `Claude 会话已结束:${this.endReason}`, { _meta: { coda: { failure: { kind: 'session_ended', ...(input && { input }) } } } }));
|
|
479
|
+
}
|
|
480
|
+
this.prompts.clear(); this.usage.drop();
|
|
453
481
|
try { query?.close(); } catch {}
|
|
454
482
|
this.dropMcpConfig();
|
|
455
483
|
if (!intended) this.onEnded(error);
|
|
@@ -639,6 +667,8 @@ export class ClaudeSession {
|
|
|
639
667
|
}
|
|
640
668
|
}
|
|
641
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);
|
|
642
672
|
const windows = Object.values(m.modelUsage ?? {});
|
|
643
673
|
const ids = takenIn(m);
|
|
644
674
|
// The compaction Coda asked for (compact) is the turn that names its input. Any other is the session's own, whose cache runs
|
|
@@ -682,6 +712,7 @@ export class ClaudeSession {
|
|
|
682
712
|
const own = this.waits.handling || this.waits.unclaimed;
|
|
683
713
|
if (own) this.waits.finished(error ? { error: error.message, title: error.data?._meta?.coda?.failure?.kind === 'quota_exhausted' ? '额度不足' : undefined } : {});
|
|
684
714
|
if (id) {
|
|
715
|
+
this.usage.hold(spent);
|
|
685
716
|
const outcome = this.ending ?? (failed ? { failure: error } : { stopReason: cancelled ? 'cancelled' : 'end_turn' });
|
|
686
717
|
if (this.ending || !this.steering.size) this.settle(id, outcome);
|
|
687
718
|
else { this.held = id; if (cancelled || failed) this.dropRest(outcome); }
|
|
@@ -693,7 +724,7 @@ export class ClaudeSession {
|
|
|
693
724
|
const unsent = failure?.kind === 'service_unavailable' ? new RequestError(error.code, error.message,
|
|
694
725
|
{ _meta: { coda: { failure: { ...failure, input: 'not_accepted' } } } }) : error;
|
|
695
726
|
for (const prompt of this.prompts.values()) prompt.reject(unsent);
|
|
696
|
-
this.prompts.clear();
|
|
727
|
+
this.prompts.clear(); this.usage.drop();
|
|
697
728
|
}
|
|
698
729
|
void this.title?.refresh(!failed && !cancelled);
|
|
699
730
|
}
|
package/agent/usage.mjs
ADDED
|
@@ -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
|
+
}
|