@nathanstephenson/flow 0.1.10-beta.1 → 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 (73) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
  3. package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
  4. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
  5. package/build/backend-worker.mjs +48 -7
  6. package/dist/backend/claude/background-calls.js +7 -3
  7. package/dist/backend/claude/index.js +72 -10
  8. package/dist/backend/claude/subagents.js +30 -9
  9. package/dist/backend/fake/index.js +36 -6
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/state.js +16 -1
  12. package/dist/backend/pi/subagents.js +7 -3
  13. package/dist/backend/worker/claude-state.js +22 -0
  14. package/dist/backend/worker/entry.js +25 -6
  15. package/dist/backend/worker/index.js +30 -5
  16. package/dist/backend/worker/protocol.js +1 -1
  17. package/dist/backend/worker/rpc.js +13 -0
  18. package/dist/backend/worker/sandbox-mcp.js +18 -7
  19. package/dist/backend/workflow-tools.js +9 -7
  20. package/dist/build-id +1 -1
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/client/reduce.js +29 -3
  23. package/dist/client/subagent-tree.js +49 -0
  24. package/dist/daemon/git.js +10 -7
  25. package/dist/daemon/host.js +226 -26
  26. package/dist/daemon/runtime.js +71 -3
  27. package/dist/daemon/server.js +3 -0
  28. package/dist/daemon/store.js +2 -0
  29. package/dist/daemon/workflow-builder-guidance.js +1 -1
  30. package/dist/daemon/workflow-builder.js +36 -11
  31. package/dist/daemon/workflow-environment.js +191 -0
  32. package/dist/daemon/workflow-execution-launch.js +77 -0
  33. package/dist/daemon/workflow-execution-resources.js +76 -0
  34. package/dist/daemon/workflow-execution-routes.js +9 -6
  35. package/dist/daemon/workflow-execution-values.js +128 -0
  36. package/dist/daemon/workflow-executions.js +382 -300
  37. package/dist/daemon/workflow-routes.js +39 -0
  38. package/dist/daemon/workflow-schedule-driver.js +247 -0
  39. package/dist/daemon/workflow-schedule-routes.js +137 -0
  40. package/dist/daemon/workflow-schedules.js +341 -0
  41. package/dist/isolation/sandbox.js +30 -14
  42. package/dist/isolation/shared-sandbox.js +3 -3
  43. package/dist/protocol/events.js +2 -0
  44. package/dist/protocol/workflow-schedules.js +1 -0
  45. package/dist/tui/render.js +7 -1
  46. package/dist/workflows/calls.js +53 -0
  47. package/dist/workflows/errors.js +2 -0
  48. package/dist/workflows/executors.js +1 -1
  49. package/dist/workflows/graph.js +78 -4
  50. package/dist/workflows/invocations.js +23 -0
  51. package/dist/workflows/owner.js +45 -0
  52. package/dist/workflows/records.js +124 -8
  53. package/dist/workflows/recovery.js +37 -1
  54. package/dist/workflows/schedule-errors.js +2 -0
  55. package/dist/workflows/schedule-store.js +385 -0
  56. package/dist/workflows/scheduler.js +351 -92
  57. package/dist/workflows/schedules.js +129 -0
  58. package/dist/workflows/schema.js +2 -0
  59. package/dist/workflows/store.js +110 -11
  60. package/package.json +2 -1
  61. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  62. package/web/dist/assets/index-Miy2nveb.js +40 -0
  63. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
  64. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  65. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  66. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  67. package/web/dist/index.html +4 -3
  68. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  69. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  70. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  71. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  72. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  73. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -1,8 +1,9 @@
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";
4
5
  import { randomUUID } from "node:crypto";
5
- import { existsSync, realpathSync } from "node:fs";
6
+ import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
6
7
  import { isAbsolute, join, resolve } from "node:path";
7
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
8
9
  import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.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,11 +578,13 @@ 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),
572
585
  mcpConnectionIds: meta.mcpConnectionIds ?? [],
573
586
  resumeToken: meta.resumeToken,
587
+ rewindTo: meta.rewindTo,
574
588
  modelId: meta.modelId,
575
589
  effort: meta.effort,
576
590
  permissionMode: meta.permissionMode ?? this.permissionDefault(meta.backend),
