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

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 (60) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{claude-COCNALN2.mjs → claude-6L5KCQWJ.mjs} +63 -15
  3. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-QNU2YE4G.mjs} +10 -10
  4. package/build/backend-worker.mjs +42 -5
  5. package/dist/backend/claude/background-calls.js +7 -3
  6. package/dist/backend/claude/index.js +37 -5
  7. package/dist/backend/claude/subagents.js +30 -9
  8. package/dist/backend/fake/index.js +20 -5
  9. package/dist/backend/pi/index.js +1 -0
  10. package/dist/backend/pi/subagents.js +7 -3
  11. package/dist/backend/worker/entry.js +19 -5
  12. package/dist/backend/worker/index.js +21 -2
  13. package/dist/backend/worker/rpc.js +13 -0
  14. package/dist/backend/worker/sandbox-mcp.js +18 -7
  15. package/dist/build-id +1 -1
  16. package/dist/cli/bootstrap.js +1 -1
  17. package/dist/client/reduce.js +9 -3
  18. package/dist/client/subagent-tree.js +49 -0
  19. package/dist/daemon/git.js +10 -7
  20. package/dist/daemon/host.js +88 -21
  21. package/dist/daemon/runtime.js +63 -3
  22. package/dist/daemon/server.js +3 -0
  23. package/dist/daemon/store.js +2 -0
  24. package/dist/daemon/workflow-environment.js +191 -0
  25. package/dist/daemon/workflow-execution-launch.js +77 -0
  26. package/dist/daemon/workflow-execution-resources.js +76 -0
  27. package/dist/daemon/workflow-execution-values.js +128 -0
  28. package/dist/daemon/workflow-executions.js +272 -285
  29. package/dist/daemon/workflow-schedule-driver.js +247 -0
  30. package/dist/daemon/workflow-schedule-routes.js +137 -0
  31. package/dist/daemon/workflow-schedules.js +341 -0
  32. package/dist/isolation/sandbox.js +30 -14
  33. package/dist/isolation/shared-sandbox.js +3 -3
  34. package/dist/protocol/workflow-schedules.js +1 -0
  35. package/dist/tui/render.js +7 -1
  36. package/dist/workflows/calls.js +10 -7
  37. package/dist/workflows/errors.js +2 -0
  38. package/dist/workflows/executors.js +1 -1
  39. package/dist/workflows/invocations.js +8 -5
  40. package/dist/workflows/owner.js +45 -0
  41. package/dist/workflows/records.js +8 -2
  42. package/dist/workflows/schedule-errors.js +2 -0
  43. package/dist/workflows/schedule-store.js +385 -0
  44. package/dist/workflows/scheduler.js +29 -18
  45. package/dist/workflows/schedules.js +129 -0
  46. package/dist/workflows/store.js +110 -11
  47. package/package.json +2 -1
  48. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  49. package/web/dist/assets/index-Miy2nveb.js +40 -0
  50. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-Vf_fCXyE.js} +1 -1
  51. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  52. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  53. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  54. package/web/dist/index.html +4 -3
  55. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  56. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  57. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  58. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  59. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  60. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -1,6 +1,7 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import { EFFORT_ORDER } from "../effort.js";
4
+ import { callIdFor } from "./work.js";
4
5
  export const SUBAGENT_TOOL = "subagent";
