worktrust 0.10.37 → 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.
Files changed (43) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +59 -2
  3. package/SECURITY.md +25 -0
  4. package/chat-exports.mjs +20 -20
  5. package/engine-release.json +1 -1
  6. package/export-facts.mjs +71 -0
  7. package/log-session.mjs +15 -15
  8. package/package-release.json +1 -1
  9. package/package.json +36 -2
  10. package/remote-adapter-claude-code.mjs +111 -0
  11. package/remote-adapter-codex.mjs +119 -0
  12. package/remote-approval-bridge.mjs +122 -0
  13. package/remote-approvals.mjs +124 -0
  14. package/remote-attachments.mjs +129 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +325 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +205 -0
  22. package/remote-inventory.mjs +132 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-pairing.mjs +104 -0
  25. package/remote-pipeline-config.mjs +177 -0
  26. package/remote-pipeline-parsers.mjs +121 -0
  27. package/remote-pipeline.mjs +234 -0
  28. package/remote-policy.mjs +199 -0
  29. package/remote-preview.mjs +146 -0
  30. package/remote-projects.mjs +87 -0
  31. package/remote-protocol.mjs +3881 -0
  32. package/remote-qr.mjs +175 -0
  33. package/remote-release-plans.mjs +88 -0
  34. package/remote-releases.mjs +297 -0
  35. package/remote-run.mjs +174 -0
  36. package/remote-service.mjs +101 -0
  37. package/remote-session-list.mjs +25 -0
  38. package/remote-sessions.mjs +348 -0
  39. package/remote-steered.mjs +114 -0
  40. package/remote-steering.mjs +97 -0
  41. package/remote-store.mjs +123 -0
  42. package/remote-transport.mjs +88 -0
  43. package/worktrust.mjs +13 -6
@@ -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
+ }