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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +27 -1
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
  8. package/build/backend-worker.mjs +52 -116
  9. package/dist/backend/claude/background-calls.js +7 -3
  10. package/dist/backend/claude/index.js +106 -16
  11. package/dist/backend/claude/subagents.js +41 -9
  12. package/dist/backend/fake/index.js +26 -5
  13. package/dist/backend/pi/cache-warming.js +8 -0
  14. package/dist/backend/pi/canonical-json.js +120 -0
  15. package/dist/backend/pi/compaction-model.js +3 -2
  16. package/dist/backend/pi/host-auth.js +258 -0
  17. package/dist/backend/pi/index.js +38 -12
  18. package/dist/backend/pi/model-auth.js +159 -0
  19. package/dist/backend/pi/model-catalog.js +120 -0
  20. package/dist/backend/pi/model-config.js +5 -0
  21. package/dist/backend/pi/model-selection.js +32 -0
  22. package/dist/backend/pi/subagents.js +7 -3
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-subagent.js +4 -3
  25. package/dist/backend/worker/entry.js +32 -6
  26. package/dist/backend/worker/index.js +87 -7
  27. package/dist/backend/worker/rpc.js +13 -0
  28. package/dist/backend/worker/sandbox-mcp.js +18 -7
  29. package/dist/build-id +1 -1
  30. package/dist/cli/bootstrap.js +1 -1
  31. package/dist/client/reduce.js +11 -3
  32. package/dist/client/subagent-tree.js +49 -0
  33. package/dist/client/tool-summary.js +26 -15
  34. package/dist/daemon/git.js +10 -7
  35. package/dist/daemon/host.js +100 -22
  36. package/dist/daemon/models.js +2 -2
  37. package/dist/daemon/pi-model-cache.js +44 -0
  38. package/dist/daemon/runtime.js +63 -3
  39. package/dist/daemon/server.js +3 -0
  40. package/dist/daemon/store.js +2 -0
  41. package/dist/daemon/workflow-environment.js +191 -0
  42. package/dist/daemon/workflow-execution-launch.js +77 -0
  43. package/dist/daemon/workflow-execution-resources.js +76 -0
  44. package/dist/daemon/workflow-execution-values.js +128 -0
  45. package/dist/daemon/workflow-executions.js +272 -285
  46. package/dist/daemon/workflow-schedule-driver.js +247 -0
  47. package/dist/daemon/workflow-schedule-routes.js +137 -0
  48. package/dist/daemon/workflow-schedules.js +341 -0
  49. package/dist/isolation/filesystem.js +5 -1
  50. package/dist/isolation/sandbox.js +61 -18
  51. package/dist/isolation/shared-sandbox.js +3 -3
  52. package/dist/protocol/workflow-schedules.js +1 -0
  53. package/dist/tui/render.js +7 -1
  54. package/dist/workflows/calls.js +10 -7
  55. package/dist/workflows/errors.js +2 -0
  56. package/dist/workflows/executors.js +1 -1
  57. package/dist/workflows/invocations.js +8 -5
  58. package/dist/workflows/owner.js +45 -0
  59. package/dist/workflows/records.js +8 -2
  60. package/dist/workflows/schedule-errors.js +2 -0
  61. package/dist/workflows/schedule-store.js +385 -0
  62. package/dist/workflows/scheduler.js +29 -18
  63. package/dist/workflows/schedules.js +129 -0
  64. package/dist/workflows/store.js +110 -11
  65. package/package.json +8 -5
  66. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  67. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  68. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
  69. package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
  70. package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
  71. package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
  72. package/web/dist/index.html +4 -3
  73. package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
  74. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  75. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  76. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  77. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  78. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  79. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -1,3 +1,13 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, createReadStream, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import { ZodError } from 'zod';
7
+ import { executionOwner } from "../workflows/records.js";
8
+ import { executionOwnerKey, executionOwnerOf } from "../workflows/owner.js";
9
+ import { WorkflowExecutionResources } from "./workflow-execution-resources.js";
10
+ import { prepareWorkflowLaunch } from "./workflow-execution-launch.js";
1
11
  import { resolveWorkflowCalls } from "../workflows/calls.js";
2
12
  import { invocationExecution } from "../workflows/invocations.js";
