@nathanstephenson/flow 0.1.10-beta.2 → 0.1.10-beta.4

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 (79) hide show
  1. package/README.md +27 -1
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
  8. package/build/backend-worker.mjs +52 -116
  9. package/dist/backend/claude/background-calls.js +7 -3
  10. package/dist/backend/claude/index.js +106 -16
  11. package/dist/backend/claude/subagents.js +41 -9
  12. package/dist/backend/fake/index.js +26 -5
  13. package/dist/backend/pi/cache-warming.js +8 -0
  14. package/dist/backend/pi/canonical-json.js +120 -0
  15. package/dist/backend/pi/compaction-model.js +3 -2
  16. package/dist/backend/pi/host-auth.js +258 -0
  17. package/dist/backend/pi/index.js +38 -12
  18. package/dist/backend/pi/model-auth.js +159 -0
  19. package/dist/backend/pi/model-catalog.js +120 -0
  20. package/dist/backend/pi/model-config.js +5 -0
  21. package/dist/backend/pi/model-selection.js +32 -0
  22. package/dist/backend/pi/subagents.js +7 -3
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-subagent.js +4 -3
  25. package/dist/backend/worker/entry.js +32 -6
  26. package/dist/backend/worker/index.js +87 -7
  27. package/dist/backend/worker/rpc.js +13 -0
  28. package/dist/backend/worker/sandbox-mcp.js +18 -7
  29. package/dist/build-id +1 -1
  30. package/dist/cli/bootstrap.js +1 -1
  31. package/dist/client/reduce.js +11 -3
  32. package/dist/client/subagent-tree.js +49 -0
  33. package/dist/client/tool-summary.js +26 -15
  34. package/dist/daemon/git.js +10 -7
  35. package/dist/daemon/host.js +100 -22
  36. package/dist/daemon/models.js +2 -2
  37. package/dist/daemon/pi-model-cache.js +44 -0
  38. package/dist/daemon/runtime.js +63 -3
  39. package/dist/daemon/server.js +3 -0
  40. package/dist/daemon/store.js +2 -0
  41. package/dist/daemon/workflow-environment.js +191 -0
  42. package/dist/daemon/workflow-execution-launch.js +77 -0
  43. package/dist/daemon/workflow-execution-resources.js +76 -0
  44. package/dist/daemon/workflow-execution-values.js +128 -0
  45. package/dist/daemon/workflow-executions.js +272 -285
  46. package/dist/daemon/workflow-schedule-driver.js +247 -0
  47. package/dist/daemon/workflow-schedule-routes.js +137 -0
  48. package/dist/daemon/workflow-schedules.js +341 -0
  49. package/dist/isolation/filesystem.js +5 -1
  50. package/dist/isolation/sandbox.js +61 -18
  51. package/dist/isolation/shared-sandbox.js +3 -3
  52. package/dist/protocol/workflow-schedules.js +1 -0
  53. package/dist/tui/render.js +7 -1
  54. package/dist/workflows/calls.js +10 -7
  55. package/dist/workflows/errors.js +2 -0
  56. package/dist/workflows/executors.js +1 -1
  57. package/dist/workflows/invocations.js +8 -5
  58. package/dist/workflows/owner.js +45 -0
  59. package/dist/workflows/records.js +8 -2
  60. package/dist/workflows/schedule-errors.js +2 -0
  61. package/dist/workflows/schedule-store.js +385 -0
  62. package/dist/workflows/scheduler.js +29 -18
  63. package/dist/workflows/schedules.js +129 -0
  64. package/dist/workflows/store.js +110 -11
  65. package/package.json +8 -5
  66. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  67. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  68. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
  69. package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
  70. package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
  71. package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
  72. package/web/dist/index.html +4 -3
  73. package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
  74. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  75. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  76. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  77. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  78. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  79. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -5,7 +5,7 @@ import { dirname, join, resolve, sep } from "node:path";
