cookbook-bridge 0.1.4 → 0.1.7

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/bridge.mjs CHANGED
@@ -30,6 +30,7 @@ import os from "node:os";
30
30
  import path from "node:path";
31
31
  import { fileURLToPath } from "node:url";
32
32
  import { spawn } from "node:child_process";
33
+ import { callsFromStreamLine, foldCallEvent, wireCalls } from "./live.mjs";
33
34
 
34
35
  // LOCAL modules load LAZILY (loadRuntime below), not statically: a Bridge with a
35
36
  // missing/corrupt module file must still be able to run `node bridge.mjs update` and
@@ -229,6 +230,19 @@ export function allowedByPolicy(cfg, agent, task) {
229
230
  }
230
231
 
231
232
 
233
+ /**
234
+ * IDENTITY PINNING for the persistent runner. spawnAgent rewrites a claude command
235
+ * with --strict-mcp-config + the agent's own Cookbook token; the thread runner
236
+ * builds its argv from agent.command directly, so without this an agent with its
237
+ * own token (Chef) ran as whoever the machine's Claude was logged in as — seen
238
+ * 2026-08-28: Chef saw diego's workspaces and "No such grant". Same rewrite, once.
239
+ */
240
+ function pinnedAgent(cfg, agent) {
241
+ if (!agent || !agent.token || !Array.isArray(agent.command)) return agent;
242
+ const { command } = withCookbookMcp(agent.command, { token: agent.token, cookbookUrl: agent.cookbookUrl ?? cfg.cookbookUrl });
243
+ return command === agent.command ? agent : { ...agent, command };
244
+ }
245
+
232
246
  /** Spawn the agent's headless CLI with the prompt substituted into its argv.
233
247
  * `env` (from agentEnv) strips vendor API-billing keys unless the user opted in —
234
248
  * a task must never silently bill an API account instead of the owner's subscription. */
@@ -370,6 +384,8 @@ function spawnAgent(agent, prompt, timeoutSeconds, env, onProgress, opts = {}) {
370
384
  // deltas. A completed turn REPLACES its partials (same text arrives both ways).
371
385
  let turnsText = "";
372
386
  let partialText = "";
387
+ // Live CALLS (show the work): tool_use/tool_result folded into a capped list.
388
+ let calls = [];
373
389
  const liveText = () => {
374
390
  const full = partialText ? `${turnsText}${turnsText ? "\n\n" : ""}${partialText}` : turnsText;
375
391
  return full.length > LIVE_TEXT_CAP ? "…" + full.slice(-LIVE_TEXT_CAP) : full;
@@ -383,7 +399,7 @@ function spawnAgent(agent, prompt, timeoutSeconds, env, onProgress, opts = {}) {
383
399
  // Bridge restarts (local retryCtx state is trimmed; the task row isn't).
384
400
  // Progress needs a token field to pass the server's substance check, so a
385
401
  // text-only tick sends output_tokens as-is (0 is fine once input>0 arrives).
386
- try { onProgress({ ...acc, runner: agent.name, ...(text ? { live_text: text } : {}), ...(sessionId ? { session_ref: sessionId } : {}) }); } catch { /* progress is best-effort */ }
402
+ try { onProgress({ ...acc, runner: agent.name, ...(text ? { live_text: text } : {}), ...(calls.length ? { live_calls: wireCalls(calls) } : {}), ...(sessionId ? { session_ref: sessionId } : {}) }); } catch { /* progress is best-effort */ }
387
403
  };
388
404
 
389
405
  let sessionId = null;
@@ -407,10 +423,14 @@ function spawnAgent(agent, prompt, timeoutSeconds, env, onProgress, opts = {}) {
407
423
  partialText = "";
408
424
  }
409
425
  }
426
+ // A tool call is a discrete event people are watching for — it jumps the
427
+ // text throttle (still ≥300ms apart so a burst of reads is one tick).
428
+ let touched = false;
429
+ for (const ev of callsFromStreamLine(line)) { calls = foldCallEvent(calls, ev); touched = true; }
410
430
  const r = foldStreamLine(line, acc);
411
431
  acc = r.acc;
412
432
  if (r.resultLine) resultLine = r.resultLine;
413
- else if (Date.now() - lastEmit > (agent.progressThrottleMs ?? 1200)) emit();
433
+ else if (Date.now() - lastEmit > (touched ? 300 : (agent.progressThrottleMs ?? 1200))) emit();
414
434
  }
415
435
  });
416
436
  child.stderr.on("data", (d) => { lastActivityAt = Date.now(); err += d; });
