worktrust 0.10.38 → 0.11.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.
@@ -0,0 +1,212 @@
1
+ /**
2
+ * CLAUDE CODE'S STREAM, AS THE PROTOCOL'S EVENTS: ONE PURE FUNCTION (2026-11-07). `claude -p --input-format stream-json
3
+ * --output-format stream-json --verbose [--include-partial-messages]` writes one JSON object per line;
4
+ * `mapClaudeLine(state, line, mint, now)` turns one of them into the protocol's sealed events and says when a turn starts
5
+ * or ends. No I/O and no clock of its own: `mint(prefix)` makes opaque ids, `now` is the computer's clock or null. Held by
6
+ * scripts/test-remote-claude-events.mjs against two recorded Claude Code 2.1.286 runs (scripts/fixtures/remote/), one
7
+ * with partial messages, and a third in the same format with a plan and subagents. The plan, the agent map and the
8
+ * tokens are remote-claude-progress.mjs (owner, 2026-11-07).
9
+ *
10
+ * Claude Code line protocol event(s) turn
11
+ * system/init (the session's own id, model and folder noted; started
12
+ * the turn's started_at)
13
+ * stream_event text_delta (partial messages) agent.output_delta {assistant}, coalesced: one event
14
+ * per 2,048 characters or at the block's end
15
+ * stream_event message_start / message_delta agent.usage {running}, the main agent's only
16
+ * assistant: text block (no partial messages) agent.output_delta {assistant}, cut at 65,536
17
+ * assistant: tool_use block agent.step_started {label, kind, steps, plan_item_id}
18
+ * assistant: TodoWrite, TaskCreate, TaskUpdate + agent.plan, whole, when the plan changed
19
+ * assistant: Task or Agent tool_use + agent.subagent {started}
20
+ * assistant: a message's usage + agent.usage {running}, the main agent's only
21
+ * assistant: thinking block, thinking deltas (nothing: never sent)
22
+ * user: tool_result block agent.step_completed {ok | failed, duration_ms}
23
+ * user: tool_result, is_error + agent.output_delta {tool} with the reason
24
+ * user: tool_result of a test command (its outcome and counts kept for the result)
25
+ * user: a Task's result (tool_use_result) + agent.subagent {done | failed, tokens, steps, duration}
26
+ * a tracked subagent's assistant / user line its steps {subagent_id}, agent.subagent {working, steps};
27
+ * (parent_tool_use_id) its text is never sent as the reply
28
+ * system task_started / task_progress / agent.subagent {the tokens, tool uses, duration, end}
29
+ * task_notification
30
+ * result, success agent.usage {final}, agent.completed {summary, steps,
31
+ * result: the full answer and the tests; the files are
32
+ * added by the session; started_at, duration_ms} ended
33
+ * result, an error subtype or is_error agent.usage, agent.failed {adapter_error | timeout} ended
34
+ * an untracked subagent's line, system/status, system/thinking_tokens, rate_limit_event, other stream_event types,
35
+ * anything else: nothing, counted
36
+ */
37
+ import { emptyProgress, planItemNow, progressAssistant, progressEndSubagents, progressInit, progressResult, progressStream, progressTask, progressUser, subagentLine, subagentOf } from "./remote-claude-progress.mjs";
38
+
39
+ /** The agent's run ended (a stop, its exit): every subagent not ended is stopped, background ones too. */
40
+ export function endClaudeRun(state, now = null) {
41
+ const p = progressEndSubagents(state.progress, Number.isSafeInteger(now) ? now : null, { background: true });
42
+ return { state: { ...state, progress: p.state }, events: p.events };
43
+ }
44
+
45
+ export const CHUNK_CHARS = 2048;
46
+ const MAX_ANSWER = 262_144;
47
+ export const emptyClaudeState = () => ({ steps: {}, stepAt: {}, tests: {}, testRuns: [], started: 0, completed: 0, offset: 0, pending: "", streamed: false, cwd: null, sessionRef: null, model: null, ignored: 0, turnStartedAt: null, progress: emptyProgress() });
48
+
49
+ const cut = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
50
+ const relative = (cwd, path) => (typeof path !== "string" ? "" : cwd && path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path);
51
+ export const TEST_COMMAND = /(^|\s)(test|tests|pytest|jest|vitest|mocha|--test)(\s|$)/;
52
+
53
+ /** The step's words and kind, from the tool's own name and input. */
54
+ export function stepOf(name, input, cwd) {
55
+ const a = input && typeof input === "object" ? input : {};
56
+ switch (name) {
57
+ case "Bash": { const command = String(a.command ?? ""); return { label: cut(`Run ${command}`, 500), kind: TEST_COMMAND.test(command) ? "test" : "command" }; }
58
+ case "Read": case "NotebookRead": return { label: cut(`Read ${relative(cwd, a.file_path ?? a.notebook_path)}`, 500), kind: "read" };
59
+ case "Edit": case "MultiEdit": case "NotebookEdit": return { label: cut(`Edit ${relative(cwd, a.file_path ?? a.notebook_path)}`, 500), kind: "edit" };
60
+ case "Write": return { label: cut(`Write ${relative(cwd, a.file_path)}`, 500), kind: "edit" };
61
+ case "Glob": case "Grep": return { label: cut(`Search ${String(a.pattern ?? "")}`, 500), kind: "search" };
62
+ case "WebFetch": case "WebSearch": return { label: cut(`Look up ${String(a.url ?? a.query ?? "")}`, 500), kind: "search" };
63
+ case "Task": case "Agent": return { label: cut(`Delegate ${String(a.description ?? "")}`, 500), kind: "tool" };
64
+ case "TodoWrite": case "TaskCreate": case "TaskUpdate": return { label: "Plan the work", kind: "think" };
65
+ default: return { label: cut(`Use ${String(name ?? "a tool")}`, 500), kind: "tool" };
66
+ }
67
+ }
68
+
69
+ /** Counts a test runner printed: node --test, Jest, Vitest, pytest, Go and cargo. Null when it named none. */
70
+ export function testCounts(output) {
71
+ const t = String(output ?? "");
72
+ const num = (re) => { const m = re.exec(t); return m ? Number(m[1]) : null; };
73
+ let passed = num(/(?:^|\n)[ℹ#] pass (\d+)/), failed = num(/(?:^|\n)[ℹ#] fail (\d+)/), total = num(/(?:^|\n)[ℹ#] tests (\d+)/);
74
+ if (passed === null) { const jest = /Tests:\s+(?:(\d+) failed, )?(?:\d+ skipped, )?(?:(\d+) passed, )?(\d+) total/.exec(t); if (jest) { failed = Number(jest[1] ?? 0); passed = Number(jest[2] ?? 0); total = Number(jest[3]); } }
75
+ if (passed === null) { const vitest = /Tests\s+(?:(\d+) failed \| )?(\d+) passed/.exec(t); if (vitest) { failed = Number(vitest[1] ?? 0); passed = Number(vitest[2]); } }
76
+ if (passed === null) { const py = /=+ (?:(\d+) failed, )?(\d+) passed/.exec(t) ?? /(\d+) passed/.exec(t); if (py) { passed = Number(py[2] ?? py[1]); failed = num(/(\d+) failed/) ?? 0; } }
77
+ if (passed === null) { const cargo = /test result: \w+\. (\d+) passed; (\d+) failed/.exec(t); if (cargo) { passed = Number(cargo[1]); failed = Number(cargo[2]); } }
78
+ return passed === null && failed === null ? null : { passed, failed, total: total ?? (passed !== null && failed !== null ? passed + failed : null) };
79
+ }
80
+
81
+ const steps = (s) => ({ kind: "steps", started: s.started, completed: s.completed });
82
+ const textOfResult = (content) => (typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => b?.type === "text").map((b) => b.text).join("\n") : "");
83
+ function flush(s, events, all) {
84
+ while (s.pending.length >= CHUNK_CHARS || (all && s.pending.length > 0)) {
85
+ const text = s.pending.slice(0, CHUNK_CHARS);
86
+ s.pending = s.pending.slice(text.length);
87
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
88
+ s.offset += text.length;
89
+ }
90
+ }
91
+
92
+ const toolUses = (content) => content.filter((b) => b?.type === "tool_use" && typeof b.id === "string").length;
93
+ const at = (now) => (Number.isSafeInteger(now) && now >= 0 ? now : null);
94
+ /** started_at and duration_ms of the turn that ends now, where the clock was given. */
95
+ const turnTime = (s, now) => (s.turnStartedAt !== null && at(now) !== null && now >= s.turnStartedAt ? { started_at: s.turnStartedAt, duration_ms: now - s.turnStartedAt } : s.turnStartedAt !== null ? { started_at: s.turnStartedAt } : {});
96
+
97
+ /**
98
+ * "READY, BUT A JOB IS STILL RUNNING" (owner, 2026-11-08): the background jobs the agent itself reports, by Claude Code's
99
+ * own task lines (system task_started with is_backgrounded, then its task_notification). Counted only: never a process
100
+ * looked at, never a job's output read. → the open task ids, or null while the agent reported no background job at all
101
+ * (a surface then shows nothing, never a 0 it cannot know).
102
+ */
103
+ export function backgroundJobs(open, line) {
104
+ if (line?.type !== "system" || typeof line.task_id !== "string") return open;
105
+ if (line.subtype === "task_started" && line.is_backgrounded === true) return new Set([...(open ?? []), line.task_id]);
106
+ if (line.subtype === "task_notification" && open?.has(line.task_id)) { const next = new Set(open); next.delete(line.task_id); return next; }
107
+ return open;
108
+ }
109
+
110
+ /**
111
+ * One line in, the protocol's events out. `mint(prefix)` makes an opaque id of that kind ("stp" by default); `now` is the
112
+ * computer's clock in milliseconds, or null (no times are then sent).
113
+ */
114
+ export function mapClaudeLine(state, line, mint, now = null) {
115
+ const s = { ...state, steps: { ...state.steps }, tests: { ...state.tests }, testRuns: [...state.testRuns], stepAt: { ...state.stepAt } };
116
+ const events = [];
117
+ const id = (prefix = "stp") => mint(prefix);
118
+ if (!line || typeof line !== "object") return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
119
+ const parent = typeof line.parent_tool_use_id === "string" && line.parent_tool_use_id ? line.parent_tool_use_id : null;
120
+ const sub = parent ? subagentOf(s.progress, parent) : null;
121
+ // A line of a subagent this computer does not track (past the cap, or of an untracked parent): nothing, counted.
122
+ if (parent && (!sub || (line.type !== "assistant" && line.type !== "user"))) return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
123
+ if (line.type === "system" && line.subtype === "init") {
124
+ s.sessionRef = typeof line.session_id === "string" ? line.session_id : s.sessionRef;
125
+ s.model = typeof line.model === "string" ? line.model : s.model;
126
+ s.cwd = typeof line.cwd === "string" ? line.cwd : s.cwd;
127
+ s.turnStartedAt = at(now);
128
+ s.progress = progressInit(s.progress, line);
129
+ return { state: s, events, turn: "started" };
130
+ }
131
+ if (line.type === "system" && /^task_(started|progress|notification)$/.test(line.subtype ?? "")) {
132
+ const p = progressTask(s.progress, line, at(now));
133
+ return { state: { ...s, progress: p.state }, events: p.events, turn: null };
134
+ }
135
+ if (line.type === "stream_event") {
136
+ const e = line.event ?? {};
137
+ if (e.type === "content_block_delta" && e.delta?.type === "text_delta" && typeof e.delta.text === "string") { s.streamed = true; s.pending += e.delta.text; flush(s, events, false); }
138
+ else if (e.type === "content_block_stop" || e.type === "message_stop") flush(s, events, true);
139
+ const p = progressStream(s.progress, line);
140
+ s.progress = p.state;
141
+ events.push(...p.events);
142
+ return { state: s, events, turn: null };
143
+ }
144
+ if (line.type === "assistant" && Array.isArray(line.message?.content)) {
145
+ const minted = {};
146
+ for (const block of line.message.content) {
147
+ if (block?.type === "text" && typeof block.text === "string" && block.text.length > 0 && !s.streamed && !sub) {
148
+ const text = block.text.slice(0, 65_536);
149
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
150
+ s.offset += text.length;
151
+ } else if (block?.type === "tool_use" && typeof block.id === "string") {
152
+ if (!sub) flush(s, events, true);
153
+ const step_id = id("stp");
154
+ minted[block.id] = step_id;
155
+ s.steps[block.id] = step_id;
156
+ s.stepAt[block.id] = at(now);
157
+ s.started += 1;
158
+ const step = stepOf(block.name, block.input, s.cwd);
159
+ if (step.kind === "test") s.tests[block.id] = String(block.input?.command ?? "").slice(0, 500);
160
+ const item = planItemNow(s.progress);
161
+ events.push({ type: "agent.step_started", body: { step_id, ...step, progress: steps(s), ...(item ? { plan_item_id: item } : {}), ...(sub ? { subagent_id: sub.subagent_id } : {}) } });
162
+ }
163
+ }
164
+ const p = progressAssistant(s.progress, line, { now: at(now), mint: id, stepFor: (b) => minted[b.id] });
165
+ s.progress = p.state;
166
+ events.push(...p.events);
167
+ if (sub) { const e = subagentLine(s.progress, parent, toolUses(line.message.content)); if (e) events.push(e); }
168
+ return { state: s, events, turn: null };
169
+ }
170
+ if (line.type === "user" && Array.isArray(line.message?.content)) {
171
+ for (const block of line.message.content) {
172
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
173
+ const step_id = s.steps[block.tool_use_id];
174
+ if (!step_id) { s.ignored += 1; continue; }
175
+ const began = s.stepAt[block.tool_use_id];
176
+ delete s.steps[block.tool_use_id];
177
+ delete s.stepAt[block.tool_use_id];
178
+ s.completed += 1;
179
+ const duration = began !== null && began !== undefined && at(now) !== null && now >= began ? { duration_ms: now - began } : {};
180
+ events.push({ type: "agent.step_completed", body: { step_id, outcome: block.is_error ? "failed" : "ok", progress: steps(s), ...duration } });
181
+ const output = textOfResult(block.content);
182
+ if (s.tests[block.tool_use_id] !== undefined && s.testRuns.length < 20) {
183
+ const counts = testCounts(output);
184
+ const outcome = block.is_error || (counts?.failed ?? 0) > 0 ? "failed" : counts ? "passed" : "unknown";
185
+ s.testRuns.push({ command: s.tests[block.tool_use_id] || "tests", outcome, passed: counts?.passed ?? null, failed: counts?.failed ?? null, total: counts?.total ?? null });
186
+ delete s.tests[block.tool_use_id];
187
+ }
188
+ const reason = block.is_error && !sub ? output.trim() : "";
189
+ if (reason) events.push({ type: "agent.output_delta", body: { stream: "tool", offset: 0, text: cut(reason, 2000) } });
190
+ }
191
+ const p = progressUser(s.progress, line, { now: at(now), textOf: (b) => textOfResult(b.content) });
192
+ s.progress = p.state;
193
+ events.push(...p.events);
194
+ if (sub) { const e = subagentLine(s.progress, parent, 0); if (e) events.push(e); }
195
+ return { state: s, events, turn: null };
196
+ }
197
+ if (line.type === "result") {
198
+ flush(s, events, true);
199
+ const failed = line.is_error === true || (typeof line.subtype === "string" && line.subtype !== "success");
200
+ const answer = typeof line.result === "string" && line.result.trim() ? line.result.trim() : null;
201
+ let p = progressResult(s.progress, line);
202
+ events.push(...p.events);
203
+ if (failed) { const ended = progressEndSubagents(p.state, at(now), { background: false }); p = { ...p, state: ended.state }; events.push(...ended.events); }
204
+ const time = turnTime(s, now);
205
+ events.push(failed
206
+ ? { type: "agent.failed", body: { reason: line.subtype === "error_max_turns" ? "timeout" : "adapter_error", message: answer ? cut(answer, 4000) : null, ...time } }
207
+ : { type: "agent.completed", body: { summary: answer ? cut(answer, 4000) : null, progress: steps(s), result: { answer: answer ? answer.slice(0, MAX_ANSWER) : null, answer_cut: (answer?.length ?? 0) > MAX_ANSWER, source: "none", files: [], files_cut: false, tests: s.testRuns }, ...time } });
208
+ // A new turn counts its own steps and tests; the plan, the subagents and the session's tokens go on.
209
+ return { state: { ...s, progress: p.state, steps: {}, stepAt: {}, tests: {}, testRuns: [], started: 0, completed: 0, streamed: false, pending: "", turnStartedAt: null }, events, turn: "ended" };
210
+ }
211
+ return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
212
+ }
@@ -0,0 +1,328 @@
1
+ /**
2
+ * CLAUDE CODE'S PLAN, SUBAGENTS AND TOKENS, AS THE PROTOCOL'S SEALED PROGRESS (owner, 2026-11-07: a roadmap with a 0 to
3
+ * 100% loader, an agent map, the token usage and the elapsed time while a prompt runs on the phone). Pure: no I/O and no
4
+ * clock; `now` and `mint` are parameters. remote-claude-events.mjs calls it line by line; no model is asked anything.
5
+ *
6
+ * THE PLAN is Claude Code's own to-do list, rebuilt the way Claude Code 2.1.286 rebuilds it for its own screen (read from
7
+ * its bundle, 2026-11-07): the main agent's lines only (a subagent's to-do list is its own); TaskCreate `{ subject,
8
+ * activeForm? }` is a pending item until its result says "Task #<id> created successfully" (an error drops it); TaskUpdate
9
+ * `{ taskId, status?, subject?, activeForm? }` changes one ("deleted" removes it) once its result is not an error (stricter
10
+ * than Claude Code's screen, which applies it at once: a refused update moves no bar); an update to a task never seen
11
+ * created here (a resumed session) or a list past the cap marks the plan cut, so it shows no percentage; a create or an
12
+ * update whose result never came leaves at the turn's end; when any task exists the tasks are the
13
+ * plan, otherwise the last TodoWrite `{ todos: [{ content, status, activeForm }] }` is (a list that does not parse is
14
+ * empty). Item ids are opaque and stable: a task keeps its id, a to-do item keeps the id of the same words in the version
15
+ * before. `agent.plan` is sent whole when an item, a label or a state changed, with planChange's marker.
16
+ *
17
+ * SUBAGENTS: a Task or Agent tool_use starts one (`description`, `subagent_type`); a line carrying its tool use id as
18
+ * parent_tool_use_id is its own (state working, its steps counted and sent with its subagent_id, nested when it delegates
19
+ * again); system task_started / task_progress / task_notification lines add what they report (the tokens' total, tool
20
+ * uses, duration, the end); the delegating step's result ends it: `status: "completed"` with totalTokens, usage,
21
+ * totalToolUseCount and totalDurationMs is done, `async_launched` keeps it working, an error is failed. At most
22
+ * MAX_SUBAGENTS per session; past that, and below one not tracked, nothing is drawn or attributed.
23
+ *
24
+ * TOKENS: while a turn runs, the main agent's messages' own `usage` reports summed (one count per message id, the
25
+ * highest it reported, since a message reports its output when it starts and again when it ends); the turn's result
26
+ * replaces the sum with its own total. A field never reported is null.
27
+ */
28
+ import * as P from "./remote-protocol.mjs";
29
+
30
+ const LABEL = 500;
31
+ const cut = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
32
+ const words = (v) => (typeof v === "string" && v.trim() ? cut(v.trim(), LABEL) : null);
33
+ const count = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
34
+ const STATES = new Set(["pending", "in_progress", "completed"]);
35
+ const CREATED = /^Task #(\S+) created successfully/;
36
+ export const isDelegation = (name) => name === "Task" || name === "Agent";
37
+
38
+ export const emptyProgress = () => ({
39
+ todos: null, todoIds: [], tasks: [], pending: [], updates: [], partial: false, plan: null,
40
+ subagents: {}, subagentCount: 0,
41
+ model: null, messages: {}, current: null, sessionFinal: null, lastUsage: null,
42
+ });
43
+
44
+ const copy = (ps) => ({ ...ps, todoIds: [...ps.todoIds], tasks: ps.tasks.map((t) => ({ ...t })), pending: ps.pending.map((t) => ({ ...t })), updates: ps.updates.map((u) => ({ ...u })), subagents: { ...ps.subagents }, messages: { ...ps.messages } });
45
+
46
+ // THE PLAN
47
+ const aliased = (input) => {
48
+ const a = input && typeof input === "object" && !Array.isArray(input) ? { ...input } : {};
49
+ for (const k of ["id", "task_id"]) if (!("taskId" in a) && typeof a[k] === "string" && a[k].trim()) a.taskId = a[k];
50
+ if (!("activeForm" in a) && typeof a.active_form === "string" && a.active_form.trim()) a.activeForm = a.active_form;
51
+ return a;
52
+ };
53
+ function parseTodos(input) {
54
+ const list = input?.todos;
55
+ if (!Array.isArray(list)) return [];
56
+ const ok = list.every((t) => t && typeof t.content === "string" && t.content.length > 0 && STATES.has(t.status) && typeof t.activeForm === "string" && t.activeForm.length > 0);
57
+ return ok ? list.map((t) => ({ content: t.content, status: t.status, activeForm: t.activeForm })) : [];
58
+ }
59
+
60
+ /** One main-agent tool_use block's effect on the plan. True when it was a plan tool. */
61
+ function planTool(ps, block, mint) {
62
+ const a = aliased(block.input);
63
+ if (block.name === "TaskCreate") {
64
+ if (typeof a.subject !== "string") return false;
65
+ // Past the cap the list is no longer whole: no item is added and the plan has no percentage (items_cut).
66
+ if (ps.tasks.length + ps.pending.length >= P.MAX_PLAN_ITEMS) { ps.partial = true; return true; }
67
+ ps.pending.push({ tool_use_id: block.id, item_id: mint("pli"), content: a.subject, activeForm: typeof a.activeForm === "string" ? a.activeForm : a.subject, status: "pending" });
68
+ return true;
69
+ }
70
+ if (block.name === "TaskUpdate") {
71
+ // Held until its result, like a create: an update Claude Code refused moves nothing (review 2026-11-07).
72
+ if (typeof a.taskId !== "string" || (a.status !== undefined && !STATES.has(a.status) && a.status !== "deleted") || ps.updates.length >= P.MAX_PLAN_ITEMS) return false;
73
+ ps.updates.push({ tool_use_id: block.id, taskId: a.taskId, status: a.status, subject: typeof a.subject === "string" ? a.subject : undefined, activeForm: typeof a.activeForm === "string" ? a.activeForm : undefined });
74
+ return false;
75
+ }
76
+ if (block.name === "TodoWrite") {
77
+ const todos = parseTodos(block.input);
78
+ const free = [...ps.todoIds];
79
+ ps.todoIds = todos.map((t) => {
80
+ const at = free.findIndex((f) => f.label === t.content);
81
+ return at >= 0 ? free.splice(at, 1)[0] : { label: t.content, item_id: mint("pli") };
82
+ });
83
+ ps.todos = todos.map((t, i) => ({ ...t, item_id: ps.todoIds[i].item_id }));
84
+ return true;
85
+ }
86
+ return false;
87
+ }
88
+
89
+ /** A tool_result for a pending TaskCreate: its id from Claude Code's own words, or dropped on an error. */
90
+ function planResult(ps, block, text) {
91
+ const u = ps.updates.findIndex((x) => x.tool_use_id === block.tool_use_id);
92
+ if (u >= 0) {
93
+ const [a] = ps.updates.splice(u, 1);
94
+ if (block.is_error) return false;
95
+ const at = ps.tasks.findIndex((t) => t.task_id === a.taskId);
96
+ // A task this computer never saw created (a resumed session, a restarted daemon): the list is not whole, so the
97
+ // plan says so and shows no percentage, rather than a one-item plan that is "100%".
98
+ if (at < 0) { ps.partial = true; return true; }
99
+ if (a.status === "deleted") { ps.tasks.splice(at, 1); return true; }
100
+ const was = ps.tasks[at];
101
+ ps.tasks[at] = { ...was, content: a.subject ?? was.content, activeForm: a.activeForm ?? was.activeForm, status: a.status ?? was.status };
102
+ return true;
103
+ }
104
+ const at = ps.pending.findIndex((p) => p.tool_use_id === block.tool_use_id);
105
+ if (at < 0) return false;
106
+ if (block.is_error) { ps.pending.splice(at, 1); return true; }
107
+ const task_id = CREATED.exec(text)?.[1];
108
+ if (!task_id) return false;
109
+ const [p] = ps.pending.splice(at, 1);
110
+ if (!ps.tasks.some((t) => t.task_id === task_id)) ps.tasks.push({ task_id, item_id: p.item_id, content: p.content, activeForm: p.activeForm, status: p.status });
111
+ return true;
112
+ }
113
+
114
+ /** The plan Claude Code would show now, as the protocol's items; null while it never had one. */
115
+ function planItems(ps) {
116
+ const tasks = [...ps.tasks, ...ps.pending];
117
+ const list = tasks.length > 0 ? tasks : ps.todos;
118
+ // Never a plan: nothing to send. A plan whose last item went (a failed TaskCreate, a deleted task): an empty plan, not a stale one.
119
+ if (list === null) return ps.plan ? { items: [], items_cut: false } : null;
120
+ const items = list.slice(0, P.MAX_PLAN_ITEMS).map((t) => ({ item_id: t.item_id, label: words(t.content) ?? "…", state: t.status, active: t.status === "in_progress" ? words(t.activeForm) ?? words(t.content) : null }));
121
+ return { items, items_cut: list.length > P.MAX_PLAN_ITEMS || (list !== ps.todos && ps.partial) };
122
+ }
123
+
124
+ /** The agent.plan event when the plan changed, else null; the state keeps the version sent. */
125
+ function planEvent(ps) {
126
+ const next = planItems(ps);
127
+ if (next === null) return null;
128
+ const prev = ps.plan;
129
+ if (prev && JSON.stringify(prev.items) === JSON.stringify(next.items) && prev.items_cut === next.items_cut) return null;
130
+ ps.plan = { plan_version: (prev?.plan_version ?? 0) + 1, change: P.planChange(prev, next), ...next };
131
+ return { type: "agent.plan", body: ps.plan };
132
+ }
133
+
134
+ /** The plan item a step starting now belongs to. */
135
+ export const planItemNow = (ps) => P.currentPlanItem(ps.plan)?.item_id ?? null;
136
+
137
+ // SUBAGENTS
138
+ const NO_SUB_TOKENS = { total: null, input: null, output: null, cache_read: null, cache_creation: null };
139
+ const subEvent = (r) => ({ type: "agent.subagent", body: { subagent_id: r.subagent_id, parent_id: r.parent_id, step_id: r.step_id, label: r.label, agent_type: r.agent_type, state: r.state, steps: r.steps, tokens: r.tokens, started_at: r.started_at, duration_ms: r.duration_ms } });
140
+ const final = (r) => P.isFinalSubagentState(r.state);
141
+
142
+ /** The tracked subagent a line belongs to, by its parent_tool_use_id, or null. */
143
+ export const subagentOf = (ps, parentToolUseId) => (typeof parentToolUseId === "string" ? ps.subagents[parentToolUseId] ?? null : null);
144
+
145
+ /** A Task or Agent tool_use: a new subagent, under the subagent whose line carried it. */
146
+ function delegate(ps, block, parentToolUseId, stepId, now, mint) {
147
+ const parent = parentToolUseId ? subagentOf(ps, parentToolUseId) : null;
148
+ if ((parentToolUseId && !parent) || ps.subagentCount >= P.MAX_SUBAGENTS || ps.subagents[block.id]) return null;
149
+ ps.subagentCount += 1;
150
+ const a = block.input && typeof block.input === "object" ? block.input : {};
151
+ const r = { subagent_id: mint("sag"), parent_id: parent?.subagent_id ?? null, step_id: stepId, label: words(a.description), agent_type: typeof a.subagent_type === "string" && a.subagent_type.trim() ? cut(a.subagent_type.trim(), 128) : null,
152
+ state: "started", steps: 0, tokens: NO_SUB_TOKENS, started_at: count(now), duration_ms: null };
153
+ ps.subagents[block.id] = r;
154
+ return subEvent(r);
155
+ }
156
+
157
+ function updateSub(ps, toolUseId, change) {
158
+ const r = ps.subagents[toolUseId];
159
+ if (!r || final(r)) return null;
160
+ const next = { ...r, ...change(r) };
161
+ if (JSON.stringify(next) === JSON.stringify(r)) return null;
162
+ ps.subagents[toolUseId] = next;
163
+ return subEvent(next);
164
+ }
165
+ const measured = (r, now) => (count(now) !== null && r.started_at !== null && now >= r.started_at ? now - r.started_at : null);
166
+
167
+ /** A line of the subagent's own: working, and one more step for each tool it used. */
168
+ export function subagentLine(ps, parentToolUseId, steps) {
169
+ const r = subagentOf(ps, parentToolUseId);
170
+ if (!r) return null;
171
+ return updateSub(ps, parentToolUseId, (x) => ({ state: "working", steps: x.steps + steps }));
172
+ }
173
+
174
+ /** system task_started / task_progress / task_notification. */
175
+ function taskLine(ps, line, now) {
176
+ const r = ps.subagents[line.tool_use_id];
177
+ if (!r) return null;
178
+ const u = line.usage && typeof line.usage === "object" ? line.usage : {};
179
+ const total = count(u.total_tokens), uses = count(u.tool_uses);
180
+ if (line.subtype === "task_started") return updateSub(ps, line.tool_use_id, (x) => ({ label: x.label ?? words(line.description), agent_type: x.agent_type ?? (typeof line.subagent_type === "string" && line.subagent_type.trim() ? cut(line.subagent_type.trim(), 128) : null) }));
181
+ const base = (x) => ({ tokens: total === null ? x.tokens : { ...x.tokens, total }, steps: Math.max(x.steps, uses ?? 0) });
182
+ if (line.subtype === "task_progress") return updateSub(ps, line.tool_use_id, (x) => ({ ...base(x), state: "working" }));
183
+ const state = { completed: "done", failed: "failed", stopped: "stopped", killed: "stopped" }[line.status];
184
+ if (!state) return updateSub(ps, line.tool_use_id, (x) => base(x)); // a status not known here ends nothing
185
+ return updateSub(ps, line.tool_use_id, (x) => ({ ...base(x), state, duration_ms: count(u.duration_ms) ?? measured(x, now) }));
186
+ }
187
+
188
+ /** The delegating step's own result. */
189
+ function delegationResult(ps, block, report, now) {
190
+ if (!ps.subagents[block.tool_use_id]) return null;
191
+ const rep = report && typeof report === "object" ? report : {};
192
+ if (block.is_error) return updateSub(ps, block.tool_use_id, (x) => ({ state: "failed", duration_ms: measured(x, now) }));
193
+ if (rep.status === "async_launched") return updateSub(ps, block.tool_use_id, () => ({ state: "working", background: true }));
194
+ const u = rep.usage && typeof rep.usage === "object" ? rep.usage : {};
195
+ return updateSub(ps, block.tool_use_id, (x) => ({
196
+ state: "done",
197
+ steps: Math.max(x.steps, count(rep.totalToolUseCount) ?? 0),
198
+ tokens: { total: count(rep.totalTokens) ?? x.tokens.total, input: count(u.input_tokens), output: count(u.output_tokens), cache_read: count(u.cache_read_input_tokens), cache_creation: count(u.cache_creation_input_tokens) },
199
+ duration_ms: count(rep.totalDurationMs) ?? measured(x, now),
200
+ }));
201
+ }
202
+
203
+ // TOKENS
204
+ export const tokensOf = (u) => (u && typeof u === "object" ? { input: count(u.input_tokens), output: count(u.output_tokens), cache_read: count(u.cache_read_input_tokens), cache_creation: count(u.cache_creation_input_tokens) } : null);
205
+ const higher = (a, b) => (a === null ? b : b === null ? a : Math.max(a, b));
206
+ const maxTokens = (a, b) => (a ? { input: higher(a.input, b.input), output: higher(a.output, b.output), cache_read: higher(a.cache_read, b.cache_read), cache_creation: higher(a.cache_creation, b.cache_creation) } : b);
207
+
208
+ function runningTurn(ps) {
209
+ const all = Object.values(ps.messages);
210
+ return all.length === 0 ? null : all.reduce((sum, t) => P.addTokens(sum, t));
211
+ }
212
+ function usageEvent(ps, turn, turnFinal) {
213
+ const session = ps.sessionFinal === null ? turn ?? P.NO_TOKENS : turn === null ? ps.sessionFinal : P.addTokens(ps.sessionFinal, turn);
214
+ const body = { model: ps.model, turn: turn ?? P.NO_TOKENS, turn_final: turnFinal, session };
215
+ const key = JSON.stringify(body);
216
+ if (key === ps.lastUsage) return null;
217
+ ps.lastUsage = key;
218
+ return { type: "agent.usage", body };
219
+ }
220
+
221
+ /** A main-agent message's usage report (an assistant line, or a stream_event message_start / message_delta). */
222
+ function messageUsage(ps, messageId, usage, model) {
223
+ const t = tokensOf(usage);
224
+ if (typeof model === "string" && model.trim()) ps.model = cut(model.trim(), 128);
225
+ if (!t || typeof messageId !== "string") return null;
226
+ ps.messages[messageId] = maxTokens(ps.messages[messageId] ?? null, t);
227
+ return usageEvent(ps, runningTurn(ps), false);
228
+ }
229
+
230
+ // THE ENTRY POINTS remote-claude-events.mjs CALLS
231
+
232
+ /** The turn began (system/init): the model it names; nothing is sent until a report arrives. */
233
+ export function progressInit(state, line) {
234
+ const ps = copy(state);
235
+ if (typeof line.model === "string" && line.model.trim()) ps.model = cut(line.model.trim(), 128);
236
+ // A turn before this one ended without its own total (stopped, crashed): the session's sum is no longer whole.
237
+ if (Object.keys(ps.messages).length > 0) ps.sessionFinal = P.NO_TOKENS;
238
+ ps.messages = {}; ps.current = null;
239
+ return ps;
240
+ }
241
+
242
+ /**
243
+ * The run ended another way (a stop, the agent's exit, a failed turn): every subagent not ended is `stopped`, at once,
244
+ * so the map never shows one working forever. A failed turn leaves a background subagent (async_launched) alone: its
245
+ * own notification ends it.
246
+ */
247
+ export function progressEndSubagents(state, now, { background }) {
248
+ const ps = copy(state), events = [];
249
+ for (const [key, r] of Object.entries(ps.subagents)) {
250
+ if (final(r) || (r.background && !background)) continue;
251
+ ps.subagents[key] = { ...r, state: "stopped", duration_ms: measured(r, now) };
252
+ events.push(subEvent(ps.subagents[key]));
253
+ }
254
+ return { state: ps, events };
255
+ }
256
+
257
+ /**
258
+ * One assistant line's progress: the plan tools (main agent only) and its usage (main agent only). `stepFor(block)`
259
+ * gives the step id the caller minted for a tool_use block, so a subagent names the step that delegated it.
260
+ */
261
+ export function progressAssistant(state, line, { now, mint, stepFor }) {
262
+ const ps = copy(state), events = [];
263
+ const parent = typeof line.parent_tool_use_id === "string" ? line.parent_tool_use_id : null;
264
+ let planned = false;
265
+ for (const block of line.message.content) {
266
+ if (block?.type !== "tool_use" || typeof block.id !== "string") continue;
267
+ if (!parent && planTool(ps, block, mint)) planned = true;
268
+ if (isDelegation(block.name)) { const e = delegate(ps, block, parent, stepFor(block) ?? null, now, mint); if (e) events.push(e); }
269
+ }
270
+ if (planned) { const e = planEvent(ps); if (e) events.push(e); }
271
+ if (!parent) { const e = messageUsage(ps, line.message.id, line.message.usage, line.message.model); if (e) events.push(e); }
272
+ return { state: ps, events };
273
+ }
274
+
275
+ /** One user line's tool_results: a pending task's id, a delegation's end. `textOf(block)` is the result's text. */
276
+ export function progressUser(state, line, { now, textOf }) {
277
+ const ps = copy(state), events = [];
278
+ let planned = false;
279
+ for (const block of line.message.content) {
280
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
281
+ if (!line.parent_tool_use_id && planResult(ps, block, textOf(block))) planned = true;
282
+ const e = delegationResult(ps, block, line.tool_use_result, now);
283
+ if (e) events.push(e);
284
+ }
285
+ if (planned) { const e = planEvent(ps); if (e) events.push(e); }
286
+ return { state: ps, events };
287
+ }
288
+
289
+ /** stream_event message_start / message_delta of the main agent. */
290
+ export function progressStream(state, line) {
291
+ const e = line.event ?? {};
292
+ if (line.parent_tool_use_id) return { state, events: [] };
293
+ const ps = copy(state);
294
+ if (e.type === "message_start" && e.message && typeof e.message.id === "string") {
295
+ ps.current = e.message.id;
296
+ const u = messageUsage(ps, e.message.id, e.message.usage, e.message.model);
297
+ return { state: ps, events: u ? [u] : [] };
298
+ }
299
+ if (e.type === "message_delta" && ps.current) {
300
+ const u = messageUsage(ps, ps.current, e.usage, null);
301
+ return { state: ps, events: u ? [u] : [] };
302
+ }
303
+ return { state, events: [] };
304
+ }
305
+
306
+ /** system task_* lines. */
307
+ export function progressTask(state, line, now) {
308
+ const ps = copy(state);
309
+ const e = taskLine(ps, line, now);
310
+ return { state: ps, events: e ? [e] : [] };
311
+ }
312
+
313
+ /** The turn's result: its own usage total replaces the running sum, and the session adds it. */
314
+ export function progressResult(state, line) {
315
+ const ps = copy(state);
316
+ const reported = tokensOf(line.usage);
317
+ const turn = reported ?? runningTurn(ps);
318
+ // A turn without its own total leaves the session's sum not whole: its fields are null from here on, never a part
319
+ // shown as the whole (review 2026-11-07).
320
+ if (reported === null) ps.sessionFinal = P.NO_TOKENS;
321
+ // A turn that reported no tokens at all sends no usage: nothing is not a count of zero.
322
+ const e = turn === null ? null : usageEvent(ps, turn, reported !== null);
323
+ if (reported !== null) ps.sessionFinal = ps.sessionFinal === null ? reported : P.addTokens(ps.sessionFinal, reported);
324
+ // A create or an update whose result never came did not happen as far as anyone can tell: it leaves the plan.
325
+ ps.messages = {}; ps.current = null; ps.pending = []; ps.updates = [];
326
+ const plan = planEvent(ps);
327
+ return { state: ps, events: [...(e ? [e] : []), ...(plan ? [plan] : [])] };
328
+ }