5
5
  import { isSea } from "node:sea";
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { prepareFilesystemIsolation } from "../../isolation/filesystem.js";
8
- import { createSandbox, sandboxMounts, sandboxUnavailable } from "../../isolation/sandbox.js";
8
+ import { createSandbox, hostClaude, sandboxMounts, sandboxUnavailable } from "../../isolation/sandbox.js";
9
9
  import { validateFilesystemScope } from "../../isolation/filesystem.js";
10
10
  import { workflowBuilderFolder } from "../../isolation/shared-sandbox.js";
11
11
  import { nodeExecutionAssets } from "../../isolation/node-assets.js";
@@ -18,12 +18,42 @@ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "
18
18
  import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from "../session-tools.js";
19
19
  import { migrateLegacyClaudeState, prepareClaudeState, relocateClaudeState, forkClaudeState } from "./claude-state.js";
20
20
  import { relocatePiState, forkPiState } from "../pi/state.js";
21
+ import { createPiModelAuth } from "../pi/model-auth.js";
21
22
  import { recordTiming } from "../../daemon/timings.js";
22
23
  /** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
23
24
  export class WorkerBackend {
24
25
  name;
25
26
  options;
27
+ piAuth;
28
+ stopped = false;
26
29
  constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
30
+ async shutdown() {
31
+ this.stopped = true;
32
+ await this.piAuth?.close?.();
33
+ }
34
+ assertRunning() {
35
+ if (this.stopped)
36
+ throw new Error("Backend Adapter stopped");
37
+ }
38
+ scheduledSandboxMounts(scope) {
39
+ const packageRoot = fileURLToPath(new URL("../../..", import.meta.url));
40
+ const readable = [packageRoot, ...(this.options.readablePaths ?? [])];
41
+ if (this.options.entry)
42
+ readable.push(this.options.entry);
43
+ if (this.options.backendModule)
44
+ readable.push(fileURLToPath(this.options.backendModule));
45
+ readable.push(...nodeExecutionAssets(readable));
46
+ const env = { ...process.env, ...this.options.env };
47
+ const source = this.name === 'pi' ? env.PI_CODING_AGENT_DIR ?? join(homedir(), '.pi/agent')
48
+ : resolve(scope, env.CLAUDE_CONFIG_DIR || join(env.HOME ?? homedir(), '.claude'));
49
+ const resources = this.name === 'pi' ? ['AGENTS.md', 'skills', 'prompts']
50
+ : ['CLAUDE.md', 'settings.json', 'commands', 'skills', 'agents', 'rules', 'plugins'];
51
+ for (const name of resources)
52
+ if (existsSync(join(source, name)))
53
+ readable.push(realpathSync(join(source, name)));
54
+ const support = this.options.sandbox?.();
55
+ return { readable, writable: support?.supported && support.provider.claudeAuthDir ? [support.provider.claudeAuthDir] : [] };
56
+ }
27
57
  async opened(proxy, signal, isolation, begin, sandbox) {
28
58
  const opening = performance.now();
29
59
  const worker = await proxy.open(signal);
@@ -58,6 +88,18 @@ export class WorkerBackend {
58
88
  if (this.options.backendModule)
59
89
  assets.push(fileURLToPath(this.options.backendModule));
60
90
  assets.push(...nodeExecutionAssets(assets));
91
+ let claudePath = support.provider.claudePath;
92
+ if (support.provider.hostClaudePath && (shared || this.name === "claude")) {
93
+ let host;
94
+ try {
95
+ host = hostClaude(support.provider.hostClaudePath);
96
+ }
97
+ catch (error) {
98
+ throw new Error(`${sandboxUnavailable().message}: ${error.message}`);
99
+ }
100
+ claudePath = host.executable;
101
+ assets.push(host.directory);
102
+ }
61
103
  const env = { FLOW_BACKEND_WORKER: "1",
62
104
  ...Object.fromEntries(Object.entries(this.options.env ?? {}).filter((entry) => entry[1] !== undefined)) };
63
105
  const cleanups = [];
@@ -68,10 +110,13 @@ export class WorkerBackend {
68
110
  env.CLAUDE_CONFIG_DIR = claude.env.CLAUDE_CONFIG_DIR;
69
111
  if (claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR)
70
112
  env.CLAUDE_SECURESTORAGE_CONFIG_DIR = claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
71
- env.FLOW_CLAUDE_PATH = support.provider.claudePath;
113
+ if (claudePath)
114
+ env.FLOW_CLAUDE_PATH = claudePath;
115
+ if (support.provider.hostClaudePath)
116
+ env.DISABLE_AUTOUPDATER = "1";
72
117
  for (const entry of readdirSync(env.CLAUDE_CONFIG_DIR)) {
73
118
  const link = join(env.CLAUDE_CONFIG_DIR, entry);
74
- if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && entry !== "projects")
119
+ if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && !["projects", "file-history"].includes(entry))
75
120
  assets.push(realpathSync(link));
76
121
  }
77
122
  }
@@ -81,7 +126,7 @@ export class WorkerBackend {
81
126
  rmSync(agent, { recursive: true, force: true });
82
127
  mkdirSync(agent, { recursive: true, mode: 0o700 });
83
128
  cleanups.push(() => rmSync(agent, { recursive: true, force: true }));
84
- for (const name of ["auth.json", "models.json", "settings.json"]) {
129
+ for (const name of ["models.json", "settings.json"]) {
85
130
  if (existsSync(join(source, name)))
86
131
  copyFileSync(join(source, name), join(agent, name));
87
132
  }
@@ -121,6 +166,7 @@ export class WorkerBackend {
121
166
  ({ startup } = sandbox);
122
167
  cleanups.push(() => { removed = sandbox.close().catch((error) => console.error(`Sandbox ${sandbox.name} removal failed: ${error.message}`)); });
123
168
  }
169
+ this.assertRunning();
124
170
  const launch = sandbox.command(scope, [support.provider.nodePath, ...plan.args], env);
125
171
  proxy = new WorkerSession({ ...options, scope, stateDir }, { ...this.options, sandboxed: sandbox, startupTimeoutMs: this.options.startupTimeoutMs ?? 300_000, command: launch.command, args: launch.args, env: {} }, cleanup);
126
172
  await this.opened(proxy, options.signal, "sandbox", begin, { sharing: shared ? "shared" : "own", remove: Math.round(startup.remove), create: Math.round(startup.create) });
@@ -144,9 +190,15 @@ export class WorkerBackend {
144
190
  return this.name === "claude" ? forkClaudeState(from, to) : forkPiState(from.stateDir, to.stateDir, to.scope);
145
191
  }
146
192
  async create(options) {
193
+ this.assertRunning();
147
194
  const begin = performance.now();
148
195
  options.signal?.throwIfAborted();
149
- const isolationMode = this.options.isolationMode?.() ?? "bubblewrap";
196
+ if (this.name === 'pi' && !this.options.backendModule && !options.piAuth) {
197
+ const directory = this.options.env?.PI_CODING_AGENT_DIR;
198
+ this.piAuth ??= createPiModelAuth(directory ? { authPath: join(directory, 'auth.json') } : {});
199
+ options = { ...options, piAuth: this.piAuth };
200
+ }
201
+ const isolationMode = options.isolationMode ?? this.options.isolationMode?.() ?? "bubblewrap";
150
202
  if (isolationMode === "sandbox")
151
203
  return this.createSandboxed(options);
152
204
  if (isolationMode === "none") {
@@ -191,6 +243,7 @@ export class WorkerBackend {
191
243
  env: this.options.env ?? {}, credentials: this.name, workflowBuilder: !!options.workflowBuilder, worker: true, readablePaths: assets });
192
244
  let proxy;
193
245
  try {
246
+ this.assertRunning();
194
247
  options.signal?.throwIfAborted();
195
248
  if (this.name === "claude")
196
249
  migrateLegacyClaudeState(options.stateDir, { ...process.env, ...this.options.env }, isolation.scope, options.resume);
@@ -214,6 +267,7 @@ class WorkerSession {
214
267
  worker;
215
268
  rpc;
216
269
  failed;
270
+ piAuthProviders = new Set();
217
271
  disposing = false;
218
272
  disposal;
219
273
  workflows = new Map();
@@ -241,11 +295,25 @@ class WorkerSession {
241
295
  if (this.disposing || this.failed)
242
296
  throw new Error("Backend Session stopped");
243
297
  // Builders never inherit other host capabilities, even if the worker asks directly.
244
- if (this.options.workflowBuilder && !["workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
298
+ if (this.options.workflowBuilder && !["pi.auth.snapshot", "pi.auth.resolve", "workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
245
299
  throw new Error("Host capability is not enabled for workflow builder");
246
300
  }
247
301
  // Never look up host functions by a worker-supplied property name.
248
302
  switch (method) {
303
+ case 'pi.auth.snapshot': return this.snapshotPiAuth(signal);
304
+ case 'pi.auth.resolve': {
305
+ const auth = this.requirePiAuth();
306
+ const provider = args[0];
307
+ if (typeof provider !== 'string' || !this.piAuthProviders.has(provider))
308
+ throw new Error('Unknown Pi provider');
309
+ try {
310
+ return await auth.resolve(provider, signal);
311
+ }
312
+ catch {
313
+ signal.throwIfAborted();
314
+ throw new Error(`Pi authentication failed for ${provider}. Check sign-in and auth.json access. Move any !command credentials to models.json.`);
315
+ }
316
+ }
249
317
  case "mcp.token": {
250
318
  if (!(this.options.mcp instanceof SandboxMcpSession) || typeof args[0] !== "string")
251
319
  throw new Error("Host capability is not enabled");
@@ -282,6 +350,16 @@ class WorkerSession {
282
350
  child.stdout?.once("close", () => this.fail(new Error("Backend worker disconnected")));
283
351
  child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
284
352
  }
353
+ requirePiAuth() {
354
+ if ((this.launchOptions.backend ?? 'pi') !== 'pi' || !this.options.piAuth)
355
+ throw new Error('Pi auth is not enabled');
356
+ return this.options.piAuth;
357
+ }
358
+ async snapshotPiAuth(signal) {
359
+ const metadata = await this.requirePiAuth().snapshot(signal);
360
+ this.piAuthProviders = new Set(metadata.map(({ providerId }) => providerId));
361
+ return metadata;
362
+ }
285
363
  requireWorkflowBuilder(input) {
286
364
  if (!this.options.workflowBuilder)
287
365
  throw new Error("Workflow builder tools are not enabled");
@@ -300,7 +378,7 @@ class WorkerSession {
300
378
  return this.options.sessionTools;
301
379
  }
302
380
  async open(signal) {
303
- const { emit: _emit, onFailure: _onFailure, signal: _signal, evict: _evict, mcp, workflow, workflowBuilder, sessionTools, ...options } = this.options;
381
+ const { emit: _emit, onFailure: _onFailure, signal: _signal, evict: _evict, mcp, workflow, workflowBuilder, sessionTools, piAuth, ...options } = this.options;
304
382
  const controller = new AbortController();
305
383
  const cancel = () => controller.abort(signal?.reason);
306
384
  if (signal?.aborted)
@@ -309,7 +387,9 @@ class WorkerSession {
309
387
  signal?.addEventListener('abort', cancel, { once: true });
310
388
  const timer = setTimeout(() => controller.abort(), this.launchOptions.startupTimeoutMs ?? 60_000);
311
389
  try {
390
+ const auth = piAuth ? await this.snapshotPiAuth(controller.signal) : undefined;
312
391
  const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
392
+ ...(auth ? { piAuth: auth } : {}),
313
393
  workflowEnabled: !workflowBuilder && !!workflow,
314
394
  sessionToolsEnabled: !workflowBuilder && options.tools !== "none" && !!sessionTools,
315
395
  ...(workflowBuilder ? { workflowBuilderInstructions: workflowBuilder.instructions }
@@ -1,4 +1,17 @@
1
1
  import { AutoPermissionUnavailable } from "../permission-errors.js";
2
+ export function waitForAbort(work, signal) {
3
+ if (!signal)
4
+ return work;
5
+ return new Promise((resolve, reject) => {
6
+ const abort = () => { reject(signal.reason); };
7
+ signal.addEventListener("abort", abort, { once: true });
8
+ void work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
9
+ if (signal.aborted) {
10
+ signal.removeEventListener("abort", abort);
11
+ abort();
12
+ }
13
+ });
14
+ }
2
15
  export function errorText(error) {
3
16
  return error instanceof Error ? error.message : String(error);
4
17
  }
@@ -1,5 +1,6 @@
1
1
  import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
2
2
  import { McpSession } from "../mcp.js";
3
+ import { waitForAbort } from "./rpc.js";
3
4
  /** Host stand-in for MCP clients that run in a sandbox worker (ADR 0033). The host keeps
4
5
  * definitions, OAuth and status; the worker owns the clients and their tool calls. */
