@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10

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 (170) hide show
  1. package/README.md +52 -22
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
  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-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
  8. package/build/backend-worker.mjs +69 -122
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +188 -25
  13. package/dist/backend/claude/subagents.js +41 -9
  14. package/dist/backend/claude/todo-list.js +114 -0
  15. package/dist/backend/claude/workflow-parent.js +1 -1
  16. package/dist/backend/diff-excerpt-instructions.js +8 -0
  17. package/dist/backend/fake/index.js +54 -6
  18. package/dist/backend/mcp.js +4 -1
  19. package/dist/backend/pi/agent-permissions.js +1 -1
  20. package/dist/backend/pi/cache-warming.js +8 -0
  21. package/dist/backend/pi/canonical-json.js +120 -0
  22. package/dist/backend/pi/compaction-model.js +3 -2
  23. package/dist/backend/pi/host-auth.js +258 -0
  24. package/dist/backend/pi/import.js +269 -0
  25. package/dist/backend/pi/index.js +118 -20
  26. package/dist/backend/pi/model-auth.js +159 -0
  27. package/dist/backend/pi/model-catalog.js +120 -0
  28. package/dist/backend/pi/model-config.js +5 -0
  29. package/dist/backend/pi/model-selection.js +32 -0
  30. package/dist/backend/pi/plan-limits.js +41 -0
  31. package/dist/backend/pi/state.js +19 -1
  32. package/dist/backend/pi/subagents.js +7 -3
  33. package/dist/backend/pi/todo-list.js +23 -0
  34. package/dist/backend/pi/work.js +9 -1
  35. package/dist/backend/pi/workflow-parent.js +1 -1
  36. package/dist/backend/pi/workflow-subagent.js +4 -3
  37. package/dist/backend/plan-limits.js +17 -0
  38. package/dist/backend/session-tools.js +1 -1
  39. package/dist/backend/worker/claude-state.js +48 -0
  40. package/dist/backend/worker/entry.js +42 -8
  41. package/dist/backend/worker/index.js +131 -15
  42. package/dist/backend/worker/launcher.js +11 -4
  43. package/dist/backend/worker/protocol.js +2 -1
  44. package/dist/backend/worker/rpc.js +13 -0
  45. package/dist/backend/worker/sandbox-mcp.js +18 -7
  46. package/dist/backend/workflow-tools.js +9 -7
  47. package/dist/build-id +1 -1
  48. package/dist/cli/application.js +48 -42
  49. package/dist/cli/bootstrap.js +2 -2
  50. package/dist/cli/host-control.js +1 -1
  51. package/dist/cli/install-guard.js +2 -2
  52. package/dist/cli/main.js +4 -4
  53. package/dist/cli/systemd-update.js +3 -3
  54. package/dist/cli/update.js +6 -6
  55. package/dist/cli/web-update.js +6 -6
  56. package/dist/client/connection.js +46 -0
  57. package/dist/client/context-usage.js +3 -4
  58. package/dist/client/diff.js +40 -0
  59. package/dist/client/enquiry.js +0 -6
  60. package/dist/client/markdown.js +3 -2
  61. package/dist/client/model-choices.js +1 -1
  62. package/dist/client/permission.js +1 -2
  63. package/dist/client/project-name.js +3 -1
  64. package/dist/client/reduce.js +77 -3
  65. package/dist/client/relative-time.js +1 -1
  66. package/dist/client/scope-kind.js +6 -3
  67. package/dist/client/search.js +1 -1
  68. package/dist/client/status.js +1 -1
  69. package/dist/client/subagent-tree.js +49 -0
  70. package/dist/client/tool-chains.js +1 -1
  71. package/dist/client/tool-summary.js +28 -18
  72. package/dist/daemon/changes.js +128 -0
  73. package/dist/daemon/commit.js +84 -0
  74. package/dist/daemon/config-store.js +8 -3
  75. package/dist/daemon/config.js +105 -4
  76. package/dist/daemon/diff-excerpts.js +52 -0
  77. package/dist/daemon/git-state.js +197 -0
  78. package/dist/daemon/git.js +53 -10
  79. package/dist/daemon/github-image.js +18 -0
  80. package/dist/daemon/github.js +54 -0
  81. package/dist/daemon/host-control-routes.js +1 -1
  82. package/dist/daemon/host.js +940 -119
  83. package/dist/daemon/http.js +4 -1
  84. package/dist/daemon/log.js +3 -0
  85. package/dist/daemon/mcp-auth.js +1 -1
  86. package/dist/daemon/models.js +2 -2
  87. package/dist/daemon/pi-model-cache.js +44 -0
  88. package/dist/daemon/pull-request.js +223 -138
  89. package/dist/daemon/push.js +43 -0
  90. package/dist/daemon/repository.js +123 -0
  91. package/dist/daemon/runtime.js +103 -22
  92. package/dist/daemon/secret-store.js +1 -1
  93. package/dist/daemon/server.js +111 -14
  94. package/dist/daemon/skills.js +24 -0
  95. package/dist/daemon/spend-ledger.js +118 -0
  96. package/dist/daemon/stack-metadata.js +12 -5
  97. package/dist/daemon/stack.js +162 -657
  98. package/dist/daemon/store.js +2 -0
  99. package/dist/daemon/summariser.js +30 -12
  100. package/dist/daemon/tour.js +56 -0
  101. package/dist/daemon/whisper.js +144 -0
  102. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  103. package/dist/daemon/workflow-authoring-scope.js +1 -1
  104. package/dist/daemon/workflow-builder-files.js +2 -2
  105. package/dist/daemon/workflow-builder-guidance.js +1 -1
  106. package/dist/daemon/workflow-builder-routes.js +2 -2
  107. package/dist/daemon/workflow-builder.js +44 -17
  108. package/dist/daemon/workflow-environment.js +193 -0
  109. package/dist/daemon/workflow-execution-launch.js +77 -0
  110. package/dist/daemon/workflow-execution-resources.js +76 -0
  111. package/dist/daemon/workflow-execution-routes.js +12 -9
  112. package/dist/daemon/workflow-execution-values.js +128 -0
  113. package/dist/daemon/workflow-executions.js +400 -311
  114. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  115. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  116. package/dist/daemon/workflow-mcp.js +1 -1
  117. package/dist/daemon/workflow-routes.js +60 -2
  118. package/dist/daemon/workflow-schedule-driver.js +251 -0
  119. package/dist/daemon/workflow-schedule-routes.js +137 -0
  120. package/dist/daemon/workflow-schedules.js +342 -0
  121. package/dist/isolation/filesystem.js +6 -2
  122. package/dist/isolation/sandbox.js +61 -18
  123. package/dist/isolation/shared-sandbox.js +3 -3
  124. package/dist/isolation/toolchain-assets.js +1 -1
  125. package/dist/protocol/events.js +3 -0
  126. package/dist/protocol/plan-limits.js +1 -0
  127. package/dist/protocol/settings.js +1 -0
  128. package/dist/protocol/spend.js +2 -0
  129. package/dist/protocol/stack.js +12 -39
  130. package/dist/protocol/workflow-schedules.js +1 -0
  131. package/dist/workflows/calls.js +53 -0
  132. package/dist/workflows/errors.js +2 -0
  133. package/dist/workflows/executors.js +6 -5
  134. package/dist/workflows/graph.js +83 -9
  135. package/dist/workflows/invocations.js +23 -0
  136. package/dist/workflows/mcp.js +1 -1
  137. package/dist/workflows/owner.js +45 -0
  138. package/dist/workflows/records.js +127 -11
  139. package/dist/workflows/recovery.js +38 -2
  140. package/dist/workflows/runtime-settings.js +16 -16
  141. package/dist/workflows/runtime.js +2 -2
  142. package/dist/workflows/schedule-errors.js +2 -0
  143. package/dist/workflows/schedule-store.js +385 -0
  144. package/dist/workflows/scheduler.js +367 -96
  145. package/dist/workflows/schedules.js +130 -0
  146. package/dist/workflows/schema.js +3 -1
  147. package/dist/workflows/store.js +126 -13
  148. package/package.json +10 -6
  149. package/web/dist/assets/index-C76t-z4w.css +2 -0
  150. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  151. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  152. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  153. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  154. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  155. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  156. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  157. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  158. package/web/dist/index.html +6 -5
  159. package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
  160. package/dist/daemon/publish.js +0 -289
  161. package/dist/tui/app.js +0 -612
  162. package/dist/tui/keys.js +0 -90
  163. package/dist/tui/render.js +0 -411
  164. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  165. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  166. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  167. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  168. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  169. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  170. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,10 +1,14 @@