5
6
  const parameters = Type.Object({
6
7
  description: Type.String({ minLength: 1, description: "Short description of the delegated work" }),
@@ -10,14 +11,17 @@ const parameters = Type.Object({
10
11
  effort: Type.Optional(Type.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
11
12
  run_in_background: Type.Optional(Type.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." })),
12
13
  });
13
- export function subagentTool(work, run) {
14
+ export function subagentTool(work, run, producer) {
14
15
  return defineTool({
15
16
  name: SUBAGENT_TOOL,
16
17
  label: "Subagent",
17
18
  description: "Delegate work to a Subagent with its own Conversation Context. Subagents run in the background by default and report back automatically. Multiple Subagents may run concurrently. They cannot ask the human or create further Subagents.",
18
19
  promptSnippet: "Delegate independent work to Subagents",
19
20
  parameters,
20
- execute: async (id, input, signal) => work.run({ type: "subagent", subagentId: id,
21
- name: input.name ?? "Subagent", description: input.description }, (childSignal) => run(id, input, childSignal), input.run_in_background !== false, signal),
21
+ execute: async (id, input, signal) => {
22
+ const subagentId = callIdFor(id, producer);
23
+ return work.run({ type: "subagent", subagentId, name: input.name ?? "Subagent", description: input.description,
24
+ ...(producer ? { producer } : {}) }, (childSignal) => run(subagentId, input, childSignal), input.run_in_background !== false, signal);
25
+ },
22
26
  });
23
27
  }
@@ -7,7 +7,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  return path;
8
8
  };
9
9
  import { McpSession } from "../mcp.js";
10
- import { WorkerRpc, errorText } from "./rpc.js";
10
+ import { WorkerRpc, errorText, waitForAbort } from "./rpc.js";
11
11
  import { snapshot } from "./protocol.js";
12
12
  import { killWorkerTree } from "./launcher.js";
13
13
  import { encodeFrame, frameDecoder } from "./frames.js";
@@ -43,6 +43,16 @@ export function runWorker() {
43
43
  void stop(); });
44
44
  };
45
45
  const rpc = new WorkerRpc(send, async (method, args, signal) => {
46
+ if (method === "mcp.initialize") {
47
+ signal.throwIfAborted();
48
+ if (creating || closing)
49
+ throw new Error('Worker already initialized');
50
+ creating = true;
51
+ const options = args[0];
52
+ localMcp = new McpSession(options.connections, options.scope, undefined, true, undefined, undefined, undefined, 'none', undefined, (connectionId, refresh) => rpc.call('mcp.token', [connectionId, refresh]));
53
+ localMcp.connectTimeoutMs = 120_000;
54
+ return;
55
+ }
46
56
  if (method === "create") {
47
57
  const ready = performance.now();
48
58
  if (creating || closing)
@@ -116,8 +126,8 @@ export function runWorker() {
116
126
  setImmediate(() => process.stdout.end(() => process.exit(0)));
117
127
  return;
118
128
  }
119
- if (!session || closing)
120
- throw new Error("Backend worker is not running");
129
+ if (closing || (!session && (!localMcp || !method.startsWith('mcp.'))))
130
+ throw new Error("Worker is not running");
121
131
  let result;
122
132
  switch (method) {
123
133
  case "prompt":
@@ -181,14 +191,17 @@ export function runWorker() {
181
191
  case "mcp.direct": {
182
192
  if (!localMcp)
183
193
  throw new Error("No sandbox MCP clients");
194
+ signal.throwIfAborted();
184
195
  const id = args[0];
185
196
  if (localMcp.status().find((state) => state.id === id)?.state !== "connected")
186
- await localMcp.retry(id).catch(() => { });
197
+ await waitForAbort(localMcp.retry(id).catch(() => { }), signal);
198
+ signal.throwIfAborted();
187
199
  result = { status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
188
200
  tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool) };
189
201
  break;
190
202
  }
191
203
  case "mcp.callTool": {
204
+ signal.throwIfAborted();
192
205
  const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
193
206
  if (!tool)
194
207
  throw new Error("Unknown MCP tool");
@@ -217,7 +230,8 @@ export function runWorker() {
217
230
  break;
218
231
  default: throw new Error(`Unknown worker method: ${method}`);
219
232
  }
220
- rpc.notify("snapshot", publishSnapshot());
233
+ if (session)
234
+ rpc.notify("snapshot", publishSnapshot());
221
235
  return result;
222
236
  }, () => { });
223
237
  function updateTools(metadata) {
@@ -24,6 +24,25 @@ export class WorkerBackend {
24
24
  name;
25
25
  options;
26
26
  constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
27
+ scheduledSandboxMounts(scope) {
28
+ const packageRoot = fileURLToPath(new URL("../../..", import.meta.url));
29
+ const readable = [packageRoot, ...(this.options.readablePaths ?? [])];
30
+ if (this.options.entry)
31
+ readable.push(this.options.entry);
32
+ if (this.options.backendModule)
33
+ readable.push(fileURLToPath(this.options.backendModule));
34
+ readable.push(...nodeExecutionAssets(readable));
35
+ const env = { ...process.env, ...this.options.env };
36
+ const source = this.name === 'pi' ? env.PI_CODING_AGENT_DIR ?? join(homedir(), '.pi/agent')
37
+ : resolve(scope, env.CLAUDE_CONFIG_DIR || join(env.HOME ?? homedir(), '.claude'));
38
+ const resources = this.name === 'pi' ? ['AGENTS.md', 'skills', 'prompts']
39
+ : ['CLAUDE.md', 'settings.json', 'commands', 'skills', 'agents', 'rules', 'plugins'];
40
+ for (const name of resources)
41
+ if (existsSync(join(source, name)))
42
+ readable.push(realpathSync(join(source, name)));
43
+ const support = this.options.sandbox?.();
44
+ return { readable, writable: support?.supported && support.provider.claudeAuthDir ? [support.provider.claudeAuthDir] : [] };
45
+ }
27
46
  async opened(proxy, signal, isolation, begin, sandbox) {
28
47
  const opening = performance.now();
29
48
  const worker = await proxy.open(signal);
@@ -71,7 +90,7 @@ export class WorkerBackend {
71
90
  env.FLOW_CLAUDE_PATH = support.provider.claudePath;
72
91
  for (const entry of readdirSync(env.CLAUDE_CONFIG_DIR)) {
73
92
  const link = join(env.CLAUDE_CONFIG_DIR, entry);
74
- if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && entry !== "projects")
93
+ if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && !["projects", "file-history"].includes(entry))
75
94
  assets.push(realpathSync(link));
76
95
  }
77
96
  }
@@ -146,7 +165,7 @@ export class WorkerBackend {
146
165
  async create(options) {
147
166
  const begin = performance.now();
148
167
  options.signal?.throwIfAborted();
149
- const isolationMode = this.options.isolationMode?.() ?? "bubblewrap";
168
+ const isolationMode = options.isolationMode ?? this.options.isolationMode?.() ?? "bubblewrap";
150
169
  if (isolationMode === "sandbox")
151
170
  return this.createSandboxed(options);
152
171
  if (isolationMode === "none") {
@@ -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
+ 9b413a4b-f6c7-4907-a328-516c056eb9ad
@@ -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("9b413a4b-f6c7-4907-a328-516c056eb9ad", 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,7 @@ 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.producer === undefined ? {} : { producer: event.producer }),
187
192
  status: event.state,
188
193
  // Only ever set alongside "waiting", so a Subagent that resumes drops it rather than
189
194
  // carrying a stale object it is no longer waiting on.
@@ -335,7 +340,8 @@ function applyEvent(state, event, at) {
335
340
  case "notice":
336
341
  return {
337
342
  ...state,
338
- entries: [...state.entries, { kind: "notice", id: `notice-${state.entries.length}`, level: event.level, text: event.text }],
343
+ entries: [...state.entries, { kind: "notice", id: `notice-${state.entries.length}`, level: event.level, text: event.text,
344
+ ...(event.sessionId === undefined ? {} : { sessionId: event.sessionId }) }],
339
345
  };
340
346
  case "compacting":
341
347
  // 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
+ }
@@ -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;
@@ -1,3 +1,4 @@
1
+ import { waitForAbort } from "../backend/worker/rpc.js";
1
2
  import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from "../backend/session-tools.js";
2
3
  import { sessionToolSummary, sessionToolPage } from "./session-tool-views.js";
3
4
  import { credentialKey } from "./credential-redaction.js";
@@ -16,6 +17,7 @@ import { deriveStatus, railGroupRank } from "../client/status.js";
16
17
  import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
17
18
  import { SessionLog } from "./log.js";
18
19
  import { probeModels } from "./models.js";
20
+ import { ScheduleValidationError } from "../workflows/schedule-errors.js";
19
21
  import { probeSkills } from "./skills.js";
20
22
  import { recordTiming } from "./timings.js";
21
23
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
@@ -298,10 +300,11 @@ export class SessionHost {
298
300
  * In flight rather than resolved is what is remembered, so two clients opening the page at once
299
301
  * spawn one probe between them rather than one each.
300
302
  */
301
- async models(scope, refresh = false) {
303
+ async models(scope, refresh = false, backendName) {
302
304
  if (refresh)
303
305
  this.modelProbes.clear();
304
- const probes = [...this.backends.values()].map((backend) => {
306
+ const backends = backendName === undefined ? [...this.backends.values()] : [this.backendFor(backendName)];
307
+ const probes = backends.map((backend) => {
305
308
  const held = this.modelProbes.get(backend.name);
306
309
  if (held)
307
310
  return held;
@@ -311,6 +314,15 @@ export class SessionHost {
311
314
  });
312
315
  return await Promise.all(probes);
313
316
  }
317
+ async workflowAgentModels(scope, backend) {
318
+ const [catalogue] = await this.models(scope, false, backend);
319
+ if (!catalogue || catalogue.problem)
320
+ throw new Error(catalogue?.problem ?? 'Workflow model capabilities are unavailable');
321
+ const probe = this.skillSessions.get(backend);
322
+ if (!probe || probe.dead || !probe.session.startWorkflowSubagent)
323
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
324
+ return catalogue.models;
325
+ }
314
326
  /**
315
327
  * Which Skills a Scope offers through one Backend Adapter, with no Agent Session in it.
316
328
  *
@@ -566,6 +578,7 @@ export class SessionHost {
566
578
  branch: branchFrom(entries),
567
579
  branchGeneration: 0,
568
580
  worktree: meta.worktree,
581
+ ...(meta.scheduledOccurrenceId ? { scheduledOccurrenceId: meta.scheduledOccurrenceId } : {}),
569
582
  pendingBranchNote: undefined,
570
583
  capabilities: capabilitiesFrom(entries),
571
584
  spend: spendFrom(entries),
@@ -594,7 +607,30 @@ export class SessionHost {
594
607
  }
595
608
  await this.reap();
596
609
  }
610
+ scheduledAttachments = new Map();
611
+ /** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
612
+ * The caller has already journaled the intended identity before entering this operation. */
613
+ attachScheduled(options) {
614
+ if (this.workflowShutdown)
615
+ return Promise.reject(new CommandRefused('Session Host is stopping'));
616
+ const id = options.scheduled.id;
617
+ const pending = this.scheduledAttachments.get(id);
618
+ if (pending)
619
+ return pending;
620
+ const attachment = this.create(options).finally(() => { this.scheduledAttachments.delete(id); });
621
+ this.scheduledAttachments.set(id, attachment);
622
+ return attachment;
623
+ }
597
624
  async create(options) {
625
+ if (options.scheduled) {
626
+ const existing = this.sessions.get(options.scheduled.id);
627
+ if (existing) {
628
+ if (existing.scheduledOccurrenceId !== options.scheduled.occurrenceId)
629
+ throw new Error('Scheduled association mismatch');
630
+ await this.openWorkflowSession(existing.id);
631
+ return existing.id;
632
+ }
633
+ }
598
634
  const connections = this.mcpConnections?.() ?? [];
599
635
  if (options.mcpConnectionIds !== undefined && (!Array.isArray(options.mcpConnectionIds) || options.mcpConnectionIds.some((id) => typeof id !== "string")))
600
636
  throw new Error("Invalid MCP selection");
@@ -606,17 +642,18 @@ export class SessionHost {
606
642
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
607
643
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
608
644
  this.validatePermissionMode(backend.name, permissionMode);
609
- const worktree = options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined;
645
+ const worktree = options.scheduled?.worktree ?? (options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined);
610
646
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
611
647
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
612
648
  // that is not there.
613
649
  const scope = scopeKey(worktree?.path ?? options.scope);
614
- const id = randomUUID();
650
+ const id = options.scheduled?.id ?? randomUUID();
615
651
  const now = new Date().toISOString();
616
652
  const modelId = options.modelId ?? this.defaultModel?.(backend.name);
617
653
  const effort = options.effort ?? this.defaultEffort?.(backend.name);
618
654
  const record = {
619
655
  id,
656
+ ...(options.scheduled ? { scheduledOccurrenceId: options.scheduled.occurrenceId } : {}),
620
657
  scope,
621
658
  backendName: backend.name,
622
659
  log: this.newLog(id),
@@ -684,7 +721,8 @@ export class SessionHost {
684
721
  // Creation never returns an Agent Session without confirmed models. In particular, do not
685
722
  // leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
686
723
  await record.session?.dispose().catch(() => { });
687
- await this.releaseWorktree(record);
724
+ if (!options.scheduled)
725
+ await this.releaseWorktree(record);
688
726
  record.log.closeSubscribers();
689
727
  this.sessions.delete(id);
690
728
  this.store?.deleteSession(id);
@@ -712,7 +750,8 @@ export class SessionHost {
712
750
  * how a spare gets dropped when somebody clears the Setting: nothing will ever *tell* us it
713
751
  * changed (ADR 0009), so a read-through is the only moment it can be noticed.
714
752
  */
715
- this.warmSummaryModel(backend.name);
753
+ if (!options.scheduled)
754
+ this.warmSummaryModel(backend.name);
716
755
  return id;
717
756
  }
718
757
  /**
@@ -893,7 +932,7 @@ export class SessionHost {
893
932
  * value that can bypass the Steering Queue, and "after_turn" already means "queue if busy, else
894
933
  * dispatch now" — so there is no sensible default to pick. It matches `Command` either way.
895
934
  */
896
- async send(sessionId, text, when, attachments, beforeAccept, titleText) {
935
+ async send(sessionId, text, when, attachments, beforeAccept, titleText, fromSessionId) {
897
936
  const record = this.record(sessionId);
898
937
  this.refuseGitOperation(record.scope);
899
938
  // ADR 0003: the first message revives a Dormant session, so resuming work is one action.
@@ -906,14 +945,15 @@ export class SessionHost {
906
945
  // Checked before anything is written, so a refused send leaves no bytes behind.
907
946
  this.refuseUnservableAttachments(record, attachments);
908
947
  const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
948
+ const from = fromSessionId === undefined ? {} : { fromSessionId };
909
949
  if (when === "after_turn" && record.turnInFlight) {
910
- record.queue.push({ id: randomUUID(), text, attachments: ids });
950
+ record.queue.push({ id: randomUUID(), text, attachments: ids, ...from });
911
951
  record.log.append(queueChanged(record.queue));
912
952
  this.touch(record);
913
953
  return;
914
954
  }
915
955
  // A title override applies only to the initial dispatch; a queued turn already has a title.
916
- await this.dispatch(record, { text, attachments: ids }, titleText);
956
+ await this.dispatch(record, { text, attachments: ids, ...from }, titleText);
917
957
  }
918
958
  /**
919
959
  * Whether this send's Attachments can be carried at all, refused before any are written down.
@@ -1920,6 +1960,8 @@ export class SessionHost {
1920
1960
  for (const record of [...this.sessions.values()]) {
1921
1961
  if (record.lifecycle !== "settled")
1922
1962
  continue;
1963
+ if (this.workflowOwner?.canForget?.(record.id, record.scheduledOccurrenceId) === false)
1964
+ continue;
1923
1965
  const settledAt = record.settledAt === undefined ? NaN : Date.parse(record.settledAt);
1924
1966
  // An unreadable timestamp means we cannot know the age; leaving it is the safe failure.
1925
1967
  if (Number.isNaN(settledAt) || now - settledAt < retention)
@@ -2075,7 +2117,7 @@ export class SessionHost {
2075
2117
  this.workflowShutdown = true;
2076
2118
  // Creation can still be awaiting backend startup after its caller disconnects. Drain those
2077
2119
  // accepted operations before walking sessions, so late children cannot escape shutdown.
2078
- await Promise.allSettled([...this.sessionToolOperations]);
2120
+ await Promise.allSettled([...this.sessionToolOperations, ...this.scheduledAttachments.values()]);
2079
2121
  // First, so that a naming still in flight cannot warm a replacement on the way out — the
2080
2122
  // one-shot CLI runner shuts down microseconds before `process.exit`, and a spare booted in
2081
2123
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
@@ -2233,27 +2275,48 @@ export class SessionHost {
2233
2275
  throw new Error('Unknown Agent Session');
2234
2276
  return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
2235
2277
  }
2278
+ scheduledConnections(ids) {
2279
+ const connections = this.mcpConnections?.() ?? [];
2280
+ if (ids.some(id => !connections.some(connection => connection.id === id)))
2281
+ throw new ScheduleValidationError('Selected MCP connection is unavailable');
2282
+ return structuredClone(connections.filter(connection => ids.includes(connection.id)));
2283
+ }
2284
+ scheduledMcp(scope, ids, mode) {
2285
+ const connections = this.scheduledConnections(ids);
2286
+ const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2287
+ return import("../backend/mcp.js").then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2288
+ }
2289
+ scheduledSandboxMcp(scope, ids) {
2290
+ return import("../backend/worker/sandbox-mcp.js").then(({ SandboxMcpSession }) => new SandboxMcpSession(this.scheduledConnections(ids), scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, this.resolveSecret));
2291
+ }
2236
2292
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2237
2293
  filesystemStateRoot() { return this.store?.root; }
2238
2294
  /** A host without configured Settings keeps the safe, restricted library default. */
2239
2295
  filesystemIsolationMode() { return this.filesystemIsolation?.() ?? "bubblewrap"; }
2240
2296
  sandboxSupport() { return this.sandbox?.(); }
2241
2297
  /** The Shared Sandbox, when the Settings choose one VM for all sandbox sessions. */
2298
+ scheduledSandboxMounts(scope) {
2299
+ const mounts = [...this.backends.values()].flatMap(backend => backend.scheduledSandboxMounts?.(scope) ?? []);
2300
+ return { writable: mounts.flatMap(item => item.writable), readable: mounts.flatMap(item => item.readable) };
2301
+ }
2242
2302
  sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2243
- async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode()) {
2303
+ async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
2304
+ signal?.throwIfAborted();
2244
2305
  if (isolationMode === "sandbox") {
2245
- await this.openWorkflowSession(id);
2306
+ await waitForAbort(this.openWorkflowSession(id), signal);
2307
+ signal?.throwIfAborted();
2246
2308
  const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
2247
2309
  const mcp = this.record(id).mcp;
2248
2310
  if (!(mcp instanceof SandboxMcpSession))
2249
2311
  throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
2250
- return mcp.directView(connectionId);
2312
+ return mcp.directView(connectionId, signal);
2251
2313
  }
2252
2314
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2253
2315
  if (!connection)
2254
2316
  throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
2255
2317
  const { McpSession } = await import("../backend/mcp.js");
2256
2318
  const scope = this.workflowSession(id).scope;
2319
+ signal?.throwIfAborted();
2257
2320
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2258
2321
  }
2259
2322
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
@@ -2380,11 +2443,11 @@ export class SessionHost {
2380
2443
  mcpConnectionIds: source.mcpConnectionIds ?? [],
2381
2444
  permissionMode: source.permissionMode === 'auto' && name !== 'claude' ? 'ask' : source.permissionMode });
2382
2445
  // Persist a receipt even if cancellation loses the RPC result; never blindly recreate.
2383
- source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}` });
2384
- this.record(sessionId).log.append({ type: 'notice', level: 'info', text: `Created by Agent Session ${source.id}` });
2446
+ source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}`, sessionId });
2447
+ this.record(sessionId).log.append({ type: 'notice', level: 'info', text: `Created by Agent Session ${source.id}`, sessionId: source.id });
2385
2448
  try {
2386
2449
  check(signal);
2387
- await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text);
2450
+ await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
2388
2451
  return { sessionId, delivery: 'accepted' };
2389
2452
  }
2390
2453
  catch (error) {
@@ -2396,7 +2459,7 @@ export class SessionHost {
2396
2459
  const { sessionId, text } = sessionSendInput.parse(input);
2397
2460
  if (sessionId === source.id)
2398
2461
  throw new CommandRefused('Use the current conversation instead of messaging yourself');
2399
- await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text);
2462
+ await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
2400
2463
  return { sessionId, delivery: 'accepted' };
2401
2464
  }),
2402
2465
  };
@@ -2418,6 +2481,7 @@ export class SessionHost {
2418
2481
  const compactionModelId = this.compactionModel?.(backend.name);
2419
2482
  let attached;
2420
2483
  const session = await backend.create({
2484
+ isolationMode,
2421
2485
  mcp,
2422
2486
  onFailure: () => {
2423
2487
  if (!attached || record.session !== attached)
@@ -2656,7 +2720,7 @@ export class SessionHost {
2656
2720
  }
2657
2721
  record.initialEffortUnconfirmed = false;
2658
2722
  }
2659
- const { text, attachments } = message;
2723
+ const { text, attachments, fromSessionId } = message;
2660
2724
  const note = record.pendingBranchNote;
2661
2725
  record.pendingBranchNote = undefined;
2662
2726
  /*
@@ -2679,6 +2743,7 @@ export class SessionHost {
2679
2743
  id: messageId,
2680
2744
  text: sent,
2681
2745
  ...(attachments.length > 0 ? { attachments } : {}),
2746
+ ...(fromSessionId === undefined ? {} : { fromSessionId }),
2682
2747
  });
2683
2748
  // Titled from the original instructions, never attribution or `sent`. A switch made before the first
2684
2749
  // message would otherwise name the Agent Session after the note, and permanently: the rename
@@ -2994,6 +3059,7 @@ export class SessionHost {
2994
3059
  return;
2995
3060
  const meta = {
2996
3061
  id: record.id,
3062
+ ...(record.scheduledOccurrenceId ? { scheduledOccurrenceId: record.scheduledOccurrenceId } : {}),
2997
3063
  scope: record.scope,
2998
3064
  backend: record.backendName,
2999
3065
  title: record.title,
@@ -3228,12 +3294,13 @@ function openSubagents(entries) {
3228
3294
  const event = entry.event;
3229
3295
  if (event.type !== "subagent")
3230
3296
  continue;
3231
- if (event.state === "running" || event.state === "waiting")
3232
- open.set(event.subagentId, event.name);
3297
+ if (event.state === "running" || event.state === "waiting") {
3298
+ open.set(event.subagentId, { name: event.name, ...(event.producer === undefined ? {} : { producer: event.producer }) });
3299
+ }
3233
3300
  else
3234
3301
  open.delete(event.subagentId);
3235
3302
  }
3236
- return [...open].map(([subagentId, name]) => ({ subagentId, name }));
3303
+ return [...open].map(([subagentId, brief]) => ({ subagentId, ...brief }));
3237
3304
  }
3238
3305
  /** What the transcript last reported this Agent Session had spent, across every Backend Session. */
3239
3306
  function spendFrom(entries) {