@proofoftech/flowsafe 0.24.0 → 0.26.0

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 (86) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +6 -4
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +64 -3
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  7. package/dist/agent-host/thread-topology.js +2 -1
  8. package/dist/agent-host/thread-topology.js.map +1 -1
  9. package/dist/agent-runner/durable-agent-runner.d.ts +12 -3
  10. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  11. package/dist/agent-runner/durable-agent-runner.js +217 -102
  12. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  13. package/dist/approval-api/grants.d.ts +11 -1
  14. package/dist/approval-api/grants.d.ts.map +1 -1
  15. package/dist/approval-api/grants.js +20 -0
  16. package/dist/approval-api/grants.js.map +1 -1
  17. package/dist/approval-api/index.d.ts +1 -1
  18. package/dist/approval-api/index.d.ts.map +1 -1
  19. package/dist/approval-api/index.js +1 -1
  20. package/dist/approval-api/index.js.map +1 -1
  21. package/dist/approval-api/retention.d.ts.map +1 -1
  22. package/dist/approval-api/retention.js +6 -5
  23. package/dist/approval-api/retention.js.map +1 -1
  24. package/dist/approval-api/service.d.ts +4 -1
  25. package/dist/approval-api/service.d.ts.map +1 -1
  26. package/dist/approval-api/service.js +12 -5
  27. package/dist/approval-api/service.js.map +1 -1
  28. package/dist/approval-api/types.d.ts +8 -1
  29. package/dist/approval-api/types.d.ts.map +1 -1
  30. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  31. package/dist/background-tasks/d1-storage.js +7 -12
  32. package/dist/background-tasks/d1-storage.js.map +1 -1
  33. package/dist/do-runner/durable-object.d.ts +29 -10
  34. package/dist/do-runner/durable-object.d.ts.map +1 -1
  35. package/dist/do-runner/durable-object.js +56 -33
  36. package/dist/do-runner/durable-object.js.map +1 -1
  37. package/dist/do-runner/fenced-workflow-capability.d.ts +35 -5
  38. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  39. package/dist/do-runner/fenced-workflows-d1.d.ts +8 -0
  40. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  41. package/dist/do-runner/fenced-workflows-d1.js +402 -39
  42. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  43. package/dist/do-runner/index.d.ts +1 -1
  44. package/dist/do-runner/index.d.ts.map +1 -1
  45. package/dist/do-runner/index.js +1 -1
  46. package/dist/do-runner/index.js.map +1 -1
  47. package/dist/do-runner/run-input-depth.d.ts +15 -0
  48. package/dist/do-runner/run-input-depth.d.ts.map +1 -0
  49. package/dist/do-runner/run-input-depth.js +32 -0
  50. package/dist/do-runner/run-input-depth.js.map +1 -0
  51. package/dist/do-runner/run-lifecycle.d.ts +68 -3
  52. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  53. package/dist/do-runner/run-lifecycle.js +76 -12
  54. package/dist/do-runner/run-lifecycle.js.map +1 -1
  55. package/dist/do-runner/runtime.d.ts +46 -9
  56. package/dist/do-runner/runtime.d.ts.map +1 -1
  57. package/dist/do-runner/runtime.js +361 -115
  58. package/dist/do-runner/runtime.js.map +1 -1
  59. package/dist/do-runner/workflow-snapshot-row.d.ts +4 -5
  60. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  61. package/dist/do-runner/workflow-snapshot-row.js +14 -18
  62. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  63. package/dist/host-kit/approval-bridge.d.ts +20 -2
  64. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  65. package/dist/host-kit/approval-bridge.js +66 -7
  66. package/dist/host-kit/approval-bridge.js.map +1 -1
  67. package/dist/host-kit/do-run-topology.d.ts +3 -1
  68. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  69. package/dist/host-kit/do-run-topology.js +2 -1
  70. package/dist/host-kit/do-run-topology.js.map +1 -1
  71. package/dist/host-kit/flowsafe-worker.d.ts +6 -1
  72. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  73. package/dist/host-kit/flowsafe-worker.js +2 -2
  74. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  75. package/dist/host-kit/host-approval-service.d.ts +3 -1
  76. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  77. package/dist/host-kit/host-approval-service.js.map +1 -1
  78. package/dist/host-kit/run-router.d.ts +4 -1
  79. package/dist/host-kit/run-router.d.ts.map +1 -1
  80. package/dist/host-kit/run-router.js +14 -0
  81. package/dist/host-kit/run-router.js.map +1 -1
  82. package/dist/schedules/tick.d.ts +28 -2
  83. package/dist/schedules/tick.d.ts.map +1 -1
  84. package/dist/schedules/tick.js +35 -11
  85. package/dist/schedules/tick.js.map +1 -1
  86. package/package.json +2 -2
