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

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 (46) hide show
  1. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
  2. package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-COCNALN2.mjs} +36 -6
  3. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-HJKTV2TH.mjs} +35 -3
  4. package/build/backend-worker.mjs +7 -3
  5. package/dist/backend/claude/index.js +35 -5
  6. package/dist/backend/fake/index.js +16 -1
  7. package/dist/backend/pi/index.js +33 -2
  8. package/dist/backend/pi/state.js +16 -1
  9. package/dist/backend/worker/claude-state.js +22 -0
  10. package/dist/backend/worker/entry.js +6 -1
  11. package/dist/backend/worker/index.js +9 -3
  12. package/dist/backend/worker/protocol.js +1 -1
  13. package/dist/backend/workflow-tools.js +9 -7
  14. package/dist/build-id +1 -1
  15. package/dist/cli/bootstrap.js +1 -1
  16. package/dist/client/reduce.js +20 -0
  17. package/dist/daemon/host.js +138 -5
  18. package/dist/daemon/runtime.js +8 -0
  19. package/dist/daemon/workflow-builder-guidance.js +1 -1
  20. package/dist/daemon/workflow-builder.js +36 -11
  21. package/dist/daemon/workflow-execution-routes.js +9 -6
  22. package/dist/daemon/workflow-executions.js +179 -84
  23. package/dist/daemon/workflow-routes.js +39 -0
  24. package/dist/protocol/events.js +2 -0
  25. package/dist/workflows/calls.js +50 -0
  26. package/dist/workflows/graph.js +78 -4
  27. package/dist/workflows/invocations.js +20 -0
  28. package/dist/workflows/records.js +118 -8
  29. package/dist/workflows/recovery.js +37 -1
  30. package/dist/workflows/scheduler.js +326 -78
  31. package/dist/workflows/schema.js +2 -0
  32. package/package.json +1 -1
  33. package/web/dist/assets/index-CLdr6AA0.js +40 -0
  34. package/web/dist/assets/index-DHAcGIoF.css +2 -0
  35. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-sebWClE0.js} +1 -1
  36. package/web/dist/assets/settings-workflows-BvArjkes.js +23 -0
  37. package/web/dist/assets/workflow-editors-Tztq_Opa.js +139 -0
  38. package/web/dist/assets/workflows-CdDynCfW.js +7 -0
  39. package/web/dist/assets/workflows-pane-DaqHEeXu.js +1 -0
  40. package/web/dist/index.html +3 -3
  41. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  42. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  43. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  44. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  45. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  46. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -1,4 +1,6 @@