3
13
  import { recoveryRevision, recoverySteps, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
@@ -7,20 +17,19 @@ import { workflowAgentNameInput, workflowOutcomeNameInput } from "./summariser.j
7
17
  import { connectionIdentity, snapshotTool, sameSchema } from "./workflow-mcp.js";
8
18
  import { validateJsonSchema } from "../workflows/json-schema.js";
9
19
  import { boundedMcpValue, validateMcpSchemas } from "../workflows/mcp.js";
10
- import { createReadStream } from 'node:fs';
11
- import { isDeepStrictEqual } from 'node:util';
12
- import { createInterface } from 'node:readline';
13
- import { randomUUID } from 'node:crypto';
14
- import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
15
- import { join } from 'node:path';
20
+ import { assertNoSecrets, attemptIdentity, confirmedAgentStep, outcomeNamingData, publicDefinition, publicExecutionData, redact, redactEvent, relayContext, relaySignal, safeError, sameProject, selectWorkflowInvocation, spendKey, sumSpend, uniqueCredentials, WorkflowConflict, WorkflowValidationError } from "./workflow-execution-values.js";
16
21
  import { leadingSkillInvocation } from "../protocol/skills.js";
17
22
  import { createCodeExecutors } from "../workflows/executors.js";
18
23
  import { parseValue } from "../workflows/schema.js";
19
24
  import { WorkflowStepError, WorkflowScheduler, WorkflowLoopConflict } from "../workflows/scheduler.js";
20
25
  import { workflowRuntimeOptions } from "../workflows/runtime-settings.js";
21
26
  import { SessionHost } from "./host.js";
27
+ export { WorkflowConflict } from "./workflow-execution-values.js";
22
28
  export class WorkflowExecutionService {
23
29
  scheduler;
30
+ resources;
31
+ onScheduledResult;
32
+ scheduledOwnershipAvailable = true;
24
33
  host;
25
34
  store;
26
35
  secrets;
@@ -42,6 +51,7 @@ export class WorkflowExecutionService {
42
51
  runtimeSnapshots = new Map();
43
52
  runtimeOptions;
44
53
  checkingCode;
54
+ scheduledPublications = new Map();
45
55
  cancelling = new Map();
46
56
  constructor(host, store, secrets, config, runtimePath) {
47
57
  store.redact = value => redactCredentials(value, host.workflowMcpCredentials());
@@ -50,6 +60,7 @@ export class WorkflowExecutionService {
50
60
  this.secrets = secrets;
51
61
  this.config = config;
52
62
  this.runtimePath = runtimePath;
63
+ this.resources = new WorkflowExecutionResources(host, store, runtimePath);
53
64
  const code = (kind) => ({
54
65
  check: (step, session) => {
55
66
  const executor = (this.checkingCode ?? this.code)[kind];
@@ -74,7 +85,7 @@ export class WorkflowExecutionService {
74
85
  check: (step, session) => {
75
86
  if (step.kind !== 'mcp')
76
87
  throw new Error('Invalid MCP step');
77
- this.checkMcp(session.sessionId, step.tool);
88
+ this.checkMcp(executionOwner(session), step.tool);
78
89
  },
79
90
  execute: context => this.mcp(context),
80
91
  },
@@ -83,11 +94,12 @@ export class WorkflowExecutionService {
83
94
  check: (step, session) => {
84
95
  if (step.kind !== 'agent')
85
96
  throw new Error('Invalid Agent step');
86
- this.checkAgent(session.sessionId, step);
97
+ if (session.sessionId)
98
+ this.checkAgent(session.sessionId, step);
87
99
  },
88
100
  execute: async (context) => {
89
101
  try {
90
- return await this.agent(context);
102
+ return await this.agent(await this.attachContext(context));
91
103
  }
92
104
  catch (error) {
93
105
  throw safeError(error, this.secretValues.get(context.executionId) ?? []);
@@ -98,6 +110,48 @@ export class WorkflowExecutionService {
98
110
  host.workflowOwner = this;
99
111
  this.refresh();
100
112
  }
113
+ async attachContext(context) {
114
+ if (context.sessionId)
115
+ return { ...context, sessionId: context.sessionId };
116
+ const identity = executionOwnerOf(context);
117
+ if (identity.kind !== 'occurrence')
118
+ throw new Error('Agent Session required');
119
+ const sessionId = await this.resources.occurrence(executionOwnerKey(identity)).attach();
120
+ context.signal.throwIfAborted();
121
+ this.scheduler.associate(identity.occurrenceId, context.executionId, sessionId);
122
+ return { ...context, sessionId };
123
+ }
124
+ startScheduled(options) { return this.launch({ kind: 'occurrence', options }); }
125
+ async expireScheduled(occurrenceId) {
126
+ const owner = executionOwnerKey({ kind: 'occurrence', occurrenceId });
127
+ while (this.scheduledPublications.has(owner))
128
+ await Promise.allSettled([...this.scheduledPublications.get(owner)]);
129
+ await this.resources.forget(owner);
130
+ this.scheduler.forgetSession(owner);
131
+ for (const record of this.store.listExecutions(owner)) {
132
+ this.views.delete(record.id);
133
+ this.snapshots.delete(record.id);
134
+ this.secretValues.delete(record.id);
135
+ this.runtimeSnapshots.delete(record.id);
136
+ }
137
+ }
138
+ async stopScheduled() {
139
+ const stopped = await Promise.allSettled(this.store.listOwners().filter(owner => owner.kind === 'occurrence').map(owner => this.stop(executionOwnerKey(owner))));
140
+ while (this.scheduledPublications.size)
141
+ await Promise.allSettled([...this.scheduledPublications.values()].flatMap(publications => [...publications]));
142
+ const closed = await Promise.allSettled([this.resources.closeAll()]);
143
+ const errors = [...stopped, ...closed].flatMap(result => result.status === 'rejected' ? [result.reason] : []);
144
+ if (errors.length)
145
+ throw new AggregateError(errors, 'Scheduled work shutdown failed');
146
+ }
147
+ connections(owner) { return this.resources.get(owner).connections(); }
148
+ openMcp(owner, connectionId, mode, signal) {
149
+ return this.resources.get(owner).mcp(connectionId, mode, signal);
150
+ }
151
+ restoreScheduled(record, connectionIds, attach) {
152
+ this.privateView(executionOwner(record), record.id);
153
+ this.resources.restore(record, connectionIds, attach);
154
+ }
101
155
  filesystemPolicy() {
102
156
  const stateRoot = this.host.filesystemStateRoot();
103
157
  return stateRoot ? { stateRoot } : {};
@@ -142,7 +196,7 @@ export class WorkflowExecutionService {
142
196
  const view = this.privateView(sessionId, record.id);
143
197
  if (view.spend)
144
198
  this.host.workflowSpend(sessionId, record.id, view.spend);
145
- if (!view.completionAnnounced)
199
+ if (!record.occurrenceId && !view.completionAnnounced)
146
200
  this.publishResult(record);
147
201
  }
148
202
  }
@@ -243,11 +297,11 @@ export class WorkflowExecutionService {
243
297
  }, this.host.workflowMcpCredentials());
244
298
  }
245
299
  appendActivity(context, view, event, subagentId) {
246
- const path = this.privatePath(context.sessionId, context.executionId) + 'l';
300
+ const path = this.privatePath(executionOwner(context), context.executionId) + 'l';
247
301
  const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), ...attemptIdentity(context), subagentId, event }, this.host.workflowMcpCredentials());
248
302
  // Seed a legacy log with exactly what was retained, never invented backfill.
249
303
  if (!existsSync(path)) {
250
- this.savePrivate(context.sessionId, context.executionId, view);
304
+ this.savePrivate(executionOwner(context), context.executionId, view);
251
305
  const fd = openSync(path, 'wx', 0o600);
252
306
  try {
253
307
  writeFileSync(fd, view.activity.map(item => JSON.stringify(item) + '\n').join(''));
@@ -277,7 +331,7 @@ export class WorkflowExecutionService {
277
331
  }
278
332
  summary(root, invocationId) {
279
333
  const record = selectWorkflowInvocation(root, invocationId);
280
- const view = this.privateView(root.sessionId, root.id);
334
+ const view = this.privateView(executionOwner(root), root.id);
281
335
  return { executionId: root.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
282
336
  ...(invocationId ? { invocationId } : {}),
283
337
  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 })),
@@ -473,106 +527,95 @@ export class WorkflowExecutionService {
473
527
  redactRequestError(message) {
474
528
  return redactCredentials(message, this.host.workflowMcpCredentials());
475
529
  }
476
- validateDefinitionCredentials(definition) {
477
- assertNoSecrets(publicDefinition(definition), this.host.workflowMcpCredentials(), true);
478
- }
479
- async start(options) {
480
- const { sessionId, definition, input, stepId, nameSession = false, launchId } = options;
481
- if (launchId && !stepId) {
482
- const existing = this.store.listExecutions(sessionId).find(record => record.launchId === launchId);
483
- if (existing)
484
- return this.view(sessionId, existing.id);
485
- }
486
- const identity = this.host.workflowSession(sessionId);
487
- if (definition.backend !== identity.backend)
488
- throw new Error('Backend Adapter mismatch');
489
- if (definition.projectId && !sameProject(definition.projectId, identity.projectId))
490
- throw new Error('Workflow is restricted to another Project');
491
- if (this.scheduler.occupied(sessionId))
492
- throw new WorkflowConflict();
493
- const manifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id), stepId);
530
+ async validateScheduledAgents(definition, input, scope, projectId = scope) {
531
+ const manifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id));
494
532
  const definitions = Object.values(manifest);
495
533
  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');
534
+ if (candidate.backend !== definition.backend)
535
+ throw new WorkflowValidationError('Backend Adapter mismatch');
536
+ if (candidate.projectId && !sameProject(candidate.projectId, projectId))
537
+ throw new WorkflowValidationError('Workflow is restricted to another Project');
500
538
  }
501
- this.refresh();
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));
504
- const snapshot = needsCode ? await this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code };
505
- const values = uniqueCredentials(definitions.flatMap(candidate => this.referencedSecrets(candidate, candidate.id === definition.id ? stepId : undefined)));
539
+ try {
540
+ parseValue(definition.inputSchema, input);
541
+ }
542
+ catch (error) {
543
+ if (error instanceof ZodError)
544
+ throw new WorkflowValidationError('Workflow input does not match its schema');
545
+ throw error;
546
+ }
547
+ const values = uniqueCredentials([...this.host.workflowMcpCredentials(), ...definitions.flatMap(candidate => this.referencedSecrets(candidate))]);
506
548
  for (const candidate of definitions)
507
549
  assertNoSecrets(publicDefinition(candidate), values);
508
550
  assertNoSecrets(input, values, true);
509
- const session = await this.host.openWorkflowSession(sessionId);
510
- if (definition.projectId && !sameProject(definition.projectId, session.projectId))
511
- throw new Error('Workflow is restricted to another Project');
512
- this.host.assertWorkflowSession(sessionId, session.session);
513
- const workflowBackend = session.session;
514
- if (!workflowBackend)
515
- throw new Error('Workflow Backend Session is unavailable');
516
- // Confirmed no-control is the sole automatic persisted-effort correction. Do it before the
517
- // scheduler validates or records the definition, so old drafts and direct launches both run
518
- // with the same internal sentinel the editor applies.
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
- }
537
- const pinned = new Map();
538
- for (const step of selectedSteps) {
539
- if (step.kind !== 'mcp')
540
- continue;
541
- const tools = pinned.get(step.tool.connectionId) ?? [];
542
- tools.push(step.tool);
543
- pinned.set(step.tool.connectionId, tools);
544
- }
545
- for (const [connectionId, tools] of pinned)
546
- await this.discoverMcp(sessionId, connectionId, tools, snapshot.runtime.isolationMode);
547
- this.host.assertWorkflowSession(sessionId, session.session);
548
- // All setup above may yield. Resolve an overlapping retry by its durable identity before
549
- // treating the session as occupied, then make occupancy the final check before the synchronous
550
- // scheduler start.
551
- if (launchId && !stepId) {
552
- const existing = this.store.listExecutions(sessionId).find(record => record.launchId === launchId);
553
- if (existing)
554
- return this.view(sessionId, existing.id);
555
- }
556
- if (this.scheduler.occupied(sessionId))
551
+ const agents = definitions.flatMap(candidate => candidate.steps.filter(step => step.kind === 'agent'));
552
+ if (!agents.length)
553
+ return;
554
+ const models = await this.host.workflowAgentModels(scope, definition.backend);
555
+ for (const step of agents)
556
+ this.checkAgentModel(step, models);
557
+ if (!isDeepStrictEqual(resolveWorkflowCalls(definition, id => this.store.getDefinition(id)), manifest))
557
558
  throw new WorkflowConflict();
558
- const currentManifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id), stepId);
559
- if (!isDeepStrictEqual(currentManifest, manifest))
559
+ }
560
+ validateDefinitionCredentials(definition) {
561
+ assertNoSecrets(publicDefinition(definition), this.host.workflowMcpCredentials(), true);
562
+ }
563
+ start(options) { return this.launch({ kind: 'session', options }); }
564
+ async launch(launch) {
565
+ const manual = launch.kind === 'session' ? launch.options : undefined;
566
+ const owner = launch.kind === 'session' ? launch.options.sessionId : executionOwnerKey({ kind: 'occurrence', occurrenceId: launch.options.occurrenceId });
567
+ const existing = () => manual?.launchId && !manual.stepId ? this.store.listExecutions(owner).find(record => record.launchId === manual.launchId) : undefined;
568
+ const prior = existing();
569
+ if (prior)
570
+ return this.view(owner, prior.id);
571
+ if (this.scheduler.occupied(owner))
560
572
  throw new WorkflowConflict();
573
+ this.refresh();
561
574
  let record;
562
- this.checkingCode = snapshot.code;
575
+ let values = [];
563
576
  try {
564
- record = this.scheduler.start(preparedDefinition, { ...session, matchesProject: project => sameProject(project, session.projectId) }, input, stepId, launchId, nameSession && !stepId, preparedManifest);
577
+ const prepared = await prepareWorkflowLaunch(launch, {
578
+ host: this.host, store: this.store, secrets: this.secrets, resources: this.resources, runtimePath: this.runtimePath,
579
+ snapshot: async (needsCode) => needsCode ? this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code },
580
+ discover: (id, connection, tools, mode, signal) => this.discoverMcp(id, connection, tools, mode, signal),
581
+ validateScheduledAgents: (definition, input, scope, projectId) => this.validateScheduledAgents(definition, input, scope, projectId),
582
+ });
583
+ values = prepared.values;
584
+ const raced = existing();
585
+ if (raced)
586
+ return this.view(owner, raced.id);
587
+ if (this.scheduler.occupied(owner))
588
+ throw new WorkflowConflict();
589
+ prepared.assertCurrent();
590
+ this.checkingCode = prepared.code;
591
+ try {
592
+ record = this.scheduler.start(prepared.definition, prepared.session, launch.options.input, manual?.stepId, manual?.launchId, !!manual?.nameSession && !manual.stepId, prepared.manifest);
593
+ }
594
+ finally {
595
+ this.checkingCode = undefined;
596
+ }
597
+ this.secretValues.set(record.id, values);
598
+ this.runtimeSnapshots.set(record.id, prepared.runtime);
599
+ this.snapshots.set(record.id, prepared.code);
600
+ this.privateView(owner, record.id).historyComplete = true;
601
+ this.savePrivate(owner, record.id, this.privateView(owner, record.id));
602
+ this.watch(record);
603
+ return this.view(owner, record.id);
565
604
  }