@@ -23,7 +23,7 @@
23
23
  // functions, so throwing refusals preserve the durable-agent brand.
24
24
  //
25
25
  // Signal senders and queueMessage stay inherited because their starts reach
26
- // executeWorkflow's refusal for ids absent from #startRequesters, preserving
26
+ // executeWorkflow's refusal for ids absent from #pendingStarts, preserving
27
27
  // the input verdict and publishing terminal ERROR.
28
28
  //
29
29
  // AgentThreadStreamRuntime's idle wake, continuation and queued-signal drains
@@ -51,11 +51,13 @@
51
51
  // runtime.resume().
52
52
  import { isCreatedAgentSignal, isDurableAgentLike, isMastraSignalMessage, isTransientSignalMessage, MessageList, mastraDBMessageToSignal, signalToMastraDBMessage, } from '@mastra/core/agent';
53
53
  import { AGENT_STREAM_TOPIC, DurableAgent, globalRunRegistry, prepareForDurableExecution, } from '@mastra/core/agent/durable';
54
+ import { MastraTimeoutError } from '@mastra/core/loop';
54
55
  import { isExecutionPrincipalId, isExecutionPrincipalKind, } from '../approval-api/principal.js';
55
56
  import { DoStatusError } from '../do-runner/do-status-error.js';
56
57
  import { normalizeMutationEpoch, normalizeStartIdentity, } from '../do-runner/execution-admission.js';
57
58
  import { InvalidRunRequestError, isPathSafeId, RunStateUnreadableError, } from '../do-runner/index.js';
58
59
  import { resourceIdFromKey } from '../do-runner/memory-id.js';
60
+ import { runTerminalError, terminalStatusOfLegAbort, } from '../do-runner/run-lifecycle.js';
59
61
  import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
60
62
  import { captureReservation, } from '../do-runner/start-reservation-contract.js';
61
63
  class AgentAuthorizationDeniedError extends DoStatusError {
@@ -265,7 +267,7 @@ const INSTALLED_SERVICE_REASON = "it installs memory or pub/sub after constructi
265
267
  * Why direct aborts are refused. Homed once: both bypass the terminate route's
266
268
  * ownership and disputed-settlement checks.
267
269
  */
268
- const DIRECT_ABORT_REASON = "a direct abort bypasses the terminate route's ownership check and disputed-settlement refusal, stops running tools, and can reach another thread's run in the isolate through core's global run registry; cancel through the terminate route";
270
+ const DIRECT_ABORT_REASON = "a direct abort bypasses the terminate route's ownership check and disputed-settlement refusal, and can reach another thread's run in the isolate through core's global run registry; cancel through the terminate route";
269
271
  const GUARDED_CALLBACK_REASON = "it receives what the call's stream delivers; on the durable loop the saved message and the returned result are not filtered by the output policies";
270
272
  const GUARDED_OBSERVABILITY_REASON = 'observability only';
271
273
  const GUARDED_REENTRY_REASON = "Mastra's own re-entry options for its idle loop and background-task wait";
@@ -634,6 +636,72 @@ function bindResumedLegLifecycle(output, leg) {
634
636
  },
635
637
  });
636
638
  }