1
+ import { executionOwner } from './records.js';
2
+ import { executionAccessibleBy, executionAssociation, executionIdentity, executionOwnerKey, executionOwnerOf } from './owner.js';
1
3
  import { randomUUID } from 'node:crypto';
2
4
  import { isDeepStrictEqual } from 'node:util';
3
- import { resolveMapping, validateDefinition } from "./graph.js";
4
- import { declaredOutputSchema, parseValue, valueAt } from "./schema.js";
5
- import { validateMcpOutput } from "./mcp.js";
6
- import { WorkflowStore } from "./store.js";
7
- import { savedDefinitionRevision, validateCompatibleDefinition } from "./recovery.js";
5
+ import { resolveMapping, validateDefinition } from './graph.js';
6
+ import { declaredOutputSchema, parseValue, valueAt } from './schema.js';
7
+ import { validateMcpOutput } from './mcp.js';
8
+ import { WorkflowStore } from './store.js';
9
+ import { recoverySteps, savedDefinitionRevision, validateCompatibleDefinition } from './recovery.js';
10
+ import { resolveWorkflowCalls } from './calls.js';
11
+ import { invocationCheckpoint, invocationExecution } from './invocations.js';
8
12
  export class WorkflowStepError extends Error {
9
13
  partialOutput;
10
14
  constructor(message, partialOutput) { super(message); this.partialOutput = partialOutput; }
@@ -17,62 +21,71 @@ export class WorkflowScheduler {
17
21
  slots = new Map();
18
22
  store;
19
23
  executors;
20
- constructor(store, executors) {
24
+ onResume;
25
+ constructor(store, executors, onResume) {
21
26
  this.store = store;
22
27
  this.executors = executors;
23
- for (const sessionId of store.listSessionIds()) {
24
- for (const record of store.listExecutions(sessionId)) {
28
+ this.onResume = onResume;
29
+ for (const owner of store.listOwners()) {
30
+ let records;
31
+ try {
32
+ records = store.listOwnedExecutions(owner);
33
+ }
34
+ catch {
35
+ console.error('Workflow Execution owner records are invalid. Files retained for manual review.');
36
+ continue;
37
+ }
38
+ for (const record of records) {
25
39
  if (!occupied(record))
26
40
  continue;
27
- if (this.slots.has(sessionId))
28
- throw new Error('Multiple workflow executions occupy one Agent Session');
29
- if (record.status === 'running') {
30
- for (const step of Object.values(record.steps)) {
31
- if (step.status !== 'running')
32
- continue;
33
- step.status = 'interrupted';
34
- const attempt = step.attempts.at(-1);
35
- attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
36
- attempt.finishedAt = Date.now();
37
- }
38
- record.status = 'recovery-required';
39
- store.saveExecution(record);
40
- }
41
- this.install(record);
41
+ if (this.slots.has(executionOwnerKey(owner)))
42
+ throw new Error('Multiple workflow executions occupy one execution owner');
43
+ const active = this.install(record);
44
+ this.reconcile(active);
45
+ this.persist(active);
42
46
  }
43
47
  }
44
48
  }
45
- occupied(sessionId) { return this.slots.has(sessionId); }
49
+ occupied(sessionId) { return this.slots.has(sessionId) || [...this.active.values()].some(active => executionAssociation(active.record) === sessionId && occupied(active.record)); }
46
50
  /** Whether the slot contains a full execution doing work, excluding tests and recovery waits. */
47
51
  activeFull(sessionId) {
48
- const executionId = this.slots.get(sessionId);
52
+ const executionId = this.slots.get(sessionId) ?? [...this.active.values()].find(active => executionAssociation(active.record) === sessionId && occupied(active.record))?.record.id;
49
53
  const record = executionId ? this.active.get(executionId)?.record : undefined;
50
54
  return record?.status === 'running' && record.testStepId === undefined;
51
55
  }
52
56
  forgetSession(sessionId) {
53
- const executions = [...this.active.values()].filter(active => active.record.sessionId === sessionId);
54
- if (executions.some(active => active.running.size || active.record.status === 'running'))
57
+ const executions = [...this.active.values()].filter(active => executionOwner(active.record) === sessionId);
58
+ if (executions.some(active => this.hasWork(active) || active.record.status === 'running'))
55
59
  throw new Error('Workflow work must stop before forgetting an Agent Session');
56
60
  for (const active of executions)
57
61
  this.active.delete(active.record.id);
58
62
  this.slots.delete(sessionId);
59
63
  }
60
- start(definition, session, input, testStepId, launchId, namingEligible = false) {
61
- if (this.occupied(session.sessionId))
64
+ start(definition, session, input, testStepId, launchId, namingEligible = false, capturedDefinitions) {
65
+ if (this.occupied(executionOwner(session)))
62
66
  throw new Error('Agent Session workflow slot is occupied');
63
67
  const graph = validateDefinition(definition);
64
68
  if (graph.definition.backend !== session.backend)
65
69
  throw new Error('Backend Adapter mismatch');
66
- if (graph.definition.projectId && graph.definition.projectId !== session.projectId)
70
+ if (graph.definition.projectId && !(session.matchesProject?.(graph.definition.projectId) ?? graph.definition.projectId === session.projectId))
67
71
  throw new Error('Workflow is restricted to another Project');
68
72
  const testStep = testStepId === undefined ? undefined : graph.order.find(step => step.id === testStepId);
69
73
  if (testStepId !== undefined && !testStep)
70
74
  throw new Error('Unknown test step');
71
- this.check(testStep ? [testStep] : graph.order, session);
75
+ const retainedDefinitions = resolveWorkflowCalls(graph.definition, id => {
76
+ if (!capturedDefinitions)
77
+ return this.store.getDefinition(id);
78
+ const retained = capturedDefinitions[id];
79
+ if (!retained)
80
+ throw new Error('Missing captured Workflow Definition');
81
+ return retained;
82
+ }, testStepId);
83
+ this.check(testStep ? [testStep] : graph.order, session, retainedDefinitions);
72
84
  const parsed = parseValue(testStep ? graph.inputSchemas.get(testStep.id) : graph.definition.inputSchema, input);
73
85
  const record = {
74
- version: 1, id: randomUUID(), sessionId: session.sessionId, scope: session.scope,
86
+ ...executionIdentity(session), ...(session.runtime ? { runtime: session.runtime } : {}), id: randomUUID(), scope: session.scope,
75
87
  definition: graph.definition, input: parsed, status: 'running', startedAt: Date.now(),
88
+ ...(graph.order.some(step => step.kind === 'workflow') ? { retainedDefinitions, invocations: {} } : {}),
76
89
  ...(launchId ? { launchId } : {}),
77
90
  ...(namingEligible && testStepId === undefined ? { naming: 'pending' } : {}),
78
91
  steps: Object.fromEntries(graph.order.map(step => [step.id, { status: testStep && step.id !== testStep.id ? 'skipped' : 'pending', attempts: [] }])),
@@ -83,16 +96,25 @@ export class WorkflowScheduler {
83
96
  this.pump(active);
84
97
  return structuredClone(record);
85
98
  }
99
+ associate(occurrenceId, executionId, sessionId) {
100
+ const active = this.require(executionOwnerKey({ kind: 'occurrence', occurrenceId }), executionId);
101
+ if (executionOwnerOf(active.record).kind !== 'occurrence' || (executionAssociation(active.record) && executionAssociation(active.record) !== sessionId))
102
+ throw new Error('Invalid execution association');
103
+ const visit = (node) => { node.record.sessionId = sessionId; for (const call of node.calls.values())
104
+ visit(call.child); };
105
+ visit(active);
106
+ this.persist(active);
107
+ }
86
108
  get(sessionId, executionId) {
87
109
  const active = this.active.get(executionId);
88
- if (active?.record.sessionId === sessionId)
110
+ if (active !== undefined && executionAccessibleBy(active.record, sessionId))
89
111
  return structuredClone(active.record);
90
112
  return this.store.getExecution(sessionId, executionId);
91
113
  }
92
114
  /** Atomically consume an automatic naming request before model work starts. */
93
115
  claimNaming(sessionId, executionId) {
94
116
  const active = this.active.get(executionId);
95
- const record = active?.record.sessionId === sessionId ? active.record : this.store.getExecution(sessionId, executionId);
117
+ const record = active !== undefined && executionAccessibleBy(active.record, sessionId) ? active.record : this.store.getExecution(sessionId, executionId);
96
118
  if (record.naming !== 'pending' || record.testStepId)
97
119
  return false;
98
120
  record.naming = 'requested';
@@ -106,25 +128,20 @@ export class WorkflowScheduler {
106
128
  const active = this.require(sessionId, executionId);
107
129
  if (active.persistenceError)
108
130
  return Promise.reject(active.persistenceError);
109
- if (active.record.status !== 'running' && !active.running.size)
131
+ if (active.record.status !== 'running' && !this.hasWork(active))
110
132
  return Promise.resolve(structuredClone(active.record));
111
133
  return new Promise((resolve, reject) => active.waiters.push({ resolve, reject }));
112
134
  }
135
+ hasPendingDeadline(sessionId, executionId) {
136
+ const pending = (active) => !active.stopped && [...active.calls.values()].some(call => call.timer !== undefined || pending(call.child));
137
+ const active = this.active.get(executionId);
138
+ return active !== undefined && executionAccessibleBy(active.record, sessionId) && pending(active);
139
+ }
113
140
  async cancel(sessionId, executionId) {
114
141
  const active = this.require(sessionId, executionId);
115
142
  if (!occupied(active.record))
116
143
  return structuredClone(active.record);
117
- active.stopped = true;
118
- active.record.status = 'cancelled';
119
- for (const step of Object.values(active.record.steps))
120
- if (['pending', 'blocked', 'running', 'interrupted'].includes(step.status))
121
- step.status = 'cancelled';
122
- this.persist(active);
123
- for (const running of active.running.values())
124
- running.controller.abort();
125
- await Promise.all([...active.running.values()].map(running => running.done));
126
- active.record.finishedAt = Date.now();
127
- this.persist(active);
144
+ await this.stopTree(active, 'cancelled');
128
145
  this.settle(active);
129
146
  return structuredClone(active.record);
130
147
  }
@@ -132,28 +149,16 @@ export class WorkflowScheduler {
132
149
  const active = this.require(sessionId, executionId);
133
150
  if (!occupied(active.record))
134
151
  return structuredClone(active.record);
135
- active.stopped = true;
136
- active.record.status = 'recovery-required';
137
- for (const step of Object.values(active.record.steps)) {
138
- if (step.status !== 'running')
139
- continue;
140
- step.status = 'interrupted';
141
- const attempt = step.attempts.at(-1);
142
- attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
143
- attempt.finishedAt = Date.now();
144
- }
145
- this.persist(active);
146
- for (const running of active.running.values())
147
- running.controller.abort();
148
- await Promise.all([...active.running.values()].map(running => running.done));
152
+ await this.stopTree(active, 'interrupted');
149
153
  this.settle(active);
150
154
  return structuredClone(active.record);
151
155
  }
152
156
  /** replacementDefinition is resolved from saved storage by the host, never from request JSON. */
153
157
  recover(session, executionId, action, replacementDefinition) {
154
- const active = this.require(session.sessionId, executionId);
158
+ const root = this.require(executionOwner(session), executionId);
159
+ const active = action.invocationId ? this.findInvocation(root, action.invocationId) : root;
155
160
  const record = active.record;
156
- if (record.status !== 'recovery-required' || active.running.size)
161
+ if (record.status !== 'recovery-required' || this.hasWork(active))
157
162
  throw new Error('Execution is not ready for recovery');
158
163
  if (record.definition.backend !== session.backend || record.scope !== session.scope)
159
164
  throw new Error('Recovery requires the original Scope and Backend Adapter');
@@ -169,7 +174,7 @@ export class WorkflowScheduler {
169
174
  throw new Error('Replacement definition requires retry-updated');
170
175
  // Check the corrected configuration, not the obsolete one. No checkpoint/graph mutation
171
176
  // happens until compatibility, authority, eligibility and all runtime checks pass.
172
- this.check(graph.order.filter(step => (!record.testStepId || step.id === record.testStepId) && record.steps[step.id].status !== 'completed' && !(action.kind === 'supply' && step.id === action.stepId)), session);
177
+ this.check(recoverySteps(root.record, action, replacementDefinition), session, root.record.retainedDefinitions);
173
178
  const limits = Object.entries(record.loops ?? {}).filter(([, loop]) => loop.phase === 'limit');
174
179
  if (action.kind === 'continue' && limits.length)
175
180
  throw new WorkflowLoopConflict('Loop limit requires an extra try or cancellation');
@@ -191,6 +196,9 @@ export class WorkflowScheduler {
191
196
  throw new Error('Recover the failed handling step, not the handled failure');
192
197
  if (action.kind === 'supply') {
193
198
  const output = this.validateOutput(active, step, action.output);
199
+ this.releaseCancelledCall(active, step.id);
200
+ if (active.calls.has(step.id))
201
+ throw new Error('Cancel the owned call subtree before replacing its output');
194
202
  const attempt = { number: state.attempts.length + 1, action: 'supply', startedAt: Date.now(), finishedAt: Date.now(), input: state.attempts.at(-1).input, output, ...(state.attempts.at(-1).loops ? { loops: structuredClone(state.attempts.at(-1).loops) } : {}) };
195
203
  state.attempts.push(attempt);
196
204
  state.output = output;
@@ -198,7 +206,8 @@ export class WorkflowScheduler {
198
206
  state.outcome = step.kind === 'branch' ? output ? 'true' : 'false' : 'success';
199
207
  }
200
208
  else {
201
- this.check([step], session);
209
+ this.check([step], session, root.record.retainedDefinitions);
210
+ this.releaseCancelledCall(active, step.id);
202
211
  if (action.kind === 'retry-updated') {
203
212
  const previousStep = record.definition.steps.find(previous => previous.id === step.id);
204
213
  (record.definitionUpdates ??= []).push({ stepId: step.id, previousStep: structuredClone(previousStep), nextStep: structuredClone(step), appliedAt: Date.now(), attempt: state.attempts.length + 1 });
@@ -233,14 +242,37 @@ export class WorkflowScheduler {
233
242
  delete record.finishedAt;
234
243
  active.stopped = false;
235
244
  delete active.persistenceError;
245
+ for (let parent = active.parent; parent; parent = parent.parent) {
246
+ parent.stopped = false;
247
+ parent.record.status = 'running';
248
+ delete parent.record.finishedAt;
249
+ }
236
250
  this.persist(active);
251
+ delete root.persistenceError;
252
+ this.resumeCalls(active);
253
+ for (let parent = active.parent; parent; parent = parent.parent)
254
+ this.resumeCalls(parent);
237
255
  this.pump(active);
238
- return structuredClone(record);
256
+ return structuredClone(root.record);
239
257
  }
240
- check(steps, session) {
258
+ check(steps, session, manifest, checked = new Set()) {
241
259
  for (const step of steps) {
242
260
  if (step.kind === 'branch' || step.kind === 'join')
243
261
  continue;
262
+ if (step.kind === 'workflow') {
263
+ const target = manifest?.[step.workflowId];
264
+ if (!target)
265
+ throw new Error('Missing retained called Workflow Definition');
266
+ if (target.backend !== session.backend)
267
+ throw new Error('Backend Adapter mismatch');
268
+ if (target.projectId && !(session.matchesProject?.(target.projectId) ?? target.projectId === session.projectId))
269
+ throw new Error('Workflow is restricted to another Project');
270
+ if (!checked.has(target.id)) {
271
+ checked.add(target.id);
272
+ this.check(target.steps, session, manifest, checked);
273
+ }
274
+ continue;
275
+ }
244
276
  const executor = this.executors[step.kind];
245
277
  if (!executor)
246
278
  throw new Error(`Executor is unavailable: ${step.kind}`);
@@ -248,14 +280,234 @@ export class WorkflowScheduler {
248
280
  }
249
281
  }
250
282
  install(record) {
251
- const active = { record, graph: validateDefinition(record.definition), running: new Map(), waiters: [], stopped: record.status !== 'running' };
283
+ const active = { record, graph: validateDefinition(record.definition), running: new Map(), calls: new Map(), waiters: [], stopped: record.status !== 'running' };
252
284
  this.active.set(record.id, active);
253
- this.slots.set(record.sessionId, record.id);
285
+ this.slots.set(executionOwner(record), record.id);
286
+ const installed = new Map();
287
+ const restore = (id) => {
288
+ const cached = installed.get(id);
289
+ if (cached)
290
+ return cached;
291
+ const invocation = record.invocations[id];
292
+ const parent = invocation.parentInvocationId ? restore(invocation.parentInvocationId) : active;
293
+ const local = invocationExecution(record, id);
294
+ const step = parent.graph.order.find(step => step.id === invocation.callStepId);
295
+ const child = { record: local, graph: validateDefinition(local.definition), parent, root: active, callStepId: invocation.callStepId, callAttempt: invocation.callAttempt,
296
+ inheritedAsk: parent.inheritedAsk || parent.record.definition.permission === 'ask' || step.permission === 'ask', running: new Map(), calls: new Map(), waiters: [], stopped: local.status !== 'running' };
297
+ installed.set(id, child);
298
+ const state = parent.record.steps[invocation.callStepId];
299
+ if (state.attempts.length === invocation.callAttempt && state.status === 'running')
300
+ parent.calls.set(invocation.callStepId, { child });
301
+ return child;
302
+ };
303
+ for (const id of Object.keys(record.invocations ?? {}))
304
+ restore(id);
254
305
  return active;
255
306
  }
307
+ hasWork(active) {
308
+ return active.running.size > 0 || [...active.calls.values()].some(call => !!call.stopping || this.hasWork(call.child));
309
+ }
310
+ findInvocation(active, id) {
311
+ const pending = [active];
312
+ while (pending.length) {
313
+ const current = pending.pop();
314
+ if (current !== active && current.record.id === id)
315
+ return current;
316
+ pending.push(...[...current.calls.values()].map(call => call.child));
317
+ }
318
+ throw new Error('Invocation does not require recovery');
319
+ }
320
+ syncInvocations(active) {
321
+ const root = active.root ?? active;
322
+ for (const call of active.calls.values()) {
323
+ const child = call.child;
324
+ this.syncInvocations(child);
325
+ (root.record.invocations ??= {})[child.record.id] = invocationCheckpoint(child.record, {
326
+ ...(active.parent ? { parentInvocationId: active.record.id } : {}), callStepId: child.callStepId, callAttempt: child.callAttempt, definitionId: child.record.definition.id,
327
+ });
328
+ }
329
+ }
330
+ reconcile(active) {
331
+ if (occupied(active.record)) {
332
+ for (const [id, state] of Object.entries(active.record.steps)) {
333
+ if (state.status !== 'running' || active.calls.has(id))
334
+ continue;
335
+ state.status = 'interrupted';
336
+ const attempt = state.attempts.at(-1);
337
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
338
+ attempt.finishedAt ??= Date.now();
339
+ }
340
+ active.record.status = 'recovery-required';
341
+ active.stopped = !!active.parent?.stopped || Object.values(active.record.steps).some(state => state.status === 'interrupted');
342
+ for (const id of active.calls.keys())
343
+ this.armCall(active, id);
344
+ }
345
+ for (const call of active.calls.values())
346
+ this.reconcile(call.child);
347
+ }
348
+ releaseCancelledCall(active, stepId) {
349
+ const call = active.calls.get(stepId);
350
+ if (call?.child.record.status !== 'cancelled')
351
+ return;
352
+ clearTimeout(call.timer);
353
+ this.syncInvocations(active);
354
+ active.calls.delete(stepId);
355
+ }
356
+ failStorage(active) {
357
+ active.stopped = true;
358
+ if (!active.parent || occupied(active.record))
359
+ active.record.status = 'recovery-required';
360
+ for (const call of active.calls.values()) {
361
+ clearTimeout(call.timer);
362
+ this.failStorage(call.child);
363
+ }
364
+ for (const [id, state] of Object.entries(active.record.steps)) {
365
+ if (state.status !== 'running' || active.calls.has(id))
366
+ continue;
367
+ state.status = 'interrupted';
368
+ const attempt = state.attempts.at(-1);
369
+ attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
370
+ attempt.finishedAt ??= Date.now();
371
+ }
372
+ for (const running of active.running.values())
373
+ running.controller.abort();
374
+ }
375
+ async stopTree(active, reason) {
376
+ const tree = [active];
377
+ for (const current of tree)
378
+ tree.push(...[...current.calls.values()].map(call => call.child));
379
+ for (const current of tree) {
380
+ current.stopped = true;
381
+ if (!occupied(current.record))
382
+ continue;
383
+ current.record.status = reason === 'cancelled' ? 'cancelled' : 'recovery-required';
384
+ for (const [id, state] of Object.entries(current.record.steps)) {
385
+ if (reason === 'cancelled' && ['pending', 'blocked', 'running', 'interrupted'].includes(state.status))
386
+ state.status = 'cancelled';
387
+ else if (reason === 'interrupted' && state.status === 'running' && !current.calls.has(id)) {
388
+ state.status = 'interrupted';
389
+ const attempt = state.attempts.at(-1);
390
+ attempt.error = { kind: 'interrupted', message: 'Execution was interrupted; effects may already have occurred' };
391
+ attempt.finishedAt ??= Date.now();
392
+ }
393
+ }
394
+ }
395
+ const work = tree.flatMap(current => [...current.running.values()]);
396
+ try {
397
+ this.persist(active);
398
+ }
399
+ finally {
400
+ for (const current of tree)
401
+ for (const call of current.calls.values())
402
+ clearTimeout(call.timer);
403
+ for (const running of work)
404
+ running.controller.abort();
405
+ await Promise.all(work.map(running => running.done));
406
+ for (const current of tree)
407
+ if (reason === 'cancelled' && current.record.status === 'cancelled') {
408
+ current.record.finishedAt ??= Date.now();
409
+ for (const state of Object.values(current.record.steps))
410
+ if (state.status === 'cancelled') {
411
+ const attempt = state.attempts.at(-1);
412
+ if (attempt)
413
+ attempt.finishedAt ??= Date.now();
414
+ }
415
+ }
416
+ this.persist(active);
417
+ }
418
+ }
419
+ startCall(active, step, attempt) {
420
+ const root = active.root ?? active;
421
+ const definition = root.record.retainedDefinitions?.[step.workflowId];
422
+ if (!definition)
423
+ throw new Error('Missing retained called Workflow Definition');
424
+ const graph = validateDefinition(definition);
425
+ const record = {
426
+ ...executionIdentity(root.record), id: randomUUID(), scope: root.record.scope, definition: graph.definition,
427
+ input: structuredClone(attempt.input), status: 'running', startedAt: Date.now(),
428
+ steps: Object.fromEntries(graph.order.map(step => [step.id, { status: 'pending', attempts: [] }])),
429
+ loops: Object.fromEntries(graph.loops.map(loop => [loop.headerId, { activation: 0, try: 0, phase: 'inactive', grants: [] }])),
430
+ };
431
+ const child = { record, graph, parent: active, root, callStepId: step.id, callAttempt: attempt.number,
432
+ inheritedAsk: active.inheritedAsk || active.record.definition.permission === 'ask' || step.permission === 'ask',
433
+ running: new Map(), calls: new Map(), waiters: [], stopped: false };
434
+ active.calls.set(step.id, { child });
435
+ if (step.timeoutMs !== undefined)
436
+ attempt.deadlineAt = attempt.startedAt + step.timeoutMs;
437
+ this.persist(active);
438
+ this.armCall(active, step.id);
439
+ if (attempt.deadlineAt === undefined || attempt.deadlineAt > Date.now())
440
+ this.pump(child);
441
+ }
442
+ armCall(active, stepId) {
443
+ const call = active.calls.get(stepId);
444
+ clearTimeout(call.timer);
445
+ const deadline = active.record.steps[stepId].attempts.at(-1).deadlineAt;
446
+ if (deadline === undefined || call.stopping)
447
+ return;
448
+ call.timer = setTimeout(() => {
449
+ call.stopping = this.stopTree(call.child, 'cancelled').then(() => {
450
+ if (active.stopped)
451
+ return;
452
+ const state = active.record.steps[stepId];
453
+ const attempt = state.attempts.at(-1);
454
+ state.status = 'timed-out';
455
+ state.outcome = 'timeout';
456
+ attempt.error = { kind: 'timeout', message: 'Step timed out' };
457
+ attempt.finishedAt = Date.now();
458
+ this.persist(active);
459
+ active.calls.delete(stepId);
460
+ const root = active.root ?? active;
461
+ const resumed = root.record.status === 'recovery-required';
462
+ for (let current = active; current; current = current.parent) {
463
+ current.record.status = 'running';
464
+ delete current.record.finishedAt;
465
+ }
466
+ if (resumed)
467
+ this.onResume?.(structuredClone(root.record));
468
+ this.pump(active);
469
+ }).catch(error => { (active.root ?? active).persistenceError = error; this.failStorage(active.root ?? active); this.settle(active.root ?? active); }).finally(() => { delete call.stopping; });
470
+ }, Math.max(0, deadline - Date.now()));
471
+ }
472
+ resumeCalls(active) {
473
+ for (const [stepId, call] of active.calls) {
474
+ this.armCall(active, stepId);
475
+ if (call.child.record.status === 'completed' || call.child.record.status === 'completed-with-recovery')
476
+ this.completeCall(call.child);
477
+ }
478
+ }
479
+ completeCall(child) {
480
+ const parent = child.parent;
481
+ const stepId = child.callStepId;
482
+ const call = parent.calls.get(stepId);
483
+ if (!call || call.child !== child || call.stopping || parent.stopped)
484
+ return;
485
+ if (child.record.status === 'completed' || child.record.status === 'completed-with-recovery') {
486
+ clearTimeout(call.timer);
487
+ const state = parent.record.steps[stepId];
488
+ const attempt = state.attempts.at(-1);
489
+ const step = parent.graph.order.find(step => step.id === stepId);
490
+ try {
491
+ const output = this.validateOutput(parent, step, child.record.result);
492
+ state.status = 'completed';
493
+ state.outcome = 'success';
494
+ state.output = output;
495
+ attempt.output = output;
496
+ }
497
+ catch (error) {
498
+ state.status = 'failed';
499
+ state.outcome = 'failure';
500
+ attempt.error = { kind: 'failure', message: error instanceof Error ? error.message : String(error) };
501
+ }
502
+ attempt.finishedAt = Date.now();
503
+ this.persist(child);
504
+ parent.calls.delete(stepId);
505
+ }
506
+ this.pump(parent);
507
+ }
256
508
  require(sessionId, executionId) {
257
509
  const active = this.active.get(executionId);
258
- if (!active || active.record.sessionId !== sessionId)
510
+ if (!active || !executionAccessibleBy(active.record, sessionId))
259
511
  throw new Error('Unknown workflow execution');
260
512
  return active;
261
513
  }
@@ -276,8 +528,17 @@ export class WorkflowScheduler {
276
528
  const handled = !state.recovery && active.graph.outgoing.get(edge.from).some(candidate => candidate.outcome === state.outcome);
277
529
  return handled || edge.outcome === 'failure' || edge.outcome === 'timeout' ? 'skipped' : 'blocked';
278
530
  }
531
+ hasExpiredAncestor(active) {
532
+ const now = Date.now();
533
+ for (let child = active; child.parent; child = child.parent) {
534
+ const deadline = child.parent.record.steps[child.callStepId].attempts[child.callAttempt - 1].deadlineAt;
535
+ if (deadline !== undefined && deadline <= now)
536
+ return true;
537
+ }
538
+ return false;
539
+ }
279
540
  pump(active) {
280
- if (active.stopped || active.record.status !== 'running')
541
+ if (active.stopped || active.record.status !== 'running' || this.hasExpiredAncestor(active))
281
542
  return;
282
543
  this.transitionLoops(active);
283
544
  for (const step of active.graph.order) {
@@ -334,23 +595,25 @@ export class WorkflowScheduler {
334
595
  state.attempts.push({ number: state.attempts.length + 1, action: retry ? 'retry' : 'execute', startedAt: Date.now(), input, ...(identities.length ? { loops: identities } : {}) });
335
596
  const done = Promise.resolve().then(() => this.execute(active, step, controller, inputError)).finally(() => {
336
597
  active.running.delete(step.id);
598
+ const root = active.root ?? active;
337
599
  if (active.stopped) {
338
- if (!active.running.size && active.persistenceError)
339
- this.settle(active);
600
+ if (!this.hasWork(root) && root.persistenceError)
601
+ this.settle(root);
340
602
  return;
341
603
  }
342
604
  this.pump(active);
343
605
  }).catch(error => {
344
- active.persistenceError = error;
345
- active.stopped = true;
346
- if (!active.running.size)
347
- this.settle(active);
606
+ const root = active.root ?? active;
607
+ root.persistenceError = error;
608
+ this.failStorage(root);
609
+ if (!this.hasWork(root))
610
+ this.settle(root);
348
611
  });
349
612
  state.status = 'running';
350
613
  active.running.set(step.id, { controller, done });
351
614
  }
352
615
  this.persist(active);
353
- if (active.running.size)
616
+ if (this.hasWork(active))
354
617
  return;
355
618
  if (this.transitionLoops(active)) {
356
619
  this.persist(active);
@@ -358,13 +621,15 @@ export class WorkflowScheduler {
358
621
  return;
359
622
  }
360
623
  const states = Object.entries(active.record.steps);
361
- const unresolved = Object.values(active.record.loops ?? {}).some(loop => loop.phase === 'limit') || states.some(([id, state]) => ['pending', 'interrupted', 'blocked'].includes(state.status) || ((state.status === 'failed' || state.status === 'timed-out') && (active.record.testStepId || state.recovery || !active.graph.outgoing.get(id).some(edge => edge.outcome === state.outcome))));
624
+ const unresolved = active.calls.size > 0 || Object.values(active.record.loops ?? {}).some(loop => loop.phase === 'limit') || states.some(([id, state]) => ['pending', 'interrupted', 'blocked'].includes(state.status) || ((state.status === 'failed' || state.status === 'timed-out') && (active.record.testStepId || state.recovery || !active.graph.outgoing.get(id).some(edge => edge.outcome === state.outcome))));
362
625
  if (unresolved)
363
626
  active.record.status = 'recovery-required';
364
627
  else {
365
628
  const terminals = active.graph.order.filter(step => active.record.steps[step.id].status === 'completed' && (active.record.testStepId || !active.graph.outgoing.get(step.id).some(edge => this.edgeState(active, edge) === 'selected')));
366
629
  active.record.result = terminals.length === 1 ? active.record.steps[terminals[0].id].output : Object.fromEntries(terminals.map(step => [step.name, active.record.steps[step.id].output]));
367
- active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
630
+ const invocations = (active.root ?? active).record.invocations ?? {};
631
+ const descends = (id) => id !== undefined && (id === active.record.id || descends(invocations[id].parentInvocationId));
632
+ active.record.status = Object.values(active.record.loops ?? {}).some(loop => loop.grants.length) || Object.values(invocations).some(invocation => invocation.status === 'completed-with-recovery' && (!active.parent || descends(invocation.parentInvocationId))) || states.some(([, state]) => state.attempts.some(attempt => attempt.error || attempt.action !== 'execute')) ? 'completed-with-recovery' : 'completed';
368
633
  active.record.finishedAt = Date.now();
369
634
  }
370
635
  this.persist(active);
@@ -473,8 +738,13 @@ export class WorkflowScheduler {
473
738
  return copy;
474
739
  }
475
740
  settle(active) {
741
+ if (active.parent) {
742
+ if (!active.stopped)
743
+ this.completeCall(active);
744
+ return;
745
+ }
476
746
  if (!occupied(active.record))
477
- this.slots.delete(active.record.sessionId);
747
+ this.slots.delete(executionOwner(active.record));
478
748
  for (const waiter of active.waiters.splice(0)) {
479
749
  if (active.persistenceError)
480
750
  waiter.reject(active.persistenceError);
@@ -483,23 +753,14 @@ export class WorkflowScheduler {
483
753
  }
484
754
  }
485
755
  persist(active) {
756
+ const root = active.root ?? active;
486
757
  try {
487
- this.store.saveExecution(active.record);
758
+ this.syncInvocations(root);
759
+ this.store.saveExecution(root.record);
488
760
  }
489
761
  catch (error) {
490
- active.persistenceError = error;
491
- active.stopped = true;
492
- active.record.status = 'recovery-required';
493
- for (const step of Object.values(active.record.steps)) {
494
- if (step.status !== 'running')
495
- continue;
496
- step.status = 'interrupted';
497
- const attempt = step.attempts.at(-1);
498
- attempt.error = { kind: 'interrupted', message: 'Workflow storage failed; effects may already have occurred' };
499
- attempt.finishedAt = Date.now();
500
- }
501
- for (const running of active.running.values())
502
- running.controller.abort();
762
+ root.persistenceError = error;
763
+ this.failStorage(root);
503
764
  throw error;
504
765
  }
505
766
  }
@@ -539,6 +800,8 @@ export class WorkflowScheduler {
539
800
  this.persist(active);
540
801
  return;
541
802
  }
803
+ if (this.hasExpiredAncestor(active))
804
+ return;
542
805
  const attempt = state.attempts.at(-1);
543
806
  let timer;
544
807
  let timedOut = false;
@@ -547,7 +810,14 @@ export class WorkflowScheduler {
547
810
  throw inputError;
548
811
  if (step.inputSchema)
549
812
  attempt.input = parseValue(step.inputSchema, attempt.input);
813
+ if (step.kind === 'workflow') {
814
+ attempt.input = parseValue(step.contract.inputSchema, attempt.input);
815
+ this.startCall(active, step, attempt);
816
+ return;
817
+ }
550
818
  this.persist(active);
819
+ if (this.hasExpiredAncestor(active))
820
+ return;
551
821
  const timeout = step.timeoutMs ?? (step.kind === 'shell' || step.kind === 'typescript' || step.kind === 'mcp' ? 60_000 : undefined);
552
822
  if (timeout !== undefined)
553
823
  timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeout);
@@ -578,7 +848,7 @@ export class WorkflowScheduler {
578
848
  }
579
849
  }
580
850
  else
581
- value = await this.executors[step.kind].execute({ sessionId: active.record.sessionId, scope: active.record.scope, executionId: active.record.id, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
851
+ value = await this.executors[step.kind].execute({ owner: executionOwnerOf(active.record), ownerId: executionOwner(active.record), ...(active.record.sessionId ? { sessionId: active.record.sessionId } : {}), ...(active.record.occurrenceId ? { occurrenceId: active.record.occurrenceId } : {}), scope: active.record.scope, executionId: (active.root ?? active).record.id, ...(active.parent ? { invocationId: active.record.id } : {}), attempt: attempt.number, step: this.guidedStep(active, step, attempt), input: structuredClone(attempt.input), inputSchema: active.graph.inputSchemas.get(step.id), permission: active.inheritedAsk ? 'ask' : step.permission ?? active.record.definition.permission ?? 'auto-accept', signal: controller.signal });
582
852
  if (active.stopped)
583
853
  return;
584
854
  if (timedOut)
@@ -600,7 +870,8 @@ export class WorkflowScheduler {
600
870
  }
601
871
  finally {
602
872
  clearTimeout(timer);
603
- attempt.finishedAt ??= Date.now();
873
+ if (!active.calls.has(step.id))
874
+ attempt.finishedAt ??= Date.now();
604
875
  this.persist(active);
605
876
  }
606
877
  }