566
- finally {
567
- this.checkingCode = undefined;
605
+ catch (error) {
606
+ if (launch.kind === 'occurrence') {
607
+ record ??= this.store.listExecutions(owner)[0];
608
+ if (record) {
609
+ const interrupted = await this.scheduler.interrupt(owner, record.id);
610
+ this.watch(interrupted);
611
+ return this.view(owner, record.id);
612
+ }
613
+ await this.resources.forget(owner);
614
+ }
615
+ if (error instanceof WorkflowConflict)
616
+ throw error;
617
+ throw safeError(error, values);
568
618
  }
569
- this.secretValues.set(record.id, values);
570
- this.runtimeSnapshots.set(record.id, snapshot.runtime);
571
- this.privateView(sessionId, record.id).historyComplete = true;
572
- this.savePrivate(sessionId, record.id, this.privateView(sessionId, record.id));
573
- this.snapshots.set(record.id, snapshot.code);
574
- this.watch(record);
575
- return this.view(sessionId, record.id);
576
619
  }
577
620
  async recover(sessionId, executionId, action, authority) {
578
621
  const saved = this.scheduler.get(sessionId, executionId);
@@ -585,9 +628,10 @@ export class WorkflowExecutionService {
585
628
  const session = await this.host.openWorkflowSession(sessionId);
586
629
  this.privateView(sessionId, executionId);
587
630
  // Pre-toggle records were always restricted. Missing historical policy must never downgrade them.
588
- const options = this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
631
+ const options = saved.runtime ?? this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
589
632
  const needsCode = definitions.some(candidate => candidate.steps.some(step => ['shell', 'typescript'].includes(step.kind)));
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) }) : {};
633
+ const resources = this.resources.get(executionOwner(saved));
634
+ const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: () => resources.sandbox(), isolationMode: options.isolationMode, scope: saved.scope, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) }) : {};
591
635
  for (const candidate of definitions) {
592
636
  if (candidate.backend !== session.backend)
593
637
  throw new Error('Backend Adapter mismatch');
@@ -602,26 +646,21 @@ export class WorkflowExecutionService {
602
646
  assertNoSecrets(action.output, values, true);
603
647
  this.secretValues.set(executionId, values);
604
648
  this.host.assertWorkflowSession(sessionId, session.session);
649
+ this.recoveryAuthority(sessionId, executionId, action, authority);
650
+ if (saved.occurrenceId)
651
+ await this.resources.occurrence(executionOwner(saved)).environment.recover(authority?.signal);
605
652
  let record;
606
653
  this.checkingCode = code;
607
654
  try {
608
- if (authority) {
609
- authority.signal?.throwIfAborted();
610
- const current = this.scheduler.get(sessionId, executionId);
611
- if (current.status !== 'recovery-required' || recoveryRevision(current) !== authority.revision)
612
- throw new WorkflowConflict();
613
- const view = this.privateView(sessionId, executionId);
614
- const progress = successfulProgress(current);
615
- if (!authority.authorized && (!safeAutomaticRecovery(current, action) || (view.automaticAtProgress !== undefined && progress <= view.automaticAtProgress)))
616
- throw new Error('User direction required. Explain the failure and proposed recovery, then request confirmation.');
617
- // Persist before launching, so crashes cannot refund an automatic attempt.
618
- view.automaticAtProgress = progress;
619
- this.savePrivate(sessionId, executionId, view);
655
+ const consent = this.recoveryAuthority(sessionId, executionId, action, authority);
656
+ if (consent) {
657
+ consent.view.automaticAtProgress = consent.progress;
658
+ this.savePrivate(sessionId, executionId, consent.view);
620
659
  }
621
660
  // Re-read after readiness/Revive and human confirmation: saving again revokes consent.
622
661
  if (updated && savedDefinitionRevision(this.store.getDefinition(updated.id)) !== savedDefinitionRevision(updated))
623
662
  throw new WorkflowConflict();
624
- record = this.scheduler.recover({ ...session, matchesProject: project => sameProject(project, session.projectId) }, executionId, action, updated);
663
+ record = this.scheduler.recover({ ...session, ...(saved.occurrenceId ? { occurrenceId: saved.occurrenceId } : {}), matchesProject: project => sameProject(project, session.projectId) }, executionId, action, updated);
625
664
  }
626
665
  catch (error) {
627
666
  if (error instanceof WorkflowLoopConflict)
@@ -635,6 +674,19 @@ export class WorkflowExecutionService {
635
674
  this.watch(record);
636
675
  return this.view(sessionId, executionId);
637
676
  }
677
+ recoveryAuthority(sessionId, executionId, action, authority) {
678
+ if (!authority)
679
+ return;
680
+ authority.signal?.throwIfAborted();
681
+ const current = this.scheduler.get(sessionId, executionId);
682
+ if (current.status !== 'recovery-required' || recoveryRevision(current) !== authority.revision)
683
+ throw new WorkflowConflict();
684
+ const progress = successfulProgress(current);
685
+ const view = this.privateView(sessionId, executionId);
686
+ if (!authority.authorized && (!safeAutomaticRecovery(current, action) || (view.automaticAtProgress !== undefined && progress <= view.automaticAtProgress)))
687
+ throw new Error('User direction required. Explain the failure and proposed recovery, then request confirmation.');
688
+ return { view, progress };
689
+ }
638
690
  async cancel(sessionId, executionId) {
639
691
  this.scheduler.get(sessionId, executionId);
640
692
  this.host.cancelWorkflowConfirmation(sessionId);
@@ -650,6 +702,8 @@ export class WorkflowExecutionService {
650
702
  this.cancelling.set(executionId, { sessionId, done });
651
703
  try {
652
704
  await done;
705
+ if (record.occurrenceId)
706
+ await this.resources.close(executionOwner(record));
653
707
  }
654
708
  finally {
655
709
  this.cancelling.delete(executionId);
@@ -660,11 +714,29 @@ export class WorkflowExecutionService {
660
714
  this.host.cancelWorkflowConfirmation(sessionId);
661
715
  await Promise.all([...this.cancelling.values()].filter(item => item.sessionId === sessionId).map(item => item.done));
662
716
  for (const record of this.store.listExecutions(sessionId)) {
663
- if (record.status === 'running' || record.status === 'recovery-required')
664
- await this.scheduler.interrupt(sessionId, record.id);
717
+ if (record.status === 'running' || record.status === 'recovery-required') {
718
+ const interrupted = await this.scheduler.interrupt(sessionId, record.id);
719
+ if (interrupted.occurrenceId)
720
+ await this.onScheduledResult?.(interrupted);
721
+ }
665
722
  }
666
723
  }
724
+ canForget(sessionId, occurrenceId) {
725
+ // Consult durable records: host.load() may reap before scheduler reconciliation.
726
+ const records = this.store.listExecutions(sessionId);
727
+ // Session metadata can precede the checkpoint's association write during attachment.
728
+ if (occurrenceId) {
729
+ const owned = this.store.listExecutions({ kind: 'occurrence', occurrenceId });
730
+ if (!owned.length && !this.scheduledOwnershipAvailable)
731
+ return false;
732
+ records.push(...owned);
733
+ }
734
+ return !records.some(record => record.occurrenceId &&
735
+ (record.status === 'running' || record.status === 'recovery-required'));
736
+ }
667
737
  async forget(sessionId) {
738
+ if (!this.canForget(sessionId))
739
+ throw new WorkflowConflict();
668
740
  await this.stop(sessionId);
669
741
  this.scheduler.forgetSession(sessionId);
670
742
  for (const record of this.store.listExecutions(sessionId)) {
@@ -782,28 +854,36 @@ export class WorkflowExecutionService {
782
854
  const backend = this.host.workflowSession(sessionId).session;
783
855
  if (!backend?.startWorkflowSubagent)
784
856
  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);
857
+ return this.checkAgentModel(step, backend.capabilities.models);
858
+ }
859
+ checkAgentModel(step, models) {
860
+ step = confirmedAgentStep(step, models);
861
+ const model = models.find(model => model.id === step.model);
786
862
  if (!model)
787
- throw new Error(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
863
+ throw new WorkflowValidationError(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
788
864
  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.`);
865
+ if (levels.length ? !levels.includes(step.effort) : step.effort !== 'off')
866
+ throw new WorkflowValidationError(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.length ? levels.join(', ') : 'off'}.`);
867
+ return step;
793
868
  }
794
869
  checkMcp(sessionId, tool) {
795
- const connection = this.host.workflowMcpConnections(sessionId).find(connection => connection.id === tool.connectionId);
870
+ const connection = this.connections(sessionId).find(connection => connection.id === tool.connectionId);
796
871
  if (!connection || connectionIdentity(connection) !== tool.identity)
797
872
  throw new Error('MCP connection removed, disabled or changed. Enable the original connection or reselect the tool in the workflow editor.');
798
873
  validateMcpSchemas(tool);
799
874
  }
800
- async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode()) {
875
+ async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode(), signal) {
801
876
  const pinned = expected ? (Array.isArray(expected) ? expected : [expected]) : [];
802
877
  for (const tool of pinned)
803
878
  this.checkMcp(sessionId, tool);
804
- const session = await this.host.openWorkflowMcp(sessionId, connectionId, isolationMode);
879
+ signal?.throwIfAborted();
880
+ const session = await this.openMcp(sessionId, connectionId, isolationMode, signal);
881
+ const abort = () => { void session.dispose().catch(() => { }); };
882
+ signal?.addEventListener('abort', abort, { once: true });
805
883
  try {
884
+ signal?.throwIfAborted();
806
885
  await session.open();
886
+ signal?.throwIfAborted();
807
887
  if (session.status()[0]?.state !== 'connected')
808
888
  throw new Error('MCP connection unavailable. Sign in in MCP Settings or reconfigure the server, then retry manually.');
809
889
  // Preflight validates only pinned tools, not unrelated advertised schemas.
@@ -830,6 +910,7 @@ export class WorkflowExecutionService {
830
910
  return { tools, errors };
831
911
  }
832
912
  finally {
913
+ signal?.removeEventListener('abort', abort);
833
914
  await session.dispose();
834
915
  }
835
916
  }
@@ -840,7 +921,7 @@ export class WorkflowExecutionService {
840
921
  if (context.permission !== 'ask')
841
922
  return;
842
923
  const id = randomUUID(), callId = randomUUID();
843
- const view = this.privateView(context.sessionId, context.executionId);
924
+ const view = this.privateView(executionOwner(context), context.executionId);
844
925
  const tool = context.step.kind === 'mcp' ? context.step.tool.toolName : 'MCP';
845
926
  const decision = new Promise(resolve => this.directPermissions.set(id, { sessionId: context.sessionId, executionId: context.executionId, callId, resolve }));
846
927
  const abort = () => { this.directPermissions.get(id)?.resolve(false); };
@@ -855,7 +936,7 @@ export class WorkflowExecutionService {
855
936
  ...attemptIdentity(context), subagentId: id, callId, tool, direct: true,
856
937
  details, scope, context: relayContext(execution, context.step.id, attempt, context.invocationId),
857
938
  });
858
- this.savePrivate(context.sessionId, context.executionId, view);
939
+ this.savePrivate(executionOwner(context), context.executionId, view);
859
940
  if (context.signal.aborted)
860
941
  abort();
861
942
  let decided = false;
@@ -873,30 +954,31 @@ export class WorkflowExecutionService {
873
954
  this.directPermissions.delete(id);
874
955
  this.dropRelays(request => request.subagentId === id, !decided);
875
956
  view.permissions = view.permissions.filter(prompt => prompt.subagentId !== id);
876
- this.savePrivate(context.sessionId, context.executionId, view);
957
+ this.savePrivate(executionOwner(context), context.executionId, view);
877
958
  }
878
959
  }
879
960
  async mcp(context) {
880
961
  if (context.step.kind !== 'mcp')
881
962
  throw new Error('Invalid MCP step');
882
963
  const expected = context.step.tool;
883
- this.checkMcp(context.sessionId, expected);
964
+ this.checkMcp(executionOwner(context), expected);
884
965
  validateJsonSchema(expected.inputSchema, context.input);
885
966
  if (!context.input || typeof context.input !== 'object' || Array.isArray(context.input))
886
967
  throw new Error('MCP arguments must be an object');
887
968
  assertNoSecrets(context.input, this.host.workflowMcpCredentials(), true);
888
- await this.mcpPermission(context);
889
- this.checkMcp(context.sessionId, expected);
969
+ if (context.permission === 'ask')
970
+ await this.mcpPermission(await this.attachContext(context));
971
+ this.checkMcp(executionOwner(context), expected);
890
972
  context.signal.throwIfAborted();
891
973
  const isolationMode = this.runtimeSnapshots.get(context.executionId)?.isolationMode ?? 'bubblewrap';
892
- const session = await this.host.openWorkflowMcp(context.sessionId, expected.connectionId, isolationMode);
974
+ const session = await this.openMcp(executionOwner(context), expected.connectionId, isolationMode, context.signal);
893
975
  const abort = () => { void session.dispose(); };
894
976
  context.signal.addEventListener('abort', abort, { once: true });
895
977
  const values = () => [...(this.secretValues.get(context.executionId) ?? []), ...this.host.workflowMcpCredentials()];
896
- const view = this.privateView(context.sessionId, context.executionId);
978
+ const view = this.privateView(executionOwner(context), context.executionId);
897
979
  const activity = (text) => {
898
980
  this.appendActivity(context, view, { type: 'notice', level: 'info', text }, context.step.id);
899
- this.savePrivate(context.sessionId, context.executionId, view);
981
+ this.savePrivate(executionOwner(context), context.executionId, view);
900
982
  };
901
983
  try {
902
984
  await session.open();
@@ -906,7 +988,7 @@ export class WorkflowExecutionService {
906
988
  throw new Error('MCP tool unavailable. Sign in in MCP Settings or reconfigure the original server; retry manually.');
907
989
  if (tool.serverIdentity !== expected.serverIdentity || !sameSchema(tool.definition.inputSchema, expected.inputSchema) || !sameSchema(tool.definition.outputSchema, expected.outputSchema))
908
990
  throw new Error('MCP tool schema changed. Reselect the tool; this execution cannot retarget it.');
909
- this.checkMcp(context.sessionId, expected);
991
+ this.checkMcp(executionOwner(context), expected);
910
992
  activity('Calling MCP directly. No model or tokens. Cancellation is not rollback; remote effects may already occur.');
911
993
  const result = await tool.call(context.input, context.signal, context.step.timeoutMs ?? 60_000);
912
994
  const output = boundedMcpValue({ structuredContent: result.structuredContent ?? null, content: result.content });
@@ -924,9 +1006,10 @@ export class WorkflowExecutionService {
924
1006
  await session.dispose();
925
1007
  }
926
1008
  }
927
- async agent(context) {
928
- if (context.step.kind !== 'agent')
1009
+ async agent(incoming) {
1010
+ if (incoming.step.kind !== 'agent')
929
1011
  throw new Error('Invalid Agent step');
1012
+ const context = { ...incoming, step: this.checkAgent(incoming.sessionId, incoming.step) };
930
1013
  const resolvedInstructions = context.step.instructions;
931
1014
  const backend = this.host.workflowSession(context.sessionId).session;
932
1015
  if (!backend?.startWorkflowSubagent)
@@ -955,7 +1038,7 @@ export class WorkflowExecutionService {
955
1038
  aliases[alias] = this.secrets.resolve(reference, context.signal);
956
1039
  const values = uniqueCredentials([...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)]);
957
1040
  const id = randomUUID();
958
- const view = this.privateView(context.sessionId, context.executionId);
1041
+ const view = this.privateView(executionOwner(context), context.executionId);
959
1042
  const key = spendKey(context.step.id, context.invocationId);
960
1043
  const priorSpend = view.stepSpend[key];
961
1044
  const requestIds = new Map();
@@ -1011,7 +1094,7 @@ export class WorkflowExecutionService {
1011
1094
  view.stepSpend[key] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
1012
1095
  view.spend = sumSpend(Object.values(view.stepSpend));
1013
1096
  }
1014
- this.savePrivate(context.sessionId, context.executionId, view);
1097
+ this.savePrivate(executionOwner(context), context.executionId, view);
1015
1098
  if (event.type === 'spend' && view.spend)
1016
1099
  this.host.workflowSpend(context.sessionId, context.executionId, view.spend);
1017
1100
  },
@@ -1049,7 +1132,7 @@ export class WorkflowExecutionService {
1049
1132
  this.dropRelays(request => request.subagentId === id);
1050
1133
  view.enquiries = view.enquiries.filter(item => item.subagentId !== id);
1051
1134
  view.permissions = view.permissions.filter(item => item.subagentId !== id);
1052
- this.savePrivate(context.sessionId, context.executionId, view);
1135
+ this.savePrivate(executionOwner(context), context.executionId, view);
1053
1136
  }
1054
1137
  }
1055
1138
  recoveryCredentials(record, action, updated) {
@@ -1070,17 +1153,56 @@ export class WorkflowExecutionService {
1070
1153
  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))];
1071
1154
  }
1072
1155
  watch(record) {
1073
- void this.scheduler.wait(record.sessionId, record.id).then(result => {
1156
+ const publication = this.scheduler.wait(executionOwner(record), record.id).then(result => {
1074
1157
  const credentials = this.secretValues.get(record.id) ?? [];
1075
- this.publishResult(result, credentials);
1158
+ return this.publishScheduledResult(result, credentials);
1076
1159
  }).catch(() => { }).finally(() => {
1077
- if (this.scheduler.hasPendingDeadline(record.sessionId, record.id))
1160
+ const owner = executionOwner(record);
1161
+ if (this.scheduler.get(owner, record.id).status === 'running' || this.scheduler.hasPendingDeadline(owner, record.id))
1078
1162
  return;
1079
1163
  this.snapshots.delete(record.id);
1080
1164
  this.secretValues.delete(record.id);
1081
1165
  });
1166
+ if (record.occurrenceId) {
1167
+ const owner = executionOwner(record);
1168
+ const publications = this.scheduledPublications.get(owner) ?? new Set();
1169
+ this.scheduledPublications.set(owner, publications);
1170
+ publications.add(publication);
1171
+ const settled = () => {
1172
+ publications.delete(publication);
1173
+ if (!publications.size)
1174
+ this.scheduledPublications.delete(owner);
1175
+ };
1176
+ void publication.then(settled, settled);
1177
+ }
1178
+ }
1179
+ async publishScheduledResult(result, credentials) {
1180
+ if (result.occurrenceId && result.status === 'recovery-required' && !result.sessionId) {
1181
+ try {
1182
+ const sessionId = await this.resources.occurrence(executionOwner(result)).attach();
1183
+ this.scheduler.associate(result.occurrenceId, result.id, sessionId);
1184
+ result = this.scheduler.get(executionOwner(result), result.id);
1185
+ }
1186
+ catch { }
1187
+ }
1188
+ try {
1189
+ if (result.occurrenceId)
1190
+ await this.onScheduledResult?.(result);
1191
+ if (result.sessionId)
1192
+ this.publishResult(result, credentials);
1193
+ }
1194
+ finally {
1195
+ if (result.occurrenceId) {
1196
+ const owner = executionOwner(result);
1197
+ const current = this.scheduler.get(owner, result.id);
1198
+ if (current.status !== 'running' && current.status !== 'recovery-required' && !this.scheduler.hasPendingDeadline(owner, result.id))
1199
+ await this.resources.close(owner);
1200
+ }
1201
+ }
1082
1202
  }
1083
1203
  publishResult(result, knownCredentials = []) {
1204
+ if (!result.sessionId)
1205
+ return;
1084
1206
  if (!result.testStepId && ['recovery-required', 'completed', 'completed-with-recovery', 'cancelled'].includes(result.status)) {
1085
1207
  this.requestNaming(result.sessionId, result.id, () => {
1086
1208
  const { results, errors } = outcomeNamingData(result);
@@ -1158,14 +1280,15 @@ export class WorkflowExecutionService {
1158
1280
  privatePath(sessionId, executionId) {
1159
1281
  if (![sessionId, executionId].every(value => /^[a-zA-Z0-9_-]+$/.test(value)))
1160
1282
  throw new Error('Invalid execution identity');
1161
- return join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity', executionId + '.json');
1283
+ const record = this.scheduler.get(sessionId, executionId);
1284
+ return join(this.store.ownerPath(executionOwner(record)), 'workflow-activity', executionId + '.json');
1162
1285
  }
1163
1286
  savePrivate(sessionId, executionId, view) {
1164
1287
  const path = this.privatePath(sessionId, executionId);
1165
- const directoryPath = join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity');
1288
+ const directoryPath = join(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'workflow-activity');
1166
1289
  if (!existsSync(directoryPath)) {
1167
- mkdirSync(directoryPath, { mode: 0o700 });
1168
- const parent = openSync(join(this.store.stateRoot, 'sessions', sessionId), 'r');
1290
+ mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
1291
+ const parent = openSync(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'r');
1169
1292
  try {
1170
1293
  fsyncSync(parent);
1171
1294
  }
@@ -1191,139 +1314,3 @@ export class WorkflowExecutionService {
1191
1314
  }
1192
1315
  }
1193
1316
  }
1194
- export class WorkflowConflict extends Error {
1195
- constructor() { super('Workflow decision or slot is no longer available'); }
1196
- }
1197
- function sameProject(project, scope) {
1198
- try {
1199
- return realpathSync(project) === scope;
1200
- }
1201
- catch {
1202
- return false;
1203
- }
1204
- }
1205
- function redact(value, secrets) { return redactCredentials(value, secrets); }
1206
- function redactEvent(event, secrets, publicId) {
1207
- const visit = (item, path = []) => {
1208
- if (typeof item === 'string') {
1209
- const key = path.at(-1);
1210
- if (path.length === 1 && ['type', 'state', 'on', 'decision', 'reason', 'level', 'trigger', 'effort'].includes(key))
1211
- return item;
1212
- if (['id', 'callId', 'askId', 'subagentId', 'turnId'].includes(key) && (path.length === 1 || path[0] === 'producer'))
1213
- return publicId(item);
1214
- return redact(item, secrets);
1215
- }
1216
- if (Array.isArray(item))
1217
- return item.map(value => visit(value, path));
1218
- if (item && typeof item === 'object')
1219
- return Object.fromEntries(Object.entries(item).map(([key, value]) => [key,
1220
- path.length === 0 && ['input', 'update', 'result'].includes(key) ? redact(value, secrets) : visit(value, [...path, key]),
1221
- ]));
1222
- return item;
1223
- };
1224
- return visit(event);
1225
- }
1226
- function withConfirmedNoControlOff(definition, models) {
1227
- let changed = false;
1228
- const steps = definition.steps.map(step => {
1229
- if (step.kind !== 'agent')
1230
- return step;
1231
- const model = models.find(candidate => candidate.id === step.model);
1232
- if (!model || (model.effortLevels?.length ?? 0) > 0 || step.effort === 'off')
1233
- return step;
1234
- changed = true;
1235
- return { ...step, effort: 'off' };
1236
- });
1237
- return changed ? { ...definition, steps } : definition;
1238
- }
1239
- function publicStep({ secrets, ...step }) { return step; }
1240
- function publicDefinition(definition) {
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
- };
1252
- }
1253
- function assertNoSecrets(value, secrets, checkKeys = false) {
1254
- const visit = (item) => {
1255
- if (typeof item === 'string')
1256
- return redact(item, secrets) !== item;
1257
- if (Array.isArray(item))
1258
- return item.some(visit);
1259
- return !!item && typeof item === 'object' && Object.entries(item).some(([key, value]) => (checkKeys && visit(key)) || visit(value));
1260
- };
1261
- if (visit(value))
1262
- throw new Error('Saved workflow data cannot contain secret values');
1263
- }
1264
- function safeError(error, values) {
1265
- const message = redact(error instanceof Error ? error.message : String(error), values);
1266
- return error instanceof WorkflowStepError ? new WorkflowStepError(message, error.partialOutput === undefined ? undefined : redact(error.partialOutput, values)) : new Error(message);
1267
- }
1268
- function outcomeNamingData(record) {
1269
- const stepNames = new Map(record.definition.steps.map(step => [step.id, step.name]));
1270
- function* results() {
1271
- for (const id in record.steps) {
1272
- const output = record.steps[id].output;
1273
- if (output !== undefined)
1274
- yield { step: stepNames.get(id) ?? id, output };
1275
- }
1276
- }
1277
- function* errors() {
1278
- for (const id in record.steps)
1279
- for (const attempt of record.steps[id].attempts) {
1280
- if (attempt.error !== undefined)
1281
- yield {
1282
- step: stepNames.get(id) ?? id, attempt: attempt.number, error: attempt.error,
1283
- ...(attempt.partialOutput === undefined ? {} : { partialOutput: attempt.partialOutput }),
1284
- };
1285
- }
1286
- }
1287
- return {
1288
- results: record.result === undefined ? results() : record.result,
1289
- errors: errors(),
1290
- };
1291
- }
1292
- function uniqueCredentials(values) {
1293
- return [...new Set(values.filter(Boolean))];
1294
- }
1295
- function relayContext(record, stepId, attempt, invocationId) {
1296
- const step = record.definition.steps.find(item => item.id === stepId);
1297
- return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${invocationId ? ` · Invocation ${invocationId}` : ''}${record.testStepId ? ' · Step test' : ''}`;
1298
- }
1299
- function relaySignal(request, parent) {
1300
- return parent ? AbortSignal.any([request, parent]) : request;
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
- }
1311
- function sumSpend(values) {
1312
- const result = { tokens: 0, cached: 0, costUSD: 0, models: [] };
1313
- for (const value of values) {
1314
- result.tokens += value.tokens;
1315
- result.cached += value.cached;
1316
- result.costUSD += value.costUSD;
1317
- for (const model of value.models) {
1318
- const existing = result.models.find(item => item.id === model.id);
1319
- if (existing) {
1320
- existing.tokens += model.tokens;
1321
- existing.cached += model.cached;
1322
- existing.costUSD += model.costUSD;
1323
- }
1324
- else
1325
- result.models.push({ ...model });
1326
- }
1327
- }
1328
- return result;
1329
- }