639
+ // The rehydrated registry entry bypasses core's private budget installer, so a
640
+ // resumed leg composes `modelSettings.timeout.totalMs` with its abort signal
641
+ // here, with the same pass-through rule and timeout reason as core's
642
+ // createTimeoutAbortSignal. The parent listener stays attached after cleanup,
643
+ // which also runs when core evicts the entry mid-leg and must not unlink the
644
+ // leg's own abort.
645
+ function composeTotalBudget(parent, totalMs) {
646
+ if (typeof totalMs !== 'number' ||
647
+ !Number.isFinite(totalMs) ||
648
+ totalMs <= 0) {
649
+ return { signal: parent, cleanup: () => undefined };
650
+ }
651
+ const controller = new AbortController();
652
+ const timer = setTimeout(() => {
653
+ controller.abort(new MastraTimeoutError({ timeoutType: 'total', timeoutMs: totalMs }));
654
+ }, totalMs);
655
+ // Node's timer handle has unref; the Workers runtime returns a number.
656
+ timer.unref?.();
657
+ const onParentAbort = () => controller.abort(parent.reason);
658
+ if (parent.aborted)
659
+ onParentAbort();
660
+ else
661
+ parent.addEventListener('abort', onParentAbort, { once: true });
662
+ return {
663
+ signal: controller.signal,
664
+ cleanup: () => clearTimeout(timer),
665
+ };
666
+ }
667
+ /**
668
+ * The terminal ERROR a leg's run stream ends with when its run ended other
669
+ * than successfully. An engine cancel publishes no terminal event of its own,
670
+ * and the stream's consumers and Mastra's cleanup of the run wait for one. A
671
+ * leg cut in this isolate reads as the engine's `canceled`, so its abort
672
+ * reason names the transition that cut it.
673
+ */
674
+ function legTerminalError(summary, failedMessage, legSignal) {
675
+ if (summary.status === 'failed')
676
+ return new Error(summary.error ?? failedMessage);
677
+ const status = summary.status === 'canceled'
678
+ ? (terminalStatusOfLegAbort(legSignal?.reason) ?? 'cancelled')
679
+ : summary.status === 'cancelled' || summary.status === 'timed_out'
680
+ ? summary.status
681
+ : undefined;
682
+ return status ? endedRunError(status, summary.error) : undefined;
683
+ }
684
+ function endedRunError(status, storedError) {
685
+ const { name, message } = runTerminalError(status);
686
+ return Object.assign(new Error(storedError ?? message), { name });
687
+ }
688
+ function threadLegOutcome(status) {
689
+ return status === 'success'
690
+ ? 'success'
691
+ : status === 'canceled' || status === 'cancelled'
692
+ ? 'canceled'
693
+ : 'failed';
694
+ }
695
+ function isRecord(value) {
696
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
697
+ }
698
+ function persistedModelSettings(workflowInput) {
699
+ if (!isRecord(workflowInput) || !isRecord(workflowInput.options)) {
700
+ return undefined;
701
+ }
702
+ const { modelSettings } = workflowInput.options;
703
+ return isRecord(modelSettings) ? modelSettings : undefined;
704
+ }
637
705
  /**
638
706
  * Brand marking an agent as runtime-driven. The thread Durable Object requires
639
707
  * it before a wake seam may start a run.
@@ -672,18 +740,10 @@ export class FlowsafeDurableAgent extends DurableAgent {
672
740
  #guardedCallOptionMapper;
673
741
  #threadRuntime;
674
742
  #resumedThreadLegs = new Map();
675
- #persistenceWaiters = new Map();
676
- #startRequesters = new Map();
677
- #startRequesterKinds = new Map();
678
- #startAttemptTokens = new Map();
679
- /**
680
- * runId -> the reservation key the thread topology took for this start, so
681
- * `executeWorkflow` can hand it to `RunnerRuntime.start` for the execution
682
- * fence's proof-only match.
683
- */
684
- #startIdempotencyKeys = new Map();
685
- #startAuthorities = new Map();
686
- #startScheduleDispatches = new Map();
743
+ // Registry entries whose run's terminal ERROR this isolate published or is
744
+ // publishing, so a later release cleans them without publishing a second one.
745
+ #endedEntries = new WeakSet();
746
+ #pendingStarts = new Map();
687
747
  // The host's exact options object receives one private, single-use re-entry ticket.