@@ -593,7 +607,30 @@ export class SessionHost {
593
607
  }
594
608
  await this.reap();
595
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
+ }
596
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
+ }
597
634
  const connections = this.mcpConnections?.() ?? [];
598
635
  if (options.mcpConnectionIds !== undefined && (!Array.isArray(options.mcpConnectionIds) || options.mcpConnectionIds.some((id) => typeof id !== "string")))
599
636
  throw new Error("Invalid MCP selection");
@@ -605,17 +642,18 @@ export class SessionHost {
605
642
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
606
643
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
607
644
  this.validatePermissionMode(backend.name, permissionMode);
608
- 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);
609
646
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
610
647
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
611
648
  // that is not there.
612
649
  const scope = scopeKey(worktree?.path ?? options.scope);
613
- const id = randomUUID();
650
+ const id = options.scheduled?.id ?? randomUUID();
614
651
  const now = new Date().toISOString();
615
652
  const modelId = options.modelId ?? this.defaultModel?.(backend.name);
616
653
  const effort = options.effort ?? this.defaultEffort?.(backend.name);
617
654
  const record = {
618
655
  id,
656
+ ...(options.scheduled ? { scheduledOccurrenceId: options.scheduled.occurrenceId } : {}),
619
657
  scope,
620
658
  backendName: backend.name,
621
659
  log: this.newLog(id),
@@ -650,6 +688,7 @@ export class SessionHost {
650
688
  spend: undefined,
651
689
  mcpConnectionIds,
652
690
  resumeToken: undefined,
691
+ rewindTo: undefined,
653
692
  /*
654
693
  * Resolved here and never again.
655
694
  *
@@ -671,6 +710,8 @@ export class SessionHost {
671
710
  record.buffered = [];
672
711
  let session;
673
712
  try {
713
+ if (options.fork)
714
+ this.copyForkState(record, options.fork.source, options.fork.userMessageId, options.fork.prefix);
674
715
  session = await this.startPermissionBackend(record);
675
716
  if (session.capabilities.models.length === 0) {
676
717
  throw new CommandRefused("Model capabilities are unavailable. Check the backend and try again.");
@@ -680,7 +721,8 @@ export class SessionHost {
680
721
  // Creation never returns an Agent Session without confirmed models. In particular, do not
681
722
  // leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
682
723
  await record.session?.dispose().catch(() => { });
683
- await this.releaseWorktree(record);
724
+ if (!options.scheduled)
725
+ await this.releaseWorktree(record);
684
726
  record.log.closeSubscribers();
685
727
  this.sessions.delete(id);
686
728
  this.store?.deleteSession(id);
@@ -694,6 +736,8 @@ export class SessionHost {
694
736
  permissionMode: record.permissionMode,
695
737
  ...(worktree === undefined ? {} : { worktree: true }),
696
738
  });
739
+ if (options.fork)
740
+ this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
697
741
  this.flushBuffered(record);
698
742
  // After session_started, never before: the transcript has to open with it (see `buffered`).
699
743
  await this.refreshBranch(record);
@@ -706,7 +750,8 @@ export class SessionHost {
706
750
  * how a spare gets dropped when somebody clears the Setting: nothing will ever *tell* us it
707
751
  * changed (ADR 0009), so a read-through is the only moment it can be noticed.
708
752
  */
709
- this.warmSummaryModel(backend.name);
753
+ if (!options.scheduled)
754
+ this.warmSummaryModel(backend.name);
710
755
  return id;
711
756
  }
712
757
  /**
@@ -887,7 +932,7 @@ export class SessionHost {
887
932
  * value that can bypass the Steering Queue, and "after_turn" already means "queue if busy, else
888
933
  * dispatch now" — so there is no sensible default to pick. It matches `Command` either way.
889
934
  */
890
- async send(sessionId, text, when, attachments, beforeAccept, titleText) {
935
+ async send(sessionId, text, when, attachments, beforeAccept, titleText, fromSessionId) {
891
936
  const record = this.record(sessionId);
892
937
  this.refuseGitOperation(record.scope);
893
938
  // ADR 0003: the first message revives a Dormant session, so resuming work is one action.
@@ -900,14 +945,15 @@ export class SessionHost {
900
945
  // Checked before anything is written, so a refused send leaves no bytes behind.
901
946
  this.refuseUnservableAttachments(record, attachments);
902
947
  const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
948
+ const from = fromSessionId === undefined ? {} : { fromSessionId };
903
949
  if (when === "after_turn" && record.turnInFlight) {
904
- record.queue.push({ id: randomUUID(), text, attachments: ids });
950
+ record.queue.push({ id: randomUUID(), text, attachments: ids, ...from });
905
951
  record.log.append(queueChanged(record.queue));
906
952
  this.touch(record);
907
953
  return;
908
954
  }
909
955
  // A title override applies only to the initial dispatch; a queued turn already has a title.
910
- await this.dispatch(record, { text, attachments: ids }, titleText);
956
+ await this.dispatch(record, { text, attachments: ids, ...from }, titleText);
911
957
  }
912
958
  /**
913
959
  * Whether this send's Attachments can be carried at all, refused before any are written down.
@@ -1287,6 +1333,119 @@ export class SessionHost {
1287
1333
  await session.compact(instructions);
1288
1334
  this.touch(record);
1289
1335
  }
1336
+ /** Rewind (CONTEXT.md). Answers with the user message, for the composer to offer again. */
1337
+ async rewind(sessionId, userMessageId, restore) {
1338
+ const record = this.record(sessionId);
1339
+ this.refuseGitOperation(record.scope);
1340
+ if (record.lifecycle === "ended")
1341
+ throw new CommandRefused(`Agent Session ${sessionId} has Ended`);
1342
+ const message = userMessage(record.log.since(0), userMessageId)?.event;
1343
+ if (message?.type !== "user_message")
1344
+ throw new CommandRefused("That user message is not in this Agent Session");
1345
+ if (!record.session)
1346
+ await this.revive(sessionId);
1347
+ if (record.permissionChanging)
1348
+ await this.waitForPermissionChange(record);
1349
+ const session = record.session;
1350
+ if (!session)
1351
+ throw new CommandRefused(`Agent Session ${sessionId} has no Backend Session`);
1352
+ if (record.turnInFlight || record.queue.length > 0 || record.openSubagentIds.size > 0 || record.openBackgroundCallIds.size > 0) {
1353
+ throw new CommandRefused("Wait for the turn, the queued messages and the background work to finish, or abort them, before rewinding");
1354
+ }
1355
+ const files = restore !== "conversation";
1356
+ const conversation = restore !== "files";
1357
+ if (conversation && !session.capabilities.rewind)
1358
+ throw new CommandRefused(`${record.backendName} cannot rewind a Conversation Context`);
1359
+ if (files && (!session.capabilities.rewindFiles || !session.rewindFiles))
1360
+ throw new CommandRefused(`${record.backendName} cannot rewind files`);
1361
+ if (files) {
1362
+ try {
1363
+ await session.rewindFiles(userMessageId);
1364
+ }
1365
+ catch (error) {
1366
+ throw new CommandRefused(`Files were not rewound: ${errorMessage(error)}`);
1367
+ }
1368
+ }
1369
+ if (conversation) {
1370
+ record.rewindTo = userMessageId;
1371
+ this.persist(record);
1372
+ record.session = undefined;
1373
+ await this.stopBackendSession(record.scope, session, record.id);
1374
+ record.buffered = [];
1375
+ record.backendEpoch += 1;
1376
+ try {
1377
+ await this.startPermissionBackend(record);
1378
+ }
1379
+ catch (error) {
1380
+ record.buffered = undefined;
1381
+ record.lifecycle = "dormant";
1382
+ record.log.append({ type: "session_dormant", reason: `rewind failed: ${errorMessage(error)}` });
1383
+ this.touch(record);
1384
+ throw error;
1385
+ }
1386
+ }
1387
+ record.log.append({ type: "rewound", userMessageId, restore });
1388
+ this.flushBuffered(record);
1389
+ this.touch(record);
1390
+ return { text: message.text, attachments: message.attachments ?? [] };
1391
+ }
1392
+ /** Fork (CONTEXT.md). Answers with the new Agent Session's id. */
1393
+ async fork(sessionId, userMessageId, worktree) {
1394
+ const source = this.record(sessionId);
1395
+ if (!source.capabilities?.fork)
1396
+ throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
1397
+ const events = source.log.since(0);
1398
+ const at = userMessage(events, userMessageId);
1399
+ if (!at)
1400
+ throw new CommandRefused("That user message is not in this Agent Session");
1401
+ return await this.create({
1402
+ scope: worktree ? source.worktree?.repo ?? source.scope : source.scope,
1403
+ backend: source.backendName,
1404
+ ...(source.modelId === undefined ? {} : { modelId: source.modelId }),
1405
+ ...(source.effort === undefined ? {} : { effort: source.effort }),
1406
+ permissionMode: source.permissionMode,
1407
+ mcpConnectionIds: source.mcpConnectionIds ?? [],
1408
+ ...(worktree === undefined ? {} : { worktree }),
1409
+ fork: { source, userMessageId, prefix: events.filter((entry) => entry.seq < at.seq) },
1410
+ });
1411
+ }
1412
+ /** Give a Fork the source's Conversation Context, to be cut before the user message on start. */
1413
+ copyForkState(record, source, userMessageId, prefix) {
1414
+ record.title = `${source.title} (fork)`;
1415
+ record.titleSource = "summary";
1416
+ const backend = this.backendFor(source.backendName);
1417
+ const kept = prefix.some(({ event }) => event.type === "user_message");
1418
+ if (!kept || !this.store || !source.resumeToken)
1419
+ return;
1420
+ if (!backend.fork)
1421
+ throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
1422
+ record.resumeToken = backend.fork({ stateDir: this.store.backendDir(source.id), scope: source.scope, resume: source.resumeToken }, { stateDir: this.store.backendDir(record.id), scope: record.scope });
1423
+ record.rewindTo = userMessageId;
1424
+ this.persist(record);
1425
+ }
1426
+ /** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
1427
+ appendForkPrefix(record, sourceId, userMessageId, prefix) {
1428
+ for (const { event, at } of prefix) {
1429
+ if (event.type === "session_started" || event.type === "queue_changed")
1430
+ continue;
1431
+ if (event.type === "revived") {
1432
+ record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
1433
+ continue;
1434
+ }
1435
+ if (event.type === "user_message" && event.attachments && this.store) {
1436
+ const to = this.store.attachmentsDir(record.id);
1437
+ mkdirSync(to, { recursive: true });
1438
+ for (const id of event.attachments) {
1439
+ const from = join(this.store.attachmentsDir(sourceId), id);
1440
+ if (existsSync(from))
1441
+ copyFileSync(from, join(to, id));
1442
+ }
1443
+ }
1444
+ record.log.append(event, at);
1445
+ }
1446
+ this.closeTornTurn(record, record.log.since(0));
1447
+ record.log.append({ type: "forked", fromSessionId: sourceId, userMessageId });
1448
+ }
1290
1449
  /**
1291
1450
  * The Skills this Agent Session can be sent.
1292
1451
  *
@@ -1801,6 +1960,8 @@ export class SessionHost {
1801
1960
  for (const record of [...this.sessions.values()]) {
1802
1961
  if (record.lifecycle !== "settled")
1803
1962
  continue;
1963
+ if (this.workflowOwner?.canForget?.(record.id, record.scheduledOccurrenceId) === false)
1964
+ continue;
1804
1965
  const settledAt = record.settledAt === undefined ? NaN : Date.parse(record.settledAt);
1805
1966
  // An unreadable timestamp means we cannot know the age; leaving it is the safe failure.
1806
1967
  if (Number.isNaN(settledAt) || now - settledAt < retention)
@@ -1956,7 +2117,7 @@ export class SessionHost {
1956
2117
  this.workflowShutdown = true;
1957
2118
  // Creation can still be awaiting backend startup after its caller disconnects. Drain those
1958
2119
  // accepted operations before walking sessions, so late children cannot escape shutdown.
1959
- await Promise.allSettled([...this.sessionToolOperations]);
2120
+ await Promise.allSettled([...this.sessionToolOperations, ...this.scheduledAttachments.values()]);
1960
2121
  // First, so that a naming still in flight cannot warm a replacement on the way out — the
1961
2122
  // one-shot CLI runner shuts down microseconds before `process.exit`, and a spare booted in
1962
2123
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
@@ -2053,6 +2214,10 @@ export class SessionHost {
2053
2214
  return await this.rename(command.sessionId);
2054
2215
  case "compact":
2055
2216
  return await this.compact(command.sessionId, command.instructions);
2217
+ case "rewind":
2218
+ return await this.rewind(command.sessionId, command.userMessageId, command.restore);
2219
+ case "fork":
2220
+ return await this.fork(command.sessionId, command.userMessageId, command.worktree);
2056
2221
  case "answer_enquiry":
2057
2222
  return await this.answerEnquiry(command.sessionId, command.askId, command.answers);
2058
2223
  case "answer_permission":
@@ -2110,27 +2275,48 @@ export class SessionHost {
2110
2275
  throw new Error('Unknown Agent Session');
2111
2276
  return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
2112
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
+ }
2113
2292
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2114
2293
  filesystemStateRoot() { return this.store?.root; }
2115
2294
  /** A host without configured Settings keeps the safe, restricted library default. */
2116
2295
  filesystemIsolationMode() { return this.filesystemIsolation?.() ?? "bubblewrap"; }
2117
2296
  sandboxSupport() { return this.sandbox?.(); }
2118
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
+ }
2119
2302
  sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2120
- async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode()) {
2303
+ async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
2304
+ signal?.throwIfAborted();
2121
2305
  if (isolationMode === "sandbox") {
2122
- await this.openWorkflowSession(id);
2306
+ await waitForAbort(this.openWorkflowSession(id), signal);
2307
+ signal?.throwIfAborted();
2123
2308
  const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
2124
2309
  const mcp = this.record(id).mcp;
2125
2310
  if (!(mcp instanceof SandboxMcpSession))
2126
2311
  throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
2127
- return mcp.directView(connectionId);
2312
+ return mcp.directView(connectionId, signal);
2128
2313
  }
2129
2314
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2130
2315
  if (!connection)
2131
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.');
2132
2317
  const { McpSession } = await import("../backend/mcp.js");
2133
2318
  const scope = this.workflowSession(id).scope;
2319
+ signal?.throwIfAborted();
2134
2320
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2135
2321
  }
2136
2322
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
@@ -2257,11 +2443,11 @@ export class SessionHost {
2257
2443
  mcpConnectionIds: source.mcpConnectionIds ?? [],
2258
2444
  permissionMode: source.permissionMode === 'auto' && name !== 'claude' ? 'ask' : source.permissionMode });