5
6
  export class SandboxMcpSession extends McpSession {
@@ -49,12 +50,14 @@ export class SandboxMcpSession extends McpSession {
49
50
  await this.attached;
50
51
  this.cached = await this.worker("mcp.retry", [id]);
51
52
  }
52
- async directView(connectionId) {
53
+ async directView(connectionId, signal) {
54
+ signal?.throwIfAborted();
53
55
  const connection = this.connections.find((entry) => entry.id === connectionId);
54
56
  if (!connection)
55
57
  throw new Error("MCP connection is not selected for this Agent Session");
56
- await this.attached;
57
- return new SandboxDirectMcpSession(connection, this.root, this.worker);
58
+ await waitForAbort(this.attached, signal);
59
+ signal?.throwIfAborted();
60
+ return new SandboxDirectMcpSession(connection, this.root, this.worker, signal);
58
61
  }
59
62
  status() { return this.cached.map((state) => ({ ...state })); }
60
63
  tools() { return []; }
@@ -67,20 +70,28 @@ class SandboxDirectMcpSession extends McpSession {
67
70
  connectionId;
68
71
  state;
69
72
  listed = [];
70
- constructor(connection, scope, worker) {
73
+ lifetime = new AbortController();
74
+ signal;
75
+ constructor(connection, scope, worker, signal) {
71
76
  super([connection], scope);
72
77
  this.worker = worker;
78
+ this.signal = signal ? AbortSignal.any([signal, this.lifetime.signal]) : this.lifetime.signal;
73
79
  this.connectionId = connection.id;
74
80
  this.state = { id: connection.id, state: "connecting", tools: 0 };
75
81
  }
76
82
  async open() {
77
- const result = await this.worker("mcp.direct", [this.connectionId]);
83
+ this.signal.throwIfAborted();
84
+ const result = await this.worker("mcp.direct", [this.connectionId], this.signal);
85
+ this.signal.throwIfAborted();
78
86
  this.state = result.status;
79
87
  this.listed = result.tools.map((tool) => ({ ...tool,
80
- call: (input, signal, timeoutMs) => this.worker("mcp.callTool", [tool.name, input, timeoutMs], signal) }));
88
+ call: (input, signal, timeoutMs) => this.worker("mcp.callTool", [tool.name, input, timeoutMs], signal ? AbortSignal.any([signal, this.signal]) : this.signal) }));
81
89
  }
82
90
  async retry() { await this.open(); }
83
91
  status() { return [{ ...this.state }]; }
84
92
  tools() { return this.listed; }
85
- async dispose() { }
93
+ async dispose() {
94
+ this.lifetime.abort(new Error("MCP view stopped"));
95
+ this.listed = [];
96
+ }
86
97
  }
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- e9c6e6fa-3f7d-464d-8713-d6bc95e7391c
1
+ f94da56f-258e-42d7-900e-3933fca5ee5e
@@ -889,7 +889,7 @@ async function bootstrap() {
889
889
  if (!managed) throw new Error("Missing systemd update configuration");
890
890
  await assertSystemdOwner(managed, managed.updater, process.pid);
891
891
  }