688
748
  #hostStreamTickets = new WeakSet();
689
749
  // The created signal of a start with neither a host ticket nor a request
@@ -762,7 +822,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
762
822
  }
763
823
  /**
764
824
  * Refuse every run id that is still registered on any start or core seam.
765
- * `#startRequesters` alone is insufficient because `streamUntilPersisted()`
825
+ * `#pendingStarts` alone is insufficient because `streamUntilPersisted()`
766
826
  * removes it after the first summary while a suspended stream stays live.
767
827
  * The internal registry has no TTL, so it also covers long suspensions after
768
828
  * the global registry's TTL expires.
@@ -778,8 +838,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
778
838
  }
779
839
  /** @internal */
780
840
  isRunLive(runId) {
781
- return (this.#startRequesters.has(runId) ||
782
- this.#persistenceWaiters.has(runId) ||
841
+ return (this.#pendingStarts.has(runId) ||
783
842
  globalRunRegistry.has(runId) ||
784
843
  this.runRegistryInternal.has(runId));
785
844
  }
@@ -880,17 +939,15 @@ export class FlowsafeDurableAgent extends DurableAgent {
880
939
  reject = rejectPromise;
881
940
  });
882
941
  void persisted.catch(() => undefined);
883
- this.#persistenceWaiters.set(runId, { resolve, reject });
884
- this.#startRequesters.set(runId, requestedBy);
885
- this.#startRequesterKinds.set(runId, requestedByKind);
886
- this.#startAttemptTokens.set(runId, attemptToken);
887
- this.#startAuthorities.set(runId, capturedAuthority);
888
- if (capturedScheduleDispatch) {
889
- this.#startScheduleDispatches.set(runId, capturedScheduleDispatch);
890
- }
891
- if (idempotencyKey !== undefined) {
892
- this.#startIdempotencyKeys.set(runId, idempotencyKey);
893
- }
942
+ this.#pendingStarts.set(runId, Object.freeze({
943
+ attemptToken,
944
+ authority: capturedAuthority,
945
+ ...(capturedScheduleDispatch
946
+ ? { scheduleDispatch: capturedScheduleDispatch }
947
+ : {}),
948
+ ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
949
+ persisted: { resolve, reject },
950
+ }));
894
951
  const onError = callOptions.onError;
895
952
  try {
896
953
  const hostCallOptions = {
@@ -908,13 +965,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
908
965
  return result;
909
966
  }
910
967
  finally {
911
- this.#persistenceWaiters.delete(runId);
912
- this.#startRequesters.delete(runId);
913
- this.#startRequesterKinds.delete(runId);
914
- this.#startAttemptTokens.delete(runId);
915
- this.#startScheduleDispatches.delete(runId);
916
- this.#startIdempotencyKeys.delete(runId);
917
- this.#startAuthorities.delete(runId);
968
+ this.#pendingStarts.delete(runId);
918
969
  }
919
970
  }