2259
2445
  // Persist a receipt even if cancellation loses the RPC result; never blindly recreate.
2260
- source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}` });
2261
- 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 });
2262
2448
  try {
2263
2449
  check(signal);
2264
- 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);
2265
2451
  return { sessionId, delivery: 'accepted' };
2266
2452
  }
2267
2453
  catch (error) {
@@ -2273,7 +2459,7 @@ export class SessionHost {
2273
2459
  const { sessionId, text } = sessionSendInput.parse(input);
2274
2460
  if (sessionId === source.id)
2275
2461
  throw new CommandRefused('Use the current conversation instead of messaging yourself');
2276
- 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);
2277
2463
  return { sessionId, delivery: 'accepted' };
2278
2464
  }),
2279
2465
  };
@@ -2295,6 +2481,7 @@ export class SessionHost {
2295
2481
  const compactionModelId = this.compactionModel?.(backend.name);
2296
2482
  let attached;
2297
2483
  const session = await backend.create({
2484
+ isolationMode,
2298
2485
  mcp,
2299
2486
  onFailure: () => {
2300
2487
  if (!attached || record.session !== attached)
@@ -2325,6 +2512,7 @@ export class SessionHost {
2325
2512
  ...(record.effort === undefined ? {} : { effort: record.effort }),
2326
2513
  permissionMode: record.permissionMode,
2327
2514
  ...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
2515
+ ...(record.resumeToken === undefined || record.rewindTo === undefined ? {} : { resumeBefore: record.rewindTo }),
2328
2516
  ...(record.spend === undefined ? {} : { priorSpend: record.spend }),
2329
2517
  ...(this.store ? { stateDir: this.store.backendDir(record.id) } : {}),
2330
2518
  // Read here rather than held, so a Revive picks up every grant made since this Agent Session
@@ -2385,8 +2573,8 @@ export class SessionHost {
2385
2573
  await abort();
2386
2574
  };
2387
2575
  const prompt = session.prompt.bind(session);
2388
- session.prompt = (text, attachments) => {
2389
- pendingTurn = waitForMcp(() => prompt(text, attachments));
2576
+ session.prompt = (text, attachments, messageId) => {
2577
+ pendingTurn = waitForMcp(() => prompt(text, attachments, messageId));
2390
2578
  return pendingTurn;
2391
2579
  };
2392
2580
  if (session.compact) {
@@ -2532,7 +2720,7 @@ export class SessionHost {
2532
2720
  }
2533
2721
  record.initialEffortUnconfirmed = false;
2534
2722
  }
2535
- const { text, attachments } = message;
2723
+ const { text, attachments, fromSessionId } = message;
2536
2724
  const note = record.pendingBranchNote;
2537
2725
  record.pendingBranchNote = undefined;
2538
2726
  /*
@@ -2549,11 +2737,13 @@ export class SessionHost {
2549
2737
  const startingTurn = !record.turnInFlight;
2550
2738
  const generation = record.turnGeneration = (record.turnGeneration ?? 0) + (startingTurn ? 1 : 0);
2551
2739
  record.turnInFlight = true;
2740
+ const messageId = randomUUID();
2552
2741
  record.log.append({
2553
2742
  type: "user_message",
2554
- id: randomUUID(),
2743
+ id: messageId,
2555
2744
  text: sent,
2556
2745
  ...(attachments.length > 0 ? { attachments } : {}),
2746
+ ...(fromSessionId === undefined ? {} : { fromSessionId }),
2557
2747
  });
2558
2748
  // Titled from the original instructions, never attribution or `sent`. A switch made before the first
2559
2749
  // message would otherwise name the Agent Session after the note, and permanently: the rename
@@ -2584,7 +2774,7 @@ export class SessionHost {
2584
2774
  this.recordDispatchFailure(record, error, startingTurn);
2585
2775
  };
2586
2776
  try {
2587
- void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments)).catch(failed);
2777
+ void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments), messageId).catch(failed);
2588
2778
  }
2589
2779
  catch (error) {
2590
2780
  failed(error);
@@ -2637,6 +2827,10 @@ export class SessionHost {
2637
2827
  if (event.type === "turn_started" || (event.type === "permission" && event.state === "asked")) {
2638
2828
  record.permissionActivityVersion = (record.permissionActivityVersion ?? 0) + 1;
2639
2829
  }
2830
+ if (event.type === "turn_started" && record.rewindTo !== undefined) {
2831
+ record.rewindTo = undefined;
2832
+ this.persist(record);
2833
+ }
2640
2834
  const before = this.activityOf(record);
2641
2835
  const permissionWasOpen = event.type === "permission" && record.openPermissionAttention.has(event.callId);
2642
2836
  const enquiryWasOpen = event.type === "enquiry" && record.openEnquiryAttention.has(event.askId);
@@ -2865,6 +3059,7 @@ export class SessionHost {
2865
3059
  return;
2866
3060
  const meta = {
2867
3061
  id: record.id,
3062
+ ...(record.scheduledOccurrenceId ? { scheduledOccurrenceId: record.scheduledOccurrenceId } : {}),
2868
3063
  scope: record.scope,
2869
3064
  backend: record.backendName,
2870
3065
  title: record.title,
@@ -2884,6 +3079,7 @@ export class SessionHost {
2884
3079
  readAttentionVersion: record.readAttentionVersion,
2885
3080
  mcpConnectionIds: record.mcpConnectionIds ?? [],
2886
3081
  ...(record.resumeToken === undefined ? {} : { resumeToken: record.resumeToken }),
3082
+ ...(record.rewindTo === undefined ? {} : { rewindTo: record.rewindTo }),
2887
3083
  ...(record.modelId === undefined ? {} : { modelId: record.modelId }),
2888
3084
  ...(record.effort === undefined ? {} : { effort: record.effort }),
2889
3085
  permissionMode: record.permissionMode,
@@ -2902,6 +3098,9 @@ export function suggestedScope(scope, worktreesRoot) {
2902
3098
  const candidate = join(worktreesRoot, scope.slice(at + marker.length));
2903
3099
  return candidate !== scope && existsSync(candidate) ? candidate : undefined;
2904
3100
  }
3101
+ function userMessage(entries, id) {
3102
+ return entries.find(({ event }) => event.type === "user_message" && event.id === id);
3103
+ }
2905
3104
  /** The turn still open at the end of these entries, if any. */
2906
3105
  function openTurnId(entries) {
2907
3106
  let openTurn;
@@ -3095,12 +3294,13 @@ function openSubagents(entries) {
3095
3294
  const event = entry.event;
3096
3295
  if (event.type !== "subagent")
3097
3296
  continue;
3098
- if (event.state === "running" || event.state === "waiting")
3099
- 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
+ }
3100
3300
  else
3101
3301
  open.delete(event.subagentId);
3102
3302
  }
3103
- return [...open].map(([subagentId, name]) => ({ subagentId, name }));
3303
+ return [...open].map(([subagentId, brief]) => ({ subagentId, ...brief }));
3104
3304
  }
3105
3305
  /** What the transcript last reported this Agent Session had spent, across every Backend Session. */
3106
3306
  function spendFrom(entries) {
@@ -4,7 +4,11 @@ import { ConfigStore } from "./config-store.js";
4
4
  import { SecretStore } from "./secret-store.js";
5
5
  import { WorkflowStore } from "../workflows/store.js";
6
6
  import { WorkflowExecutionService } from "./workflow-executions.js";
7
+ import { WorkflowScheduleStore } from "../workflows/schedule-store.js";
8
+ import { WorkflowScheduleService } from "./workflow-schedules.js";
9
+ import { scheduleDriver } from "./workflow-schedule-driver.js";
7
10
  import { WorkflowBuilderService } from "./workflow-builder.js";
11
+ import { workflowCatalogue } from "./workflow-routes.js";
8
12
  import { WorkflowMcpAuthoringService } from "./workflow-mcp-authoring.js";
9
13
  import { SessionHost } from "./host.js";
10
14
  import { McpAuth } from "./mcp-auth.js";
@@ -51,6 +55,8 @@ export async function startRuntime(options) {
51
55
  defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
52
56
  });
53
57
  const shells = new ShellRegistry();
58
+ let workflowSchedules;
59
+ let workflowExecutions;
54
60
  let workflowBuilders;
55
61
  let workflowMcpAuthoring;
56
62
  let running;
@@ -60,6 +66,19 @@ export async function startRuntime(options) {
60
66
  let stopping;
61
67
  const stop = () => stopping ??= (async () => {
62
68
  clearInterval(sweep);
69
+ const scheduledErrors = [];
70
+ try {
71
+ await workflowSchedules?.stopAdmission();
72
+ }
73
+ catch (error) {
74
+ scheduledErrors.push(error);
75
+ }
76
+ try {
77
+ await workflowExecutions?.stopScheduled();
78
+ }
79
+ catch (error) {
80
+ scheduledErrors.push(error);
81
+ }
63
82
  const interrupt = async () => { await Promise.all([host.shutdown(), workflowBuilders?.shutdown(), workflowMcpAuthoring?.shutdown(), shells.killAll(), reaping]); };
64
83
  if (running)
65
84
  await running.stopAdmission(interrupt);
@@ -77,23 +96,71 @@ export async function startRuntime(options) {
77
96
  oidc?.dispose();
78
97
  }
79
98
  ownership.release();
99
+ if (scheduledErrors.length)
100
+ throw new AggregateError(scheduledErrors, 'Scheduled workflow cleanup failed');
80
101
  })();
81
102
  cleanup = stop;
82
103
  registerBackends(host);
83
104
  trimTimings(root);
84
105
  void host.models(config.projectRoot() ?? process.cwd());
85
106
  const workflows = new WorkflowStore(root);
86
- const workflowExecutions = new WorkflowExecutionService(host, workflows, secrets, config, options.workflowRuntime());
107
+ store.onSessionDeleted = sessionId => workflows.deleteOwner({ kind: 'session', sessionId });
108
+ workflowExecutions = new WorkflowExecutionService(host, workflows, secrets, config, options.workflowRuntime());
87
109
  workflowMcpAuthoring = new WorkflowMcpAuthoringService({ host, config, scope: process.cwd() });
88
110
  workflowBuilders = new WorkflowBuilderService({
89
111
  host, config, scope: process.cwd(), stateRoot: root,
90
112
  validateDefinition: definition => workflowExecutions.validateDefinitionCredentials(definition),
113
+ workflowCatalogue: () => workflowCatalogue(workflows),
114
+ workflowDefinition: id => { try {
115
+ return workflows.getDefinition(id);
116
+ }
117
+ catch {
118
+ return undefined;
119
+ } },
91
120
  mcpCatalogue: (scope, projectId, scopeIdentity) => workflowMcpAuthoring.catalogue(projectId, { scope, scopeIdentity }),
92
121
  mcpTool: (scope, projectId, scopeIdentity, connectionId, toolName) => workflowMcpAuthoring.tool(projectId, connectionId, toolName, { scope, scopeIdentity }),
93
122
  });
123
+ try {
124
+ const schedules = new WorkflowScheduleStore(root);
125
+ workflowSchedules = new WorkflowScheduleService(schedules, scheduleDriver({ host, config, workflows, executions: workflowExecutions, schedules, transcripts: store }));
126
+ workflowExecutions.onScheduledResult = async (record) => { workflowSchedules.result(record); };
127
+ }
128
+ catch {
129
+ workflowExecutions.scheduledOwnershipAvailable = false;
130
+ console.error('Workflow Schedule initialization failed. Scheduling is disabled. Other Session Host services will continue.');
131
+ }
94
132
  await host.load();
133
+ try {
134
+ await workflowSchedules?.start();
135
+ }
136
+ catch {
137
+ console.error('Workflow Schedule reconciliation failed. Other Session Host services will continue.');
138
+ }
95
139
  workflowExecutions.reconcile();
96
- sweep = setInterval(() => { reaping = reaping.then(async () => { await host.reap(); }); }, 60 * 60 * 1000);
140
+ reaping = reaping.then(async () => {
141
+ try {
142
+ await workflowSchedules?.prune();
143
+ }
144
+ catch {
145
+ console.error('Workflow Schedule retention failed. Cleanup will be retried.');
146
+ }
147
+ });
148
+ sweep = setInterval(() => {
149
+ reaping = reaping.then(async () => {
150
+ try {
151
+ await host.reap();
152
+ }
153
+ catch {
154
+ console.error('Agent Session Reaping failed. The next sweep will retry.');
155
+ }
156
+ try {
157
+ await workflowSchedules?.prune();
158
+ }
159
+ catch {
160
+ console.error('Workflow Schedule retention failed. The next sweep will retry.');
161
+ }
162
+ });
163
+ }, 60 * 60 * 1000);
97
164
  sweep.unref();
98
165
  host.onSessionClosed(sessionId => shells.killFor(sessionId));
99
166
  const token = readOrCreateToken(root);
@@ -102,7 +169,7 @@ export async function startRuntime(options) {
102
169
  instanceId: ownership.instanceId, pid: process.pid, version: options.version, url: '', token, mode: options.mode,
103
170
  settings: { port: options.port ?? 0, address: options.address ?? '127.0.0.1', cwd: process.cwd(), oidc: oidcFingerprint() },
104
171
  };
105
- const hasActiveWork = () => host.hasActiveWork() || workflowBuilders.hasActiveWork() || workflowMcpAuthoring.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
172
+ const hasActiveWork = () => !!workflowSchedules?.hasActiveWork() || host.hasActiveWork() || workflowBuilders.hasActiveWork() || workflowMcpAuthoring.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
106
173
  const updates = new WebUpdateController({
107
174
  root,
108
175
  installedVersion: options.version,
@@ -116,6 +183,7 @@ export async function startRuntime(options) {
116
183
  control: { identity, stop, hasActiveWork },
117
184
  updates,
118
185
  host, token, shells, config, mcpAuth, store, workflows, secrets, workflowExecutions, workflowBuilders, workflowMcpAuthoring,
186
+ ...(workflowSchedules === undefined ? {} : { workflowSchedules }),
119
187
  assets: options.assets(), scope: process.cwd(),
120
188
  ...(oidc === undefined ? {} : { oidc }),
121
189
  ...(options.port === undefined ? {} : { port: options.port }),