892
- const lease = await install.register("e9c6e6fa-3f7d-464d-8713-d6bc95e7391c", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
892
+ const lease = await install.register("f94da56f-258e-42d7-900e-3933fca5ee5e", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
893
893
  delete process.env.FLOW_UPDATE_CAPABILITY;
894
894
  process.on("exit", lease.release);
895
895
  if (args[0] === "update") {
@@ -45,7 +45,7 @@ export function reduceAll(entries, from = initialState()) {
45
45
  function stampTurnEnd(entries, at) {
46
46
  for (let index = entries.length - 1; index >= 0; index--) {
47
47
  const entry = entries[index];
48
- if (entry.kind === "user")
48
+ if (entry.kind === "user" && entry.producer === undefined)
49
49
  return entries;
50
50
  if (entry.kind === "assistant" && entry.producer === undefined) {
51
51
  if (entry.endedAt === at)
@@ -114,11 +114,15 @@ function applyEvent(state, event, at) {
114
114
  entries: upsert(state.entries, {
115
115
  kind: "user",
116
116
  id: event.id,
117
- text: event.text,
117
+ ...(event.fromSessionId === undefined
118
+ ? { text: event.text }
119
+ : { text: event.text.slice(event.text.indexOf("\n") + 1), fromSessionId: event.fromSessionId }),
118
120
  ...(event.attachments === undefined ? {} : { attachments: event.attachments }),
119
121
  at,
120
122
  }),
121
123
  };
124
+ case "subagent_instruction":
125
+ return { ...state, entries: upsert(state.entries, { kind: "user", id: event.id, text: event.text, producer: event.producer, at }) };
122
126
  case "turn_started":
123
127
  return { ...state, turnInFlight: true };
124
128
  case "message":
@@ -184,6 +188,9 @@ function applyEvent(state, event, at) {
184
188
  id: event.subagentId,
185
189
  name: event.name,
186
190
  ...(event.description === undefined ? {} : { description: event.description }),
191
+ ...(event.model === undefined ? {} : { model: event.model }),
192
+ ...(event.effort === undefined ? {} : { effort: event.effort }),
193
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
187
194
  status: event.state,
188
195
  // Only ever set alongside "waiting", so a Subagent that resumes drops it rather than
189
196
  // carrying a stale object it is no longer waiting on.
@@ -335,7 +342,8 @@ function applyEvent(state, event, at) {
335
342
  case "notice":
336
343
  return {
337
344
  ...state,
338
- entries: [...state.entries, { kind: "notice", id: `notice-${state.entries.length}`, level: event.level, text: event.text }],
345
+ entries: [...state.entries, { kind: "notice", id: `notice-${state.entries.length}`, level: event.level, text: event.text,
346
+ ...(event.sessionId === undefined ? {} : { sessionId: event.sessionId }) }],
339
347
  };
340
348
  case "compacting":
341
349
  // Absent rather than `false`, so Chrome's identity comparison sees the same value it saw
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Which Subagent spawned which, read from `producer` on each Subagent Entry.
3
+ *
4
+ * The transcript stays flat (ADR 0015), so the tree exists only here, built over keys at paint time.
5
+ * DOM-free so the web client and the TUI share one rule.
6
+ */
7
+ const SUBAGENT_PREFIX = "subagent:";
8
+ /** The key of the Entry a Subagent's own row uses, given the id its rows are attributed to. */
9
+ export function subagentKey(subagentId) {
10
+ return `${SUBAGENT_PREFIX}${subagentId}`;
11
+ }
12
+ /** The Subagent a row belongs to, or undefined for the Agent Session's own work. */
13
+ export function producerKey(entry) {
14
+ return "producer" in entry && entry.producer ? subagentKey(entry.producer.subagentId) : undefined;
15
+ }
16
+ /**
17
+ * Every Subagent key mapped to its parent's key, undefined at the root.
18
+ *
19
+ * A parent missing from the transcript maps to the root, so a row is never lost.
20
+ */
21
+ export function subagentParents(keys, getEntry) {
22
+ const subagents = keys.filter((key) => key.startsWith(SUBAGENT_PREFIX) && getEntry(key)?.kind === "subagent");
23
+ const known = new Set(subagents);
24
+ return new Map(subagents.map((key) => {
25
+ const parent = producerKey(getEntry(key));
26
+ return [key, parent !== undefined && known.has(parent) ? parent : undefined];
27
+ }));
28
+ }
29
+ /** How many Subagents are in the chain from `key` up to the root, `key` included. 0 for the Agent Session. */
30
+ export function depthOf(parents, key) {
31
+ let depth = 0;
32
+ const seen = new Set();
33
+ for (let at = key; at !== undefined && !seen.has(at); at = parents.get(at)) {
34
+ seen.add(at);
35
+ if (parents.has(at))
36
+ depth++;
37
+ }
38
+ return depth;
39
+ }
40
+ /** Whether `key` is `ancestor` or sits anywhere below it. */
41
+ export function isWithin(parents, key, ancestor) {
42
+ const seen = new Set();
43
+ for (let at = key; at !== undefined && !seen.has(at); at = parents.get(at)) {
44
+ if (at === ancestor)
45
+ return true;
46
+ seen.add(at);
47
+ }
48
+ return false;
49
+ }
@@ -13,17 +13,18 @@
13
13
  const MAX = 60;
14
14
  /**
15
15
  * Ordered, because a tool's input usually carries several of these and the first is the one the
16
- * question is about: a Bash call's `command` before its `description`, a Grep's `pattern` before the
17
- * directory it searched.
16
+ * question is about: the `description` a model wrote for a call before the `command` or `prompt` it
17
+ * describes, a Grep's `pattern` before the directory it searched.
18
18
  *
19
19
  * Keyed on the shape of the arguments rather than on the tool's name, because the name is the part
20
20
  * that varies: Claude's `Edit` and a pi tool that edits a file are not called the same thing, while
21
21
  * `file_path` means the same in both. An unrecognised tool with a recognisable argument still reads.
22
22
  */
23
23
  const ARGUMENTS = [
24
+ { key: "description", shape: "text" },
24
25
  { key: "command", shape: "text" },
25
- // Ahead of `description` and `prompt`, which an AskUserQuestion call does not carry but a future
26
- // asking tool might. Keyed on the argument rather than the tool's name, which is this list's rule.
26
+ // Ahead of `prompt`, which an AskUserQuestion call does not carry but a future asking tool might.
27
+ // Keyed on the argument rather than the tool's name, which is this list's rule.
27
28
  { key: "questions", shape: "questions" },
28
29
  { key: "file_path", shape: "path" },
29
30
  { key: "notebook_path", shape: "path" },
@@ -31,36 +32,46 @@ const ARGUMENTS = [
31
32
  { key: "url", shape: "text" },
32
33
  { key: "query", shape: "text" },
33
34
  { key: "path", shape: "path" },
34
- { key: "description", shape: "text" },
35
35
  { key: "prompt", shape: "text" },
36
36
  ];
37
+ const MAIN_ARGUMENTS = ARGUMENTS.filter(({ key }) => key !== "description");
37
38
  /**
38
39
  * Returns undefined when there is nothing worth saying, so a caller renders the tool's name alone
39
40
  * rather than a padded blank. `input` is `unknown` on the wire (`events.ts` — a Backend Adapter
40
41
  * passes its backend's arguments through), so every access is narrowed rather than trusted.
41
42
  */
42
43
  export function toolSummary(input) {
44
+ return summarise(input, MAX);
45
+ }
46
+ /**
47
+ * The first argument after `description`, unclipped — the command or prompt the description
48
+ * stands for — for a card that has room to wrap it.
49
+ */
50
+ export function fullToolSummary(input) {
51
+ return summarise(input, Infinity, MAIN_ARGUMENTS);
52
+ }
53
+ function summarise(input, max, args = ARGUMENTS) {
43
54
  if (!input || typeof input !== "object")
44
55
  return undefined;
45
56
  const record = input;
46
- for (const argument of ARGUMENTS) {
57
+ for (const argument of args) {
47
58
  const value = record[argument.key];
48
59
  if (argument.shape === "questions") {
49
- const asked = clipQuestions(value);
60
+ const asked = clipQuestions(value, max);
50
61
  if (asked !== undefined)
51
62
  return asked;
52
63
  continue;
53
64
  }
54
65
  if (typeof value !== "string" || value.trim() === "")
55
66
  continue;
56
- return argument.shape === "path" ? clipPath(value.trim()) : clipText(value);
67
+ return argument.shape === "path" ? clipPath(value.trim(), max) : clipText(value, max);
57
68
  }
58
69
  // The fallback: a tool nobody here has heard of, whose input is a single string, is describing
59
70
  // itself with that string. Two or more and there is no way to know which one matters, so say
60
71
  // nothing rather than pick.
61
72
  const strings = Object.values(record).filter((value) => typeof value === "string");
62
73
  const only = strings.length === 1 ? strings[0] : undefined;
63
- return only && only.trim() !== "" ? clipText(only) : undefined;
74
+ return only && only.trim() !== "" ? clipText(only, max) : undefined;
64
75
  }
65
76
  /**
66
77
  * The first question asked, and how many others came with it.
@@ -72,7 +83,7 @@ export function toolSummary(input) {
72
83
  * The front-ends suppress this row where an Enquiry Entry stands beside it, so what this actually
73
84
  * serves is the case where one does not: a Subagent's Enquiry, seen from the Agents tab.
74
85
  */
75
- function clipQuestions(value) {
86
+ function clipQuestions(value, max) {
76
87
  if (!Array.isArray(value) || value.length === 0)
77
88
  return undefined;
78
89
  const first = value[0];
@@ -84,15 +95,15 @@ function clipQuestions(value) {
84
95
  const rest = value.length - 1;
85
96
  // Clipped after the count is appended, not before, so the whole précis obeys MAX rather than
86
97
  // MAX-plus-however-long-the-suffix-turned-out-to-be.
87
- return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked);
98
+ return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked, max);
88
99
  }
89
100
  /** Whitespace collapsed so a heredoc or a multi-line prompt still occupies one line. */
90
- function clipText(value) {
101
+ function clipText(value, max) {
91
102
  const text = value.replace(/\s+/g, " ").trim();
92
- return text.length <= MAX ? text : `${text.slice(0, MAX - 1)}…`;
103
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
93
104
  }
94
- function clipPath(path) {
105
+ function clipPath(path, max) {
95
106
  // The tail of a path is what identifies the file; the leading directories are what a reader can
96
107
  // afford to lose, which is the opposite of how everything else here truncates.
97
- return path.length <= MAX ? path : `…${path.slice(-(MAX - 1))}`;
108
+ return path.length <= max ? path : `…${path.slice(-(max - 1))}`;
98
109
  }
@@ -297,14 +297,17 @@ export async function createWorktree(options) {
297
297
  return added;
298
298
  return { ok: true, value: planned.value };
299
299
  }
300
- export async function removeMergedBranch(repo, branch) {
301
- const target = await head(repo);
302
- if (!target.ok)
303
- return target;
304
- if (target.value.detached)
305
- return refuse(`delete refs/heads/${branch}`, "The source repository has a detached HEAD");
300
+ export async function removeMergedBranch(repo, branch, from) {
301
+ if (from === undefined) {
302
+ const target = await head(repo);
303
+ if (!target.ok)
304
+ return target;
305
+ if (target.value.detached)
306
+ return refuse(`delete refs/heads/${branch}`, "The source repository has a detached HEAD");
307
+ from = target.value.name;
308
+ }
306
309
  const branchRef = `refs/heads/${branch}`;
307
- const targetRef = `refs/heads/${target.value.name}`;
310
+ const targetRef = `refs/heads/${from}`;
308
311
  const merged = await run(repo, ["merge-base", "--is-ancestor", branchRef, targetRef], GIT_READ_TIMEOUT_MS);
309
312
  if (!merged.ok)
310
313
  return merged;