920
971
  /**
@@ -1280,9 +1331,12 @@ export class FlowsafeDurableAgent extends DurableAgent {
1280
1331
  return typeof value === 'function' ? value.bind(target) : value;
1281
1332
  },
1282
1333
  });
1283
- const preparationOptions = options.memory !== undefined
1334
+ const preparationOptions = options.memory !== undefined || options.modelSettings !== undefined
1284
1335
  ? {
1285
- memory: options.memory,
1336
+ ...(options.memory !== undefined ? { memory: options.memory } : {}),
1337
+ ...(options.modelSettings !== undefined
1338
+ ? { modelSettings: options.modelSettings }
1339
+ : {}),
1286
1340
  }
1287
1341
  : undefined;
1288
1342
  const preparation = await prepareForDurableExecution({
@@ -1303,21 +1357,28 @@ export class FlowsafeDurableAgent extends DurableAgent {
1303
1357
  preparation.registryEntry.inputProcessors = inputProcessors;
1304
1358
  preparation.registryEntry.llmRequestInputProcessors =
1305
1359
  llmRequestInputProcessors;
1360
+ const budget = composeTotalBudget(options.abortController.signal, preparation.registryEntry.timeoutTotalMs);
1306
1361
  let cleaned = false;
1307
1362
  const cleanup = () => {
1308
1363
  if (cleaned)
1309
1364
  return;
1310
1365
  cleaned = true;
1366
+ budget.cleanup();
1311
1367
  preparation.registryEntry.cleanup?.();
1312
1368
  };
1313
1369
  const registryEntry = {
1314
1370
  ...preparation.registryEntry,
1371
+ abortController: options.abortController,
1372
+ abortSignal: budget.signal,
1315
1373
  cleanup,
1316
1374
  };
1317
1375
  this.runRegistryInternal.registerWithMessageList(options.runId, registryEntry, preparation.messageList, {
1318
1376
  threadId: preparation.threadId,
1319
1377
  resourceId: preparation.resourceId,
1320
1378
  });
1379
+ // The cache does not dispose an entry that `set` replaces (noDisposeOnSet),
1380
+ // and the previous leg's entry holds Mastra's abort-request subscription.
1381
+ globalRunRegistry.delete(options.runId);
1321
1382
  globalRunRegistry.set(options.runId, {
1322
1383
  ...registryEntry,
1323
1384
  messageList: preparation.messageList,
@@ -1340,20 +1401,28 @@ export class FlowsafeDurableAgent extends DurableAgent {
1340
1401
  : options.memory;
1341
1402
  let rehydrated = false;
1342
1403
  let leg;
1404
+ const legAbort = new AbortController();
1343
1405
  try {
1344
1406
  const summary = await this.#runtime.resume(this.getWorkflow().id, options.runId, {
1345
1407
  ...(options.step !== undefined ? { step: options.step } : {}),
1346
1408
  ...(options.resumeData !== undefined
1347
1409
  ? { resumeData: options.resumeData }
1348
1410
  : {}),
1411
+ ...(options.expectedSuspension !== undefined
1412
+ ? { expectedSuspension: options.expectedSuspension }
1413
+ : {}),
1349
1414
  requestedBy: options.requestedBy,
1350
1415
  requestedByKind: 'human',
1351
- prepareExecution: async (requestContext) => {
1416
+ legAbort,
1417
+ prepareExecution: async (requestContext, workflowInput) => {
1352
1418
  const offset = (await this.pubsub.getHistory(AGENT_STREAM_TOPIC(options.runId))).length;
1419
+ const modelSettings = persistedModelSettings(workflowInput);
1353
1420
  await this.#rehydrateRegistry({
1354
1421
  runId: options.runId,
1355
1422
  requestContext,
1423
+ abortController: legAbort,
1356
1424
  ...(memory !== undefined ? { memory } : {}),
1425
+ ...(modelSettings !== undefined ? { modelSettings } : {}),
1357
1426
  });
1358
1427
  rehydrated = true;
1359
1428
  const observed = await this.observe(options.runId, { offset });
@@ -1366,33 +1435,41 @@ export class FlowsafeDurableAgent extends DurableAgent {
1366
1435
  }
1367
1436
  },
1368
1437
  });
1369
- if (summary.status === 'failed') {
1370
- await this.#publishTerminalError(options.runId, new Error(summary.error ?? 'Durable agent workflow resume failed'));
1371
- this.runRegistryInternal.cleanup(options.runId);
1372
- globalRunRegistry.delete(options.runId);
1373
- }
1374
- if (isTerminalRunStatus(summary.status)) {
1375
- this.#completeResumedThreadLegs(options.runId, summary.status === 'success'
1376
- ? 'success'
1377
- : summary.status === 'canceled' || summary.status === 'cancelled'
1378
- ? 'canceled'
1379
- : 'failed');
1380
- }
1381
- else if (leg) {
1438
+ const terminalError = legTerminalError(summary, 'Durable agent workflow resume failed', legAbort.signal);
1439
+ if (terminalError)
1440
+ await this.#endRunLocally(options.runId, terminalError, threadLegOutcome(summary.status));
1441
+ else if (isTerminalRunStatus(summary.status))
1442
+ this.#completeResumedThreadLegs(options.runId, threadLegOutcome(summary.status));
1443
+ else if (leg)
1382
1444
  leg.outcome = 'suspended';
1383
- }
1384
1445
  return summary;
1385
1446
  }
1386
1447
  catch (error) {
1387
- if (rehydrated) {
1388
- await this.#publishTerminalError(options.runId, error);
1389
- this.runRegistryInternal.cleanup(options.runId);
1390
- globalRunRegistry.delete(options.runId);
1391
- this.#completeResumedThreadLegs(options.runId, 'failed');
1392
- }
1448
+ if (rehydrated)
1449
+ await this.#endRunLocally(options.runId, error, 'failed');
1393
1450
  throw error;
1394
1451
  }
1395
1452
  }
1453
+ /**
1454
+ * @internal Ends this isolate's state for a run whose stored status a
1455
+ * terminate or deadline settled, publishing its terminal ERROR unless a leg
1456
+ * here already did. A run with a start still pending here, one this isolate
1457
+ * holds nothing for, or one whose status is not cancelled or timed out, is
1458
+ * left to its own path.
1459
+ */
1460
+ async releaseEndedRun(runId) {
1461
+ this.#assertCallerRunId(runId);
1462
+ const holdsRun = () => !this.#pendingStarts.has(runId) && this.isRunLive(runId);
1463
+ if (!holdsRun())
1464
+ return;
1465
+ const summary = await this.#runtime.authoritativeStatus(this.getWorkflow().id, runId);
1466
+ // Mastra's delayed cleanup of a run whose leg published can run during the
1467
+ // read; a release past it would publish a second terminal ERROR.
1468
+ if ((summary?.status !== 'cancelled' && summary?.status !== 'timed_out') ||
1469
+ !holdsRun())
1470
+ return;
1471
+ await this.#endRunLocally(runId, endedRunError(summary.status, summary.error), threadLegOutcome(summary.status));
1472
+ }
1396
1473
  #trackResumedLeg(runId) {