@@ -980,7 +1000,7 @@ async function processTask(cfg, ws, task, agent) {
980
1000
  const live = cfg.liveTokens !== false && agent.liveTokens !== false;
981
1001
  const r = warmRunner ?? runnerFor({
982
1002
  threadId: threadKey,
983
- agent,
1003
+ agent: pinnedAgent(cfg, agent),
984
1004
  env: agentEnv(cfg).env,
985
1005
  resumeSessionId: canResumeThread ? threadSession : null,
986
1006
  helpers: { fold: foldStreamLine, textFrom: textFromStreamLine, sessionFrom: sessionIdFrom },
@@ -1359,7 +1379,7 @@ async function dispatchWorkInner(cfg, work, warmHints) {
1359
1379
  if (!agent || agent.runner === "app-server" || agent.runner === "robot") continue;
1360
1380
  warmUp({
1361
1381
  poolKey: `warm::${h.workspace_id}::${agent.name}`,
1362
- agent,
1382
+ agent: pinnedAgent(cfg, agent),
1363
1383
  env: agentEnv(cfg).env,
1364
1384
  helpers: { fold: foldStreamLine, textFrom: textFromStreamLine, sessionFrom: sessionIdFrom },
1365
1385
  log,
package/codex-runner.mjs CHANGED
@@ -23,6 +23,7 @@ import os from "node:os";
23
23
  import path from "node:path";
24
24
  import fs from "node:fs";
25
25
  import { spawn } from "node:child_process";
26
+ import { codexCallEvent, foldCallEvent, wireCalls } from "./live.mjs";
26
27
 
27
28
  const IDLE_MS = 15 * 60_000;
28
29
  const LIVE_TEXT_CAP = 1800;
@@ -150,6 +151,8 @@ class CodexServer {
150
151
  t.text += m.params.delta;
151
152
  t.emit();
152
153
  }
154
+ const callEv = codexCallEvent(meth, m.params);
155
+ if (callEv) { t.calls = foldCallEvent(t.calls, callEv); t.emit(true); }
153
156
  if (m.params) {
154
157
  const u = m.params.usage ?? m.params.tokenUsage ?? m.params.token_usage ?? (m.params.turn && m.params.turn.usage);
155
158
  if (u && typeof u === "object") t.usage = u;
@@ -189,13 +192,14 @@ class CodexServer {
189
192
  const startedAt = Date.now();
190
193
  const t = {
191
194
  resolve, reject,
192
- text: "", usage: null,
195
+ text: "", usage: null, calls: [],
193
196
  lastEmit: 0, lastActivityAt: startedAt,
194
- emit: () => {
195
- if (!onProgress || Date.now() - t.lastEmit < 1200) return;
197
+ // `event` = a tool call started/finished: jumps the text throttle (≥300ms).
198
+ emit: (event = false) => {
199
+ if (!onProgress || Date.now() - t.lastEmit < (event ? 300 : 1200)) return;
196
200
  t.lastEmit = Date.now();
197
201
  const tail = t.text.length > LIVE_TEXT_CAP ? "…" + t.text.slice(-LIVE_TEXT_CAP) : t.text;
198
- try { onProgress({ input_tokens: 0, output_tokens: 0, runner: this.agent.name, ...(tail ? { live_text: tail } : {}) }); } catch { /* best-effort */ }
202
+ try { onProgress({ input_tokens: 0, output_tokens: 0, runner: this.agent.name, ...(tail ? { live_text: tail } : {}), ...(t.calls.length ? { live_calls: wireCalls(t.calls) } : {}) }); } catch { /* best-effort */ }
199
203
  },
200
204
  watchdog: setInterval(() => {
201
205
  if (Date.now() - startedAt < timeoutSeconds * 1000) return;
package/live.mjs ADDED
@@ -0,0 +1,179 @@
1
+ /**
2
+ * LIVE CALLS — "show the work, not just the words" (Diego, 2026-08-26).
3
+ *
4
+ * The Bridge already streams what an agent is SAYING (live_text). This streams what
5
+ * it is DOING: every tool call, as a short human line — `read_file notes/plan.md`,
6
+ * `bash npm test`, `search "canvas ics feed"` — with a running/ok/err state. The
7
+ * thread shows it as a work log, the stage shows the current line, the chat
8
+ * sidebar shows it under the conversation. Same progress tick, one more field.
9
+ *
10
+ * Pure parsers over the vendors' own streams (no network, no fs) so they're
11
+ * testable: claude stream-json (`tool_use` / `tool_result` blocks), gemini
12
+ * stream-json (`tool_use` / `tool_result` events), codex app-server item
13
+ * notifications (`item/started` / `item/completed`).
14
+ *
15
+ * Shape on the wire (progress.live_calls, ≤ LIVE_CALLS_CAP entries, oldest first):
16
+ * { n: "read_file", a: "notes/plan.md", s: "run" | "ok" | "err", at: <epoch ms> }
17
+ * The server re-validates every field (src/lib/workspaces/live-calls.ts).
18
+ */
19
+
20
+ import os from "node:os";
21
+ import { redact } from "./hands.mjs";
22
+
23
+ export const LIVE_CALLS_CAP = 12;
24
+ const NAME_CAP = 60;
25
+ const ARG_CAP = 120;
26
+
27
+ /** Claude Code's built-in tools → the verb a teammate would say. MCP tools keep their
28
+ * own name (`read_file`); other servers' tools are prefixed (`github:create_issue`). */
29
+ const BUILTIN = {
30
+ read: "read", edit: "edit", multiedit: "edit", write: "write", notebookedit: "edit",
31
+ bash: "bash", grep: "grep", glob: "glob", ls: "ls",
32
+ webfetch: "fetch", websearch: "search", task: "agent", todowrite: "todo",
33
+ // gemini-cli built-ins
34
+ read_file: "read", write_file: "write", replace: "edit", run_shell_command: "bash",
35
+ list_directory: "ls", search_file_content: "grep", glob_files: "glob", web_fetch: "fetch", google_web_search: "search",
36
+ };
37
+
38
+ /** Harness plumbing nobody wants in a work log (Claude Code loads deferred tool
39
+ * schemas through ToolSearch before the real call). */
40
+ const SKIP = new Set(["toolsearch"]);
41
+
42
+ export function shortTool(name) {
43
+ const raw = String(name ?? "").trim();
44
+ if (!raw) return "tool";
45
+ const m = /^mcp__([^_]+(?:_[^_]+)*)__(.+)$/.exec(raw);
46
+ if (m) {
47
+ const server = m[1].toLowerCase();
48
+ const tool = m[2];
49
+ return (server === "cookbook" ? tool : `${server}:${tool}`).slice(0, NAME_CAP);
50
+ }
51
+ const key = raw.toLowerCase();
52
+ if (BUILTIN[key]) return BUILTIN[key];
53
+ return raw.slice(0, NAME_CAP);
54
+ }
55
+
56
+ const ARG_KEYS = [
57
+ "path", "file_path", "filePath", "notebook_path", "absolute_path", "dir_path", "directory",
58
+ "command", "cmd", "query", "pattern", "url", "title", "verb", "name", "folder", "from", "to", "src", "dest",
59
+ "description", "prompt",
60
+ ];
61
+
62
+ /** One short, safe argument for the line. Paths and commands are what people want to
63
+ * see; ids and prose are last resort. Whitespace collapsed, capped. */
64
+ export function argFor(input) {
65
+ if (input == null) return "";
66
+ if (typeof input === "string") return clip(input);
67
+ if (typeof input !== "object") return clip(String(input));
68
+ for (const k of ARG_KEYS) {
69
+ const v = input[k];
70
+ if (typeof v === "string" && v.trim()) return clip(v);
71
+ if (Array.isArray(v) && v.length && typeof v[0] === "string") return clip(v.slice(0, 3).join(", "));
72
+ }
73
+ return "";
74
+ }
75
+
76
+ function clip(s) {
77
+ // Redact FIRST: a `curl -H "Authorization: Bearer …"` or an exported key must never
78
+ // reach the work log (every viewer of the thread sees it, and it persists).
79
+ const one = redact(String(s).replace(/\s+/g, " ").trim(), { home: os.homedir() });
80
+ return one.length > ARG_CAP ? one.slice(0, ARG_CAP - 1) + "…" : one;
81
+ }
82
+
83
+ /**
84
+ * Pull tool events out of one stream-json line. Returns an array (a claude turn can
85
+ * carry several tool_use blocks; a user line several tool_results), empty when the
86
+ * line is prose/usage/init. Event: {kind:'call', id, name, arg} | {kind:'result', id, err}.
87
+ */
88
+ export function callsFromStreamLine(line) {
89
+ let j;
90
+ try { j = JSON.parse(line); } catch { return []; }
91
+ if (!j || typeof j !== "object") return [];
92
+ const out = [];
93
+ // claude stream-json: assistant turn with tool_use blocks / user turn with tool_result blocks
94
+ if ((j.type === "assistant" || j.type === "user") && Array.isArray(j.message?.content)) {
95
+ for (const b of j.message.content) {
96
+ if (!b || typeof b !== "object") continue;
97
+ if (b.type === "tool_use") {
98
+ if (SKIP.has(String(b.name ?? "").toLowerCase())) continue;
99
+ out.push({ kind: "call", id: String(b.id ?? ""), name: shortTool(b.name), arg: argFor(b.input) });
100
+ } else if (b.type === "tool_result") out.push({ kind: "result", id: String(b.tool_use_id ?? ""), err: b.is_error === true });
101
+ }
102
+ return out;
103
+ }
104
+ // gemini stream-json: flat tool_use / tool_result events
105
+ if (j.type === "tool_use" && (j.tool_name || j.name)) {
106
+ out.push({ kind: "call", id: String(j.tool_id ?? j.id ?? ""), name: shortTool(j.tool_name ?? j.name), arg: argFor(j.parameters ?? j.input) });
107
+ } else if (j.type === "tool_result") {
108
+ const st = String(j.status ?? "").toLowerCase();
109
+ out.push({ kind: "result", id: String(j.tool_id ?? j.tool_use_id ?? ""), err: st === "error" || st === "failed" || j.is_error === true });
110
+ }
111
+ return out;
112
+ }
113
+
114
+ /**
115
+ * Codex app-server: `item/started` + `item/completed` notifications carry a typed
116
+ * item. Defensive about naming (camel/snake, slash/dot) — the protocol is young.
117
+ * Returns one event or null.
118
+ */
119
+ export function codexCallEvent(method, params) {
120
+ const meth = String(method ?? "");
121
+ const started = /item[/.]started$/.test(meth);
122
+ const completed = /item[/.]completed$/.test(meth);
123
+ if (!started && !completed) return null;
124
+ const item = params?.item;
125
+ if (!item || typeof item !== "object") return null;
126
+ const type = String(item.type ?? item.item_type ?? "").replace(/_([a-z])/g, (_, c) => c.toUpperCase());
127
+ const id = String(item.id ?? "");
128
+ let name = null;
129
+ let arg = "";
130
+ if (type === "commandExecution") { name = "bash"; arg = argFor(item.command ?? item.cmd); }
131
+ else if (type === "fileChange") {
132
+ name = "edit";
133
+ const ch = Array.isArray(item.changes) ? item.changes : [];
134
+ arg = clip(ch.map((c) => c?.path).filter(Boolean).slice(0, 3).join(", "));
135
+ }
136
+ else if (type === "mcpToolCall") {
137
+ const server = String(item.server ?? "").toLowerCase();
138
+ const tool = String(item.tool ?? item.name ?? "tool");
139
+ name = server && server !== "cookbook" ? `${server}:${tool}`.slice(0, NAME_CAP) : tool.slice(0, NAME_CAP);
140
+ arg = argFor(item.arguments ?? item.input ?? item.params);
141
+ }
142
+ else if (type === "webSearch") { name = "search"; arg = argFor(item.query ?? item); }
143
+ else return null; // agentMessage, reasoning, etc. are not calls
144
+ if (started) return { kind: "call", id, name, arg };
145
+ const st = String(item.status ?? "").toLowerCase();
146
+ const err = st === "failed" || st === "error" || st === "declined" || (typeof item.exit_code === "number" && item.exit_code !== 0) || (typeof item.exitCode === "number" && item.exitCode !== 0);
147
+ return { kind: "result", id, err };
148
+ }
149
+
150
+ /**
151
+ * Fold one event into the running list (pure; returns a new array). A result closes
152
+ * the matching call by id — or, when the vendor gave no id, the oldest still-running
153
+ * one. Capped to the newest LIVE_CALLS_CAP so the tick stays small.
154
+ */
155
+ export function foldCallEvent(list, ev, now = Date.now()) {
156
+ const cur = Array.isArray(list) ? list : [];
157
+ if (!ev) return cur;
158
+ if (ev.kind === "call") {
159
+ if (ev.id && cur.some((c) => c.id === ev.id)) return cur; // vendor re-emitted the same call
160
+ const next = [...cur, { id: ev.id || "", n: ev.name, a: ev.arg || "", s: "run", at: now }];
161
+ return next.length > LIVE_CALLS_CAP ? next.slice(next.length - LIVE_CALLS_CAP) : next;
162
+ }
163
+ if (ev.kind === "result") {
164
+ // Close by id; fall back to the oldest running call ONLY for id-less vendors.
165
+ // A known-but-unmatched id (e.g. a skipped ToolSearch) must not close a peer.
166
+ let i = ev.id ? cur.findIndex((c) => c.id === ev.id && c.s === "run") : -1;
167
+ if (i < 0 && !ev.id) i = cur.findIndex((c) => c.s === "run");
168
+ if (i < 0) return cur;
169
+ const next = cur.slice();
170
+ next[i] = { ...next[i], s: ev.err ? "err" : "ok" };
171
+ return next;
172
+ }
173
+ return cur;
174
+ }
175
+
176
+ /** Wire shape: drop the vendor id, keep what the UI renders. */
177
+ export function wireCalls(list) {
178
+ return (Array.isArray(list) ? list : []).map((c) => ({ n: c.n, ...(c.a ? { a: c.a } : {}), s: c.s, at: c.at }));
179
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cookbook-bridge",
3
- "version": "0.1.4",
3
+ "version": "0.1.7",
4
4
  "description": "Run your own Claude, Codex and Gemini subscriptions against your Cookbook workspaces. One approval connects every agent CLI on your machine, with a receipt for every run.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -18,6 +18,7 @@
18
18
  "device.mjs",
19
19
  "hands.mjs",
20
20
  "harden.mjs",
21
+ "live.mjs",
21
22
  "local.mjs",
22
23
  "openclaw-runner.mjs",
23
24
  "prompt.mjs",
package/thread-runner.mjs CHANGED
@@ -18,6 +18,7 @@
18
18
  * module must not import it back).
19
19
  */
20
20
  import { spawn } from "node:child_process";
21
+ import { callsFromStreamLine, foldCallEvent, wireCalls } from "./live.mjs";
21
22
 
22
23
  const IDLE_MS = 10 * 60_000;
23
24
  const runners = new Map(); // threadRootId -> Runner
@@ -91,6 +92,8 @@ class Runner {
91
92
  if (spoke.kind === "delta") t.partialText += spoke.text;
92
93
  else { t.turnsText += (t.turnsText && spoke.text ? "\n\n" : "") + spoke.text; t.partialText = ""; }
93
94
  }
95
+ let touched = false;
96
+ for (const ev of callsFromStreamLine(line)) { t.calls = foldCallEvent(t.calls, ev); touched = true; }
94
97
  const r = this.helpers.fold(line, t.acc);
95
98
  t.acc = r.acc;
96
99
  if (r.resultLine) {
@@ -100,7 +103,7 @@ class Runner {
100
103
  this.lastUsedAt = Date.now();
101
104
  t.resolve({ code: 0, out: r.resultLine, err: "", sessionId: this.sessionId });
102
105
  } else {
103
- t.emit();
106
+ t.emit(touched);
104
107
  }
105
108
  }
106
109
  }
@@ -118,15 +121,17 @@ class Runner {
118
121
  resolve, reject,
119
122
  acc: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, num_turns: 0 },
120
123
  turnsText: "", partialText: "",
124
+ calls: [], // live CALLS (bridge/live.mjs): the work log
121
125
  lastEmit: 0, lastActivityAt: startedAt,
122
- emit: () => {
123
- if (!onProgress || Date.now() - t.lastEmit < 1200) return;
126
+ // `event` = a tool call started/finished: jumps the text throttle (≥300ms).
127
+ emit: (event = false) => {
128
+ if (!onProgress || Date.now() - t.lastEmit < (event ? 300 : 1200)) return;
124
129
  t.lastEmit = Date.now();
125
130
  const full = t.partialText ? `${t.turnsText}${t.turnsText ? "\n\n" : ""}${t.partialText}` : t.turnsText;
126
131
  const live_text = full.length > 1800 ? "…" + full.slice(-1800) : full;
127
- if (t.acc.input_tokens === 0 && t.acc.output_tokens === 0 && !live_text) return;
132
+ if (t.acc.input_tokens === 0 && t.acc.output_tokens === 0 && !live_text && !t.calls.length) return;
128
133
  try {
129
- onProgress({ ...t.acc, runner: this.agent.name, ...(live_text ? { live_text } : {}), ...(this.sessionId ? { session_ref: this.sessionId } : {}) });
134
+ onProgress({ ...t.acc, runner: this.agent.name, ...(live_text ? { live_text } : {}), ...(t.calls.length ? { live_calls: wireCalls(t.calls) } : {}), ...(this.sessionId ? { session_ref: this.sessionId } : {}) });
130
135
  } catch { /* best-effort */ }
131
136
  },
132
137
  watchdog: setInterval(() => {