1
- import { recoveryRevision, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
1
+ import { resolveWorkflowCalls } from "../workflows/calls.js";
2
+ import { invocationExecution } from "../workflows/invocations.js";
3
+ import { recoveryRevision, recoverySteps, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
2
4
  import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../backend/workflow-tools.js";
3
5
  import { redactCredentials } from "./credential-redaction.js";
4
6
  import { workflowAgentNameInput, workflowOutcomeNameInput } from "./summariser.js";
@@ -81,19 +83,7 @@ export class WorkflowExecutionService {
81
83
  check: (step, session) => {
82
84
  if (step.kind !== 'agent')
83
85
  throw new Error('Invalid Agent step');
84
- const backend = host.workflowSession(session.sessionId).session;
85
- if (!backend?.startWorkflowSubagent)
86
- throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
87
- const model = backend.capabilities.models.find(model => model.id === step.model);
88
- if (!model)
89
- throw new Error(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
90
- const levels = model.effortLevels ?? [];
91
- if (levels.length > 0 && !levels.includes(step.effort)) {
92
- throw new Error(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.join(', ')}.`);
93
- }
94
- if (levels.length === 0 && step.effort !== 'off') {
95
- throw new Error(`${model.label ?? model.id} has no Effort control. Re-select the model to use internal off.`);
96
- }
86
+ this.checkAgent(session.sessionId, step);
97
87
  },
98
88
  execute: async (context) => {
99
89
  try {
@@ -104,7 +94,7 @@ export class WorkflowExecutionService {
104
94
  }
105
95
  },
106
96
  },
107
- });
97
+ }, record => this.watch(record));
108
98
  host.workflowOwner = this;
109
99
  this.refresh();
110
100
  }
@@ -170,13 +160,24 @@ export class WorkflowExecutionService {
170
160
  this.host.logFor(sessionId);
171
161
  return { occupied: this.scheduler.occupied(sessionId), executions: this.store.listExecutions(sessionId).map(record => ({ id: record.id, workflowId: record.definition.id, name: record.definition.name, status: record.status, startedAt: record.startedAt, ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), ...(record.testStepId ? { testStepId: record.testStepId } : {}) })) };
172
162
  }
173
- view(sessionId, executionId) {
174
- const execution = this.scheduler.get(sessionId, executionId);
163
+ view(sessionId, executionId, invocationId) {
164
+ const execution = selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), invocationId);
175
165
  const view = this.privateView(sessionId, executionId);
176
- return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
166
+ if (invocationId === undefined)
167
+ return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
168
+ const stepSpend = Object.fromEntries(execution.definition.steps.flatMap(step => {
169
+ const spend = view.stepSpend[spendKey(step.id, invocationId)];
170
+ return spend ? [[step.id, spend]] : [];
171
+ }));
172
+ return redactCredentials(structuredClone({ execution, invocationId, ...view,
173
+ activity: view.activity.filter(item => item.invocationId === invocationId),
174
+ enquiries: view.enquiries.filter(item => item.invocationId === invocationId),
175
+ permissions: view.permissions.filter(item => item.invocationId === invocationId),
176
+ stepSpend, spend: sumSpend(Object.values(stepSpend)),
177
+ }), this.host.workflowMcpCredentials());
177
178
  }
178
179
  async activity(sessionId, executionId, options = {}) {
179
- this.scheduler.get(sessionId, executionId); // ownership check, including historical records
180
+ selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), options.invocationId);
180
181
  const view = this.privateView(sessionId, executionId);
181
182
  const limit = Math.max(1, Math.min(200, options.limit ?? 100));
182
183
  const after = options.after ?? 0;
@@ -186,7 +187,8 @@ export class WorkflowExecutionService {
186
187
  throw new Error('Invalid activity cursor');
187
188
  if (![limit, after, before, options.attempt ?? 1].every(Number.isSafeInteger) || after < 0 || before < 1)
188
189
  throw new Error('Invalid activity cursor');
189
- const belongs = (event) => (!options.stepId || event.stepId === options.stepId) &&
190
+ const belongs = (event) => (options.invocationId === undefined ? !options.stepId || event.invocationId === undefined : event.invocationId === options.invocationId) &&
191
+ (!options.stepId || event.stepId === options.stepId) &&
190
192
  (options.attempt === undefined || event.attempt === options.attempt);
191
193
  const activity = [];
192
194
  const path = this.privatePath(sessionId, executionId) + 'l';
@@ -242,8 +244,7 @@ export class WorkflowExecutionService {
242
244
  }
243
245
  appendActivity(context, view, event, subagentId) {
244
246
  const path = this.privatePath(context.sessionId, context.executionId) + 'l';
245
- const attempt = this.scheduler.get(context.sessionId, context.executionId).steps[context.step.id].attempts.at(-1).number;
246
- const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), stepId: context.step.id, attempt, subagentId, event }, this.host.workflowMcpCredentials());
247
+ const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), ...attemptIdentity(context), subagentId, event }, this.host.workflowMcpCredentials());
247
248
  // Seed a legacy log with exactly what was retained, never invented backfill.
248
249
  if (!existsSync(path)) {
249
250
  this.savePrivate(context.sessionId, context.executionId, view);
@@ -274,10 +275,13 @@ export class WorkflowExecutionService {
274
275
  const record = records.find(record => ['running', 'recovery-required'].includes(record.status)) ?? records[0];
275
276
  return record && this.scheduler.get(sessionId, record.id);
276
277
  }
277
- summary(record) {
278
- const view = this.privateView(record.sessionId, record.id);
279
- return { executionId: record.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
280
- revision: recoveryRevision(record), savedDefinition: this.savedDefinitionSummary(record), automaticRecoveryAvailable: view.automaticAtProgress === undefined || successfulProgress(record) > view.automaticAtProgress,
278
+ summary(root, invocationId) {
279
+ const record = selectWorkflowInvocation(root, invocationId);
280
+ const view = this.privateView(root.sessionId, root.id);
281
+ return { executionId: root.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
282
+ ...(invocationId ? { invocationId } : {}),
283
+ invocations: Object.values(root.invocations ?? {}).map(item => ({ id: item.id, parentInvocationId: item.parentInvocationId, callStepId: item.callStepId, callAttempt: item.callAttempt, workflowId: item.definitionId, status: item.status })),
284
+ revision: recoveryRevision(root), savedDefinition: this.savedDefinitionSummary(record), automaticRecoveryAvailable: view.automaticAtProgress === undefined || successfulProgress(root) > view.automaticAtProgress,
281
285
  steps: Object.entries(record.steps).map(([id, step]) => ({ id, name: record.definition.steps.find(s => s.id === id).name, status: step.status, attempts: step.attempts.length, error: step.attempts.at(-1)?.error })),
282
286
  loops: Object.entries(record.loops ?? {}).map(([id, loop]) => ({ id, phase: loop.phase, activation: loop.activation, try: loop.try })),
283
287
  historyComplete: view.historyComplete === true, };
@@ -296,6 +300,7 @@ export class WorkflowExecutionService {
296
300
  updatedRecoveryDefinition(record, action) {
297
301
  if (action.kind !== 'retry-updated')
298
302
  return undefined;
303
+ record = selectWorkflowInvocation(record, action.invocationId);
299
304
  const definition = this.store.getDefinition(record.definition.id);
300
305
  if (savedDefinitionRevision(definition) !== action.definitionRevision)
301
306
  throw new WorkflowConflict();
@@ -373,34 +378,39 @@ export class WorkflowExecutionService {
373
378
  if (input.section === 'activity')
374
379
  return this.activity(sessionId, record.id, input);
375
380
  if (input.section === 'execution') {
381
+ const selected = selectWorkflowInvocation(record, input.invocationId);
376
382
  let savedDefinition = null;
377
383
  try {
378
- const definition = this.store.getDefinition(record.definition.id);
379
- savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.namingCredentials({ ...record, definition }));
384
+ const definition = this.store.getDefinition(selected.definition.id);
385
+ savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.availableCredentials({ ...selected, definition }));
380
386
  }
381
387
  catch { /* Retained execution remains inspectable if the saved copy was deleted. */ }
382
- return { ...this.view(sessionId, record.id), savedDefinition };
388
+ return { ...this.view(sessionId, record.id, input.invocationId), savedDefinition };
383
389
  }
384
- return redactCredentials(this.summary(record), this.host.workflowMcpCredentials());
390
+ return redactCredentials(this.summary(record, input.invocationId), this.host.workflowMcpCredentials());
385
391
  },
386
392
  recover: async (raw, signal) => {
387
393
  const input = workflowRecoverInput.parse(raw);
394
+ if (input.invocationId !== undefined && input.action.invocationId !== undefined && input.invocationId !== input.action.invocationId)
395
+ throw new Error('Conflicting Workflow invocation selectors');
396
+ const action = { ...input.action, ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }) };
388
397
  const record = this.scheduler.get(sessionId, input.executionId);
389
398
  if (record.status !== 'recovery-required' || recoveryRevision(record) !== input.revision)
390
399
  throw new WorkflowConflict();
391
- const updated = this.updatedRecoveryDefinition(record, input.action);
400
+ const updated = this.updatedRecoveryDefinition(record, action);
392
401
  let authorized = false;
393
402
  if (input.confirm) {
394
- const correction = updated && input.action.kind === 'retry-updated'
395
- ? `\nSaved step configuration to adopt: ${JSON.stringify(updated.steps.find(step => 'stepId' in input.action && step.id === input.action.stepId))}` : '';
396
- const credentials = updated ? [...this.namingCredentials(record), ...this.referencedSecrets(updated, record.testStepId)] : this.referencedSecrets(record.definition, record.testStepId);
397
- authorized = await this.host.confirmWorkflow(sessionId, redactCredentials(`Recover ${record.definition.name}: ${JSON.stringify(input.action)}.${correction} This authorizes only the current execution state and saved definition revision.`, credentials), signal);
403
+ const selected = selectWorkflowInvocation(record, action.invocationId);
404
+ const correction = updated && action.kind === 'retry-updated'
405
+ ? `\nSaved step configuration to adopt: ${JSON.stringify(updated.steps.find(step => 'stepId' in action && step.id === action.stepId))}` : '';
406
+ const credentials = uniqueCredentials([...this.availableCredentials(record, updated ? [updated] : []), ...this.recoveryCredentials(record, action, updated)]);
407
+ authorized = await this.host.confirmWorkflow(sessionId, redactCredentials(`Recover ${selected.definition.name}: ${JSON.stringify(action)}.${correction} This authorizes only the current execution state and saved definition revision.`, credentials), signal);
398
408
  if (!authorized)
399
409
  throw new Error('Recovery was not authorized');
400
410
  }
401
411
  signal?.throwIfAborted();
402
- await this.recover(sessionId, record.id, input.action, { revision: input.revision, authorized, signal });
403
- return this.summary(this.scheduler.get(sessionId, record.id));
412
+ await this.recover(sessionId, record.id, action, { revision: input.revision, authorized, signal });
413
+ return this.summary(this.scheduler.get(sessionId, record.id), action.invocationId);
404
414
  },
405
415
  relayEnquiry: async (raw, signal) => {
406
416
  const input = workflowRelayInput.parse(raw);
@@ -480,18 +490,25 @@ export class WorkflowExecutionService {
480
490
  throw new Error('Workflow is restricted to another Project');
481
491
  if (this.scheduler.occupied(sessionId))
482
492
  throw new WorkflowConflict();
493
+ const manifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id), stepId);
494
+ const definitions = Object.values(manifest);
495
+ for (const candidate of definitions) {
496
+ if (candidate.backend !== identity.backend)
497
+ throw new Error('Backend Adapter mismatch');
498
+ if (candidate.projectId && !sameProject(candidate.projectId, identity.projectId))
499
+ throw new Error('Workflow is restricted to another Project');
500
+ }
483
501
  this.refresh();
484
- const needsCode = definition.steps.some(step => (!stepId || step.id === stepId) && ['shell', 'typescript'].includes(step.kind));
502
+ const selectedSteps = definitions.flatMap(candidate => candidate.steps.filter(step => candidate.id !== definition.id || !stepId || step.id === stepId));
503
+ const needsCode = selectedSteps.some(step => ['shell', 'typescript'].includes(step.kind));
485
504
  const snapshot = needsCode ? await this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code };
486
- const values = this.referencedSecrets(definition, stepId);
487
- assertNoSecrets(publicDefinition(definition), values);
505
+ const values = uniqueCredentials(definitions.flatMap(candidate => this.referencedSecrets(candidate, candidate.id === definition.id ? stepId : undefined)));
506
+ for (const candidate of definitions)
507
+ assertNoSecrets(publicDefinition(candidate), values);
488
508
  assertNoSecrets(input, values, true);
489
509
  const session = await this.host.openWorkflowSession(sessionId);
490
- if (definition.projectId) {
491
- if (!sameProject(definition.projectId, session.projectId))
492
- throw new Error('Workflow is restricted to another Project');
493
- session.projectId = definition.projectId;
494
- }
510
+ if (definition.projectId && !sameProject(definition.projectId, session.projectId))
511
+ throw new Error('Workflow is restricted to another Project');
495
512
  this.host.assertWorkflowSession(sessionId, session.session);
496
513
  const workflowBackend = session.session;
497
514
  if (!workflowBackend)
@@ -499,10 +516,27 @@ export class WorkflowExecutionService {
499
516
  // Confirmed no-control is the sole automatic persisted-effort correction. Do it before the
500
517
  // scheduler validates or records the definition, so old drafts and direct launches both run
501
518
  // with the same internal sentinel the editor applies.
502
- const preparedDefinition = withConfirmedNoControlOff(definition, workflowBackend.capabilities.models);
519
+ const preparedManifest = Object.fromEntries(definitions.map(candidate => [candidate.id, withConfirmedNoControlOff(candidate, workflowBackend.capabilities.models)]));
520
+ const preparedDefinition = preparedManifest[definition.id];
521
+ for (const candidate of definitions) {
522
+ for (const step of candidate.steps) {
523
+ if (candidate.id === definition.id && stepId && step.id !== stepId)
524
+ continue;
525
+ if (step.kind === 'mcp')
526
+ this.checkMcp(sessionId, step.tool);
527
+ if (step.kind === 'agent')
528
+ this.checkAgent(sessionId, preparedManifest[candidate.id].steps.find(item => item.id === step.id));
529
+ if (step.kind === 'shell' || step.kind === 'typescript') {
530
+ const executor = snapshot.code[step.kind];
531
+ if (!executor)
532
+ throw new Error('Workflow runtime is unavailable');
533
+ executor.check(step, session);
534
+ }
535
+ }
536
+ }
503
537
  const pinned = new Map();
504
- for (const step of definition.steps) {
505
- if (step.kind !== 'mcp' || (stepId && step.id !== stepId))
538
+ for (const step of selectedSteps) {
539
+ if (step.kind !== 'mcp')
506
540
  continue;
507
541
  const tools = pinned.get(step.tool.connectionId) ?? [];
508
542
  tools.push(step.tool);
@@ -521,10 +555,13 @@ export class WorkflowExecutionService {
521
555
  }
522
556
  if (this.scheduler.occupied(sessionId))
523
557
  throw new WorkflowConflict();
558
+ const currentManifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id), stepId);
559
+ if (!isDeepStrictEqual(currentManifest, manifest))
560
+ throw new WorkflowConflict();
524
561
  let record;
525
562
  this.checkingCode = snapshot.code;
526
563
  try {
527
- record = this.scheduler.start(preparedDefinition, session, input, stepId, launchId, nameSession && !stepId);
564
+ record = this.scheduler.start(preparedDefinition, { ...session, matchesProject: project => sameProject(project, session.projectId) }, input, stepId, launchId, nameSession && !stepId, preparedManifest);
528
565
  }
529
566
  finally {
530
567
  this.checkingCode = undefined;
@@ -542,17 +579,23 @@ export class WorkflowExecutionService {
542
579
  if (saved.status !== 'recovery-required')
543
580
  throw new WorkflowConflict();
544
581
  const updated = this.updatedRecoveryDefinition(saved, action);
545
- const definition = updated ?? saved.definition;
582
+ const selected = selectWorkflowInvocation(saved, action.invocationId);
583
+ const definition = updated ?? selected.definition;
584
+ const definitions = [saved.definition, ...Object.values(saved.retainedDefinitions ?? {}), ...Object.keys(saved.invocations ?? {}).map(id => invocationExecution(saved, id).definition), definition];
546
585
  const session = await this.host.openWorkflowSession(sessionId);
547
586
  this.privateView(sessionId, executionId);
548
587
  // Pre-toggle records were always restricted. Missing historical policy must never downgrade them.
549
588
  const options = this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
550
- const needsCode = definition.steps.some(step => ['shell', 'typescript'].includes(step.kind));
589
+ const needsCode = definitions.some(candidate => candidate.steps.some(step => ['shell', 'typescript'].includes(step.kind)));
551
590
  const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), isolationMode: options.isolationMode, scope: session.scope, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) }) : {};
552
- if (saved.definition.projectId && !sameProject(saved.definition.projectId, session.projectId))
553
- throw new Error('Workflow is restricted to another Project');
554
- const values = updated ? [...this.namingCredentials(saved), ...this.referencedSecrets(definition, saved.testStepId)] : this.referencedSecrets(definition, saved.testStepId);
555
- assertNoSecrets({ ...saved, definition: publicDefinition(saved.definition), action }, values);
591
+ for (const candidate of definitions) {
592
+ if (candidate.backend !== session.backend)
593
+ throw new Error('Backend Adapter mismatch');
594
+ if (candidate.projectId && !sameProject(candidate.projectId, session.projectId))
595
+ throw new Error('Workflow is restricted to another Project');
596
+ }
597
+ const values = uniqueCredentials([...this.availableCredentials(saved, [definition]), ...this.recoveryCredentials(saved, action, updated)]);
598
+ assertNoSecrets({ ...publicExecutionData(saved), action }, values);
556
599
  if (updated)
557
600
  assertNoSecrets(publicDefinition(updated), values);
558
601
  if (action.kind === 'supply')
@@ -576,9 +619,9 @@ export class WorkflowExecutionService {
576
619
  this.savePrivate(sessionId, executionId, view);
577
620
  }
578
621
  // Re-read after readiness/Revive and human confirmation: saving again revokes consent.
579
- if (updated && savedDefinitionRevision(this.store.getDefinition(saved.definition.id)) !== savedDefinitionRevision(updated))
622
+ if (updated && savedDefinitionRevision(this.store.getDefinition(updated.id)) !== savedDefinitionRevision(updated))
580
623
  throw new WorkflowConflict();
581
- record = this.scheduler.recover(session, executionId, action, updated);
624
+ record = this.scheduler.recover({ ...session, matchesProject: project => sameProject(project, session.projectId) }, executionId, action, updated);
582
625
  }
583
626
  catch (error) {
584
627
  if (error instanceof WorkflowLoopConflict)
@@ -670,7 +713,7 @@ export class WorkflowExecutionService {
670
713
  // never resurrect a canceled or superseded attempt.
671
714
  if (request.kind === 'enquiry' || !request.direct) {
672
715
  const launch = this.launches.get(request.subagentId);
673
- if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.stepId !== request.stepId)
716
+ if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.invocationId !== request.invocationId || launch.stepId !== request.stepId || launch.attempt !== request.attempt)
674
717
  throw new WorkflowConflict();
675
718
  }
676
719
  else {
@@ -735,6 +778,19 @@ export class WorkflowExecutionService {
735
778
  if (oldest && !oldest.announced && !oldest.relaying)
736
779
  this.host.workflowInput(sessionId);
737
780
  }
781
+ checkAgent(sessionId, step) {
782
+ const backend = this.host.workflowSession(sessionId).session;
783
+ if (!backend?.startWorkflowSubagent)
784
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
785
+ const model = backend.capabilities.models.find(model => model.id === step.model);
786
+ if (!model)
787
+ throw new Error(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
788
+ const levels = model.effortLevels ?? [];
789
+ if (levels.length > 0 && !levels.includes(step.effort))
790
+ throw new Error(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.join(', ')}.`);
791
+ if (levels.length === 0 && step.effort !== 'off')
792
+ throw new Error(`${model.label ?? model.id} has no Effort control. Re-select the model to use internal off.`);
793
+ }
738
794
  checkMcp(sessionId, tool) {
739
795
  const connection = this.host.workflowMcpConnections(sessionId).find(connection => connection.id === tool.connectionId);
740
796
  if (!connection || connectionIdentity(connection) !== tool.identity)
@@ -791,13 +847,13 @@ export class WorkflowExecutionService {
791
847
  context.signal.addEventListener('abort', abort, { once: true });
792
848
  const details = redactCredentials(context.input, this.host.workflowMcpCredentials());
793
849
  const scope = 'Allow or deny this direct Workflow tool call once. Standing authorization is unavailable.';
794
- view.permissions.push({ direct: true, subagentId: id, stepId: context.step.id, callId, tool, details, scope });
795
- const execution = this.scheduler.get(context.sessionId, context.executionId);
796
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
850
+ view.permissions.push({ direct: true, subagentId: id, ...attemptIdentity(context), callId, tool, details, scope });
851
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
852
+ const attempt = context.attempt ?? 1;
797
853
  this.registerRelay({
798
854
  kind: 'permission', sessionId: context.sessionId, executionId: context.executionId,
799
- stepId: context.step.id, attempt, subagentId: id, callId, tool, direct: true,
800
- details, scope, context: relayContext(execution, context.step.id, attempt),
855
+ ...attemptIdentity(context), subagentId: id, callId, tool, direct: true,
856
+ details, scope, context: relayContext(execution, context.step.id, attempt, context.invocationId),
801
857
  });
802
858
  this.savePrivate(context.sessionId, context.executionId, view);
803
859
  if (context.signal.aborted)
@@ -876,7 +932,7 @@ export class WorkflowExecutionService {
876
932
  if (!backend?.startWorkflowSubagent)
877
933
  throw new Error('Workflow Backend Session is unavailable');
878
934
  context.signal.throwIfAborted();
879
- const savedStep = this.scheduler.get(context.sessionId, context.executionId).definition.steps.find(step => step.id === context.step.id);
935
+ const savedStep = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId).definition.steps.find(step => step.id === context.step.id);
880
936
  const instructions = savedStep.kind === 'agent' ? savedStep.instructions : context.step.instructions;
881
937
  const invocation = leadingSkillInvocation(instructions);
882
938
  if (invocation) {
@@ -900,7 +956,8 @@ export class WorkflowExecutionService {
900
956
  const values = uniqueCredentials([...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)]);
901
957
  const id = randomUUID();
902
958
  const view = this.privateView(context.sessionId, context.executionId);
903
- const priorSpend = view.stepSpend[context.step.id];
959
+ const key = spendKey(context.step.id, context.invocationId);
960
+ const priorSpend = view.stepSpend[key];
904
961
  const requestIds = new Map();
905
962
  const publicIds = new Map();
906
963
  const publicId = (raw) => {
@@ -921,13 +978,13 @@ export class WorkflowExecutionService {
921
978
  if (event.state !== 'asked')
922
979
  this.dropRelays(request => request.subagentId === id && request.kind === 'enquiry' && request.askId === event.askId, event.state === 'aborted');
923
980
  if (event.state === 'asked') {
924
- view.enquiries.push({ subagentId: id, stepId: context.step.id, askId: event.askId, questions: event.questions });
925
- const execution = this.scheduler.get(context.sessionId, context.executionId);
926
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
981
+ view.enquiries.push({ subagentId: id, ...attemptIdentity(context), askId: event.askId, questions: event.questions });
982
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
983
+ const attempt = context.attempt ?? 1;
927
984
  this.registerRelay({
928
985
  kind: 'enquiry', sessionId: context.sessionId, executionId: context.executionId,
929
- stepId: context.step.id, attempt, subagentId: id, askId: event.askId,
930
- questions: event.questions, context: relayContext(execution, context.step.id, attempt),
986
+ ...attemptIdentity(context), subagentId: id, askId: event.askId,
987
+ questions: event.questions, context: relayContext(execution, context.step.id, attempt, context.invocationId),
931
988
  });
932
989
  }
933
990
  }
@@ -939,19 +996,19 @@ export class WorkflowExecutionService {
939
996
  const started = view.activity.findLast(item => item.event.type === 'tool_started' && item.event.callId === event.callId);
940
997
  const details = started?.event.type === 'tool_started' ? started.event.input : undefined;
941
998
  const scope = `Allow once, deny, or always allow ${event.tool} on this machine.`;
942
- view.permissions.push({ subagentId: id, stepId: context.step.id, callId: event.callId, tool: event.tool, ...(details === undefined ? {} : { details }), scope });
943
- const execution = this.scheduler.get(context.sessionId, context.executionId);
944
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
999
+ view.permissions.push({ subagentId: id, ...attemptIdentity(context), callId: event.callId, tool: event.tool, ...(details === undefined ? {} : { details }), scope });
1000
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
1001
+ const attempt = context.attempt ?? 1;
945
1002
  this.registerRelay({
946
1003
  kind: 'permission', sessionId: context.sessionId, executionId: context.executionId,
947
- stepId: context.step.id, attempt, subagentId: id, callId: event.callId,
1004
+ ...attemptIdentity(context), subagentId: id, callId: event.callId,
948
1005
  tool: event.tool, direct: false, ...(details === undefined ? {} : { details }), scope,
949
- context: relayContext(execution, context.step.id, attempt),
1006
+ context: relayContext(execution, context.step.id, attempt, context.invocationId),
950
1007
  });
951
1008
  }
952
1009
  }
953
1010
  if (event.type === 'spend') {
954
- view.stepSpend[context.step.id] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
1011
+ view.stepSpend[key] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
955
1012
  view.spend = sumSpend(Object.values(view.stepSpend));
956
1013
  }
957
1014
  this.savePrivate(context.sessionId, context.executionId, view);
@@ -971,7 +1028,7 @@ export class WorkflowExecutionService {
971
1028
  await handle.cancel();
972
1029
  throw new Error('Workflow Agent permissions are unavailable');
973
1030
  }
974
- this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, stepId: context.step.id, handle, requestIds });
1031
+ this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, ...attemptIdentity(context), handle, requestIds });
975
1032
  const abort = () => { void handle.cancel().catch(() => { }); };
976
1033
  context.signal.addEventListener('abort', abort, { once: true });
977
1034
  if (context.signal.aborted)
@@ -995,6 +1052,20 @@ export class WorkflowExecutionService {
995
1052
  this.savePrivate(context.sessionId, context.executionId, view);
996
1053
  }
997
1054
  }
1055
+ recoveryCredentials(record, action, updated) {
1056
+ const steps = recoverySteps(record, action, updated);
1057
+ const checked = new Set();
1058
+ for (const step of steps) {
1059
+ if (step.kind !== 'workflow' || checked.has(step.workflowId))
1060
+ continue;
1061
+ checked.add(step.workflowId);
1062
+ const target = record.retainedDefinitions?.[step.workflowId];
1063
+ if (!target)
1064
+ throw new Error('Missing retained called Workflow Definition');
1065
+ steps.push(...target.steps);
1066
+ }
1067
+ return [...new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))].map(name => this.secrets.resolve(name));
1068
+ }
998
1069
  referencedSecrets(definition, stepId) {
999
1070
  return [...this.host.workflowMcpCredentials(), ...[...new Set(definition.steps.filter(step => !stepId || step.id === stepId).flatMap(step => Object.values(step.secrets ?? {})))].map(name => this.secrets.resolve(name))];
1000
1071
  }