1397
1474
  let complete;
1398
1475
  const completion = new Promise((resolve) => {
@@ -1418,19 +1495,34 @@ export class FlowsafeDurableAgent extends DurableAgent {
1418
1495
  }
1419
1496
  }
1420
1497
  async #settleRefusedStart(runId, refusal) {
1421
- let published = false;
1498
+ this.#replayedSignals.delete(runId);
1499
+ if (!(await this.#endRunLocally(runId, refusal, 'failed', 2)))
1500
+ throw refusal;
1501
+ }
1502
+ /**
1503
+ * End this isolate's state for a run: publish its terminal ERROR unless it
1504
+ * was published or is being published for the current registry entry,
1505
+ * release both run registries, complete its resumed thread legs. Publishing
1506
+ * comes first: `emitError()` ends spans through the live global registry
1507
+ * entry. Resolves `false` only when every publication attempt failed.
1508
+ */
1509
+ async #endRunLocally(runId, error, outcome, attempts = 1) {
1510
+ const entry = this.runRegistryInternal.get(runId);
1511
+ let published = entry !== undefined && this.#endedEntries.has(entry);
1512
+ if (entry)
1513
+ this.#endedEntries.add(entry);
1422
1514
  try {
1423
- published =
1424
- (await this.#publishTerminalError(runId, refusal)) ||
1425
- (await this.#publishTerminalError(runId, refusal));
1515
+ for (let attempt = 0; !published && attempt < attempts; attempt++)
1516
+ published = await this.#publishTerminalError(runId, error);
1517
+ if (!published && entry)
1518
+ this.#endedEntries.delete(entry);
1426
1519
  }
1427
1520
  finally {
1428
- this.#replayedSignals.delete(runId);
1429
1521
  this.runRegistryInternal.cleanup(runId);
1430
1522
  globalRunRegistry.delete(runId);
1523
+ this.#completeResumedThreadLegs(runId, outcome);
1431
1524
  }
1432
- if (!published)
1433
- throw refusal;
1525
+ return published;
1434
1526
  }
1435
1527
  /**
1436
1528
  * Publish one terminal ERROR attempt without throwing. Call sites publish
@@ -1679,24 +1771,17 @@ export class FlowsafeDurableAgent extends DurableAgent {
1679
1771
  */
1680
1772
  async executeWorkflow(runId, workflowInput) {
1681
1773
  this.#assertCallerRunId(runId);
1682
- const waiter = this.#persistenceWaiters.get(runId);
1774
+ const start = this.#pendingStarts.get(runId);
1775
+ // stream() composes a caller's abortSignal into this controller and
1776
+ // registers it before this method runs; every model and tool call of the
1777
+ // leg reads a signal derived from it.
1778
+ const entry = this.runRegistryInternal.get(runId);
1779
+ const legAbort = entry?.abortController;
1683
1780
  let summary;
1684
1781
  try {
1685
- // getWorkflow() is memoized and its id is the shared loop id the factory
1686
- // registered; driving that exact id keeps the started run and the
1687
- // registered workflow in lockstep.
1688
- const requestedBy = this.#startRequesters.get(runId);
1689
- const requestedByKind = this.#startRequesterKinds.get(runId);
1690
- const attemptToken = this.#startAttemptTokens.get(runId);
1691
- const scheduleDispatch = this.#startScheduleDispatches.get(runId);
1692
- const idempotencyKey = this.#startIdempotencyKeys.get(runId);
1693
- const authority = this.#startAuthorities.get(runId);
1694
- if (requestedBy === undefined || requestedByKind === undefined) {
1695
- if (requestedBy !== undefined || requestedByKind !== undefined) {
1696
- throw new InvalidRunRequestError('requestedBy and requestedByKind must be provided together');
1697
- }
1698
- // No #startRequesters entry means the host start seam never registered
1699
- // this id, so core minted it below our boundary. Such a run has no
1782
+ if (start === undefined) {
1783
+ // No pending start means the host start seam never registered this
1784
+ // id, so core minted it below our boundary. Such a run has no
1700
1785
  // ownership record or trusted engine-leg context. Preserve what the
1701
1786
  // input chain's verdict allows, including a signal stream() captured
1702
1787
  // for this id, then close the stream so core can clean up its maps and
@@ -1709,9 +1794,7 @@ export class FlowsafeDurableAgent extends DurableAgent {
1709
1794
  return;
1710
1795
  }
1711
1796
  const { runId: coreRunId, agentId: coreAgentId, ...payload } = workflowInput;
1712
- if (!authority) {
1713
- throw new InvalidRunRequestError('registered run is missing agent start authority');
1714
- }
1797
+ const { authority } = start;
1715
1798
  if (coreRunId !== runId ||
1716
1799
  authority.startIdentity.target.id !== this.#wrappedAgent.id ||
1717
1800
  coreAgentId !== authority.startIdentity.target.id) {
@@ -1719,44 +1802,76 @@ export class FlowsafeDurableAgent extends DurableAgent {
1719
1802
  }
1720
1803
  // The agent registry retains the preparation refusal when the isolate-wide
1721
1804
  // registry evicts its entry before the first step.
1722
- if (this.runRegistryInternal.get(runId)?.tripwire?.processorId ===
1723
- BREAKWATER_RBAC_PROCESSOR_ID) {
1805
+ if (entry?.tripwire?.processorId === BREAKWATER_RBAC_PROCESSOR_ID) {
1724
1806
  const refusal = new AgentAuthorizationDeniedError();
1725
- // The waiter's first rejection wins; publishing ERROR first supplies a
1807
+ // The start's first rejection wins; publishing ERROR first supplies a
1726
1808
  // plain Error that doErrorResponse maps to 500.
1727
- waiter?.reject(refusal);
1809
+ start.persisted.reject(refusal);
1728
1810
  await this.#settleRefusedStart(runId, refusal);
1729
1811
  return;
1730
1812
  }
1813
+ if (legAbort === undefined) {
1814
+ console.error(JSON.stringify({ type: 'agent-leg-abort-unavailable', runId }));
1815
+ }
1816
+ // Mastra's total budget hands the leg's calls a signal whose link to this
1817
+ // controller its own cleanup removes, and that cleanup also runs when the
1818
+ // isolate-wide registry evicts the entry mid-leg; a signal linked to both
1819
+ // keeps the leg's abort reaching the calls that already read it.
1820
+ if (entry?.abortSignal &&
1821
+ legAbort &&
1822
+ entry.abortSignal !== legAbort.signal) {
1823
+ const linked = AbortSignal.any([entry.abortSignal, legAbort.signal]);
1824
+ entry.abortSignal = linked;
1825
+ const shared = globalRunRegistry.get(runId);
1826
+ if (shared)
1827
+ shared.abortSignal = linked;
1828
+ }
1829
+ // getWorkflow() is memoized and its id is the shared loop id the factory
1830
+ // registered; driving that exact id keeps the started run and the
1831
+ // registered workflow in lockstep.
1731
1832
  const workflow = this.getWorkflow();
1732
1833
  summary = await this.#runtime.start(workflow.id, {
1733
1834
  runId,
1734
1835
  inputData: { ...payload, runId: coreRunId, agentId: coreAgentId },
1735
- ...(attemptToken === undefined ? {} : { attemptToken }),
1736
- ...(scheduleDispatch === undefined ? {} : { scheduleDispatch }),
1737
- ...(idempotencyKey === undefined ? {} : { idempotencyKey }),
1738
- requestedBy,
1739
- requestedByKind,
1836
+ attemptToken: start.attemptToken,
1837
+ ...(start.scheduleDispatch === undefined
1838
+ ? {}
1839
+ : { scheduleDispatch: start.scheduleDispatch }),
1840
+ ...(start.idempotencyKey === undefined
1841
+ ? {}
1842
+ : { idempotencyKey: start.idempotencyKey }),
1843
+ requestedBy: authority.startIdentity.owner.id,
1844
+ requestedByKind: authority.startIdentity.owner.kind,
1740
1845
  mutationEpoch: authority.mutationEpoch,
1741
1846
  startIdentity: authority.startIdentity,
1742
1847
  agentStart: authority.agentStart,
1743
1848
  onPreparedStartIdentity: authority.onPreparedStartIdentity,
1744
1849
  runOwnerGuard: authority.runOwnerGuard,
1745
1850
  startReservation: authority.startReservation,
1851
+ ...(legAbort === undefined ? {} : { legAbort }),
1746
1852
  });
1747
- waiter?.resolve();
1853
+ start.persisted.resolve();
1748
1854
  }
1749
1855
  catch (error) {
1750
- waiter?.reject(error);
1856
+ start?.persisted.reject(error);
1751
1857
  throw error;
1752
1858
  }
1753
- // Mirror the base: a FAILED run emits an error onto the agent's stream so
1754
- // observe()/onError see it. A SUSPENDED run is the approval-gate path — it
1755
- // returns normally and the host bridges the suspension to the approval
1756
- // queue. emitError publishes on this.pubsub, which the constructor defaults
1757
- // to the runtime's identity so the event reaches the run's observers.
1758
- if (summary.status === 'failed') {
1759
- await this.emitError(runId, new Error(summary.error ?? 'Durable agent workflow execution failed'));
1859
+ // See legTerminalError. Mastra's start stream cleans its registries once
1860
+ // the ERROR reaches it, so the start path publishes without releasing.
1861
+ const terminalError = legTerminalError(summary, 'Durable agent workflow execution failed', legAbort?.signal);
1862
+ if (terminalError && !(entry && this.#endedEntries.has(entry))) {
1863
+ // The host's waiter already resolved, so a release can race this
1864
+ // publication; the entry is claimed before it is awaited.
1865
+ if (entry)
1866
+ this.#endedEntries.add(entry);
1867
+ try {
1868
+ await this.emitError(runId, terminalError);
1869
+ }
1870
+ catch (error) {
1871
+ if (entry)
1872
+ this.#endedEntries.delete(entry);
1873
+ throw error;
1874
+ }
1760
1875
  }
1761
1876
  }
1762
1877
  }