@@ -1003,6 +1074,8 @@ export class WorkflowExecutionService {
1003
1074
  const credentials = this.secretValues.get(record.id) ?? [];
1004
1075
  this.publishResult(result, credentials);
1005
1076
  }).catch(() => { }).finally(() => {
1077
+ if (this.scheduler.hasPendingDeadline(record.sessionId, record.id))
1078
+ return;
1006
1079
  this.snapshots.delete(record.id);
1007
1080
  this.secretValues.delete(record.id);
1008
1081
  });
@@ -1017,7 +1090,7 @@ export class WorkflowExecutionService {
1017
1090
  outcome: result.status,
1018
1091
  results,
1019
1092
  errors,
1020
- }, uniqueCredentials([...knownCredentials, ...this.namingCredentials(result)]));
1093
+ }, uniqueCredentials([...knownCredentials, ...this.availableCredentials(result)]));
1021
1094
  });
1022
1095
  }
1023
1096
  if (!result.testStepId && result.status === 'recovery-required')
@@ -1046,13 +1119,15 @@ export class WorkflowExecutionService {
1046
1119
  }
1047
1120
  void this.host.nameWorkflow(sessionId, input).catch(() => { });
1048
1121
  }
1049
- namingCredentials(record) {
1122
+ availableCredentials(record, additional = []) {
1050
1123
  const values = [...this.host.workflowMcpCredentials()];
1051
- for (const reference of new Set(record.definition.steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1124
+ const definitions = [record.definition, ...Object.values(record.retainedDefinitions ?? {}), ...additional];
1125
+ const steps = [...definitions.flatMap(definition => definition.steps), ...[record, ...Object.values(record.invocations ?? {})].flatMap(checkpoint => (checkpoint.definitionUpdates ?? []).flatMap(update => [update.previousStep, update.nextStep]))];
1126
+ for (const reference of new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1052
1127
  try {
1053
1128
  values.push(this.secrets.resolve(reference));
1054
1129
  }
1055
- catch { /* Missing secrets cannot make naming affect execution. */ }
1130
+ catch { }
1056
1131
  }
1057
1132
  return uniqueCredentials(values);
1058
1133
  }
@@ -1161,8 +1236,19 @@ function withConfirmedNoControlOff(definition, models) {
1161
1236
  });
1162
1237
  return changed ? { ...definition, steps } : definition;
1163
1238
  }
1239
+ function publicStep({ secrets, ...step }) { return step; }
1164
1240
  function publicDefinition(definition) {
1165
- return { ...definition, steps: definition.steps.map(({ secrets, ...step }) => step) };
1241
+ return { ...definition, steps: definition.steps.map(publicStep) };
1242
+ }
1243
+ function publicExecutionData(record) {
1244
+ const corrections = (updates) => updates?.map(update => ({ ...update, previousStep: publicStep(update.previousStep), nextStep: publicStep(update.nextStep) }));
1245
+ return {
1246
+ ...record,
1247
+ definition: publicDefinition(record.definition),
1248
+ definitionUpdates: corrections(record.definitionUpdates),
1249
+ retainedDefinitions: record.retainedDefinitions && Object.fromEntries(Object.entries(record.retainedDefinitions).map(([id, definition]) => [id, publicDefinition(definition)])),
1250
+ invocations: record.invocations && Object.fromEntries(Object.entries(record.invocations).map(([id, invocation]) => [id, { ...invocation, definitionUpdates: corrections(invocation.definitionUpdates) }])),
1251
+ };
1166
1252
  }
1167
1253
  function assertNoSecrets(value, secrets, checkKeys = false) {
1168
1254
  const visit = (item) => {
@@ -1206,13 +1292,22 @@ function outcomeNamingData(record) {
1206
1292
  function uniqueCredentials(values) {
1207
1293
  return [...new Set(values.filter(Boolean))];
1208
1294
  }
1209
- function relayContext(record, stepId, attempt) {
1295
+ function relayContext(record, stepId, attempt, invocationId) {
1210
1296
  const step = record.definition.steps.find(item => item.id === stepId);
1211
- return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${record.testStepId ? ' · Step test' : ''}`;
1297
+ return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${invocationId ? ` · Invocation ${invocationId}` : ''}${record.testStepId ? ' · Step test' : ''}`;
1212
1298
  }
1213
1299
  function relaySignal(request, parent) {
1214
1300
  return parent ? AbortSignal.any([request, parent]) : request;
1215
1301
  }
1302
+ function selectWorkflowInvocation(root, invocationId) {
1303
+ return invocationId === undefined ? root : { ...invocationExecution(root, invocationId), id: root.id };
1304
+ }
1305
+ function attemptIdentity(context) {
1306
+ return { stepId: context.step.id, attempt: context.attempt ?? 1, ...(context.invocationId === undefined ? {} : { invocationId: context.invocationId }) };
1307
+ }
1308
+ function spendKey(stepId, invocationId) {
1309
+ return invocationId === undefined ? stepId : JSON.stringify([invocationId, stepId]);
1310
+ }
1216
1311
  function sumSpend(values) {
1217
1312
  const result = { tokens: 0, cached: 0, costUSD: 0, models: [] };
1218
1313
  for (const value of values) {
@@ -1,10 +1,48 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { deriveResultSchema } from "../workflows/calls.js";
1
3
  import { validSecretName } from "../protocol/secrets.js";
2
4
  import { validateDefinition } from "../workflows/graph.js";
5
+ export function workflowCatalogue(workflows) {
6
+ const entries = [];
7
+ const errors = [];
8
+ for (const definition of workflows.listDefinitions()) {
9
+ try {
10
+ entries.push({ id: definition.id, name: definition.name, backend: definition.backend, projectId: definition.projectId, contract: { inputSchema: definition.inputSchema, outputSchema: deriveResultSchema(definition) } });
11
+ }
12
+ catch {
13
+ errors.push({ id: definition.id, name: definition.name, message: 'Saved Workflow Definition is invalid' });
14
+ }
15
+ }
16
+ return { workflows: entries, errors };
17
+ }
18
+ function validateWorkflowContracts(definition, workflows) {
19
+ let original;
20
+ try {
21
+ original = workflows.getDefinition(definition.id);
22
+ }
23
+ catch { }
24
+ const catalogue = workflowCatalogue(workflows).workflows;
25
+ for (const step of definition.steps) {
26
+ if (step.kind !== 'workflow')
27
+ continue;
28
+ const retained = original?.steps.find((candidate) => candidate.id === step.id && candidate.kind === 'workflow');
29
+ if (retained?.workflowId === step.workflowId && isDeepStrictEqual(retained.contract, step.contract))
30
+ continue;
31
+ const selected = catalogue.find(item => item.id === step.workflowId && item.backend === definition.backend);
32
+ if (!selected || !isDeepStrictEqual(selected.contract, step.contract))
33
+ throw new Error(`Workflow step ${step.name} requires a saved host-derived contract`);
34
+ }
35
+ }
3
36
  export function workflowRequestError(error, redact = message => message) {
4
37
  // Redact before truncation: a credential containing ':' must not leak its prefix.
5
38
  return error instanceof Error && error.name !== 'ZodError' && error.name !== 'SyntaxError' && error.message ? redact(error.message).split(':')[0] : 'Invalid workflow request';
6
39
  }
7
40
  export async function workflowRoutes(request, response, pathname, workflows, secrets, executions) {
41
+ if (pathname === '/api/workflow-catalogue') {
42
+ response.writeHead(!workflows ? 404 : request.method === 'GET' ? 200 : 405, { 'content-type': 'application/json' });
43
+ response.end(JSON.stringify(!workflows ? { error: 'Not available' } : request.method === 'GET' ? workflowCatalogue(workflows) : { error: 'Method not allowed' }));
44
+ return true;
45
+ }
8
46
  const match = /^\/api\/(workflows|secrets)(?:\/(.*))?$/.exec(pathname);
9
47
  if (!match)
10
48
  return false;
@@ -81,6 +119,7 @@ export async function workflowRoutes(request, response, pathname, workflows, sec
81
119
  let definition;
82
120
  try {
83
121
  definition = validateDefinition(body).definition;
122
+ validateWorkflowContracts(definition, workflows);
84
123
  executions?.validateDefinitionCredentials(definition);
85
124
  if (definition.id !== id)
86
125
  throw new Error();
@@ -17,4 +17,6 @@ export const HOST_OWNED_EVENT_TYPES = [
17
17
  "session_ended",
18
18
  "branch_changed",
19
19
  "workflow_spend",
20
+ "rewound",
21
+ "forked",
20
22
  ];
@@ -0,0 +1,50 @@
1
+ import { validateDefinition } from "./graph.js";
2
+ function canonical(value) {
3
+ if (Array.isArray(value))
4
+ return value.map(canonical);
5
+ if (value !== null && typeof value === 'object')
6
+ return Object.fromEntries(Object.entries(value).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, canonical(value)]));
7
+ return value;
8
+ }
9
+ export function deriveResultSchema(definition) {
10
+ return validateDefinition(definition).resultSchema;
11
+ }
12
+ export function resolveWorkflowCalls(definition, lookup, testStepId) {
13
+ const retained = new Map();
14
+ const visited = new Set();
15
+ const visit = (candidate, ancestry, selected) => {
16
+ if (ancestry.has(candidate.id))
17
+ throw new Error(`Recursive Workflow call: ${candidate.id}`);
18
+ const graph = validateDefinition(candidate);
19
+ const current = graph.definition;
20
+ if (selected !== undefined && !current.steps.some(step => step.id === selected))
21
+ throw new Error('Unknown test step');
22
+ retained.set(current.id, current);
23
+ const path = new Set([...ancestry, current.id]);
24
+ for (const step of current.steps) {
25
+ if (step.kind !== 'workflow' || (selected !== undefined && step.id !== selected))
26
+ continue;
27
+ if (path.has(step.workflowId))
28
+ throw new Error(`Recursive Workflow call: ${step.workflowId}`);
29
+ let target = retained.get(step.workflowId);
30
+ if (!target) {
31
+ try {
32
+ target = lookup(step.workflowId);
33
+ }
34
+ catch {
35
+ throw new Error(`Missing Workflow call target: ${step.workflowId}`);
36
+ }
37
+ }
38
+ if (!target || target.id !== step.workflowId)
39
+ throw new Error(`Missing Workflow call target: ${step.workflowId}`);
40
+ const called = validateDefinition(target);
41
+ if (JSON.stringify(canonical(step.contract.inputSchema)) !== JSON.stringify(canonical(called.definition.inputSchema)) || JSON.stringify(canonical(step.contract.outputSchema)) !== JSON.stringify(canonical(called.resultSchema)))
42
+ throw new Error(`Workflow call contract does not match target: ${step.workflowId}`);
43
+ if (!visited.has(target.id))
44
+ visit(called.definition, path);
45
+ }
46
+ visited.add(current.id);
47
+ };
48
+ visit(definition, new Set(), testStepId);
49
+ return Object.fromEntries(retained);
50
+ }