@proofoftech/flowsafe 0.21.0 → 0.23.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 (77) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +25 -12
  3. package/dist/agent-host/catalog.d.ts.map +1 -1
  4. package/dist/agent-host/catalog.js +5 -2
  5. package/dist/agent-host/catalog.js.map +1 -1
  6. package/dist/agent-host/thread-host.d.ts +16 -0
  7. package/dist/agent-host/thread-host.d.ts.map +1 -1
  8. package/dist/agent-host/thread-host.js +108 -58
  9. package/dist/agent-host/thread-host.js.map +1 -1
  10. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  11. package/dist/agent-host/thread-topology.js +11 -9
  12. package/dist/agent-host/thread-topology.js.map +1 -1
  13. package/dist/agent-runner/durable-agent-runner.d.ts +134 -96
  14. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  15. package/dist/agent-runner/durable-agent-runner.js +424 -282
  16. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  17. package/dist/approval-api/actor-context.js +3 -3
  18. package/dist/approval-api/actor-context.js.map +1 -1
  19. package/dist/approval-api/service.d.ts +6 -9
  20. package/dist/approval-api/service.d.ts.map +1 -1
  21. package/dist/approval-api/service.js +6 -9
  22. package/dist/approval-api/service.js.map +1 -1
  23. package/dist/background-tasks/d1-storage.js +1 -1
  24. package/dist/background-tasks/d1-storage.js.map +1 -1
  25. package/dist/background-tasks/host.d.ts.map +1 -1
  26. package/dist/background-tasks/host.js +3 -2
  27. package/dist/background-tasks/host.js.map +1 -1
  28. package/dist/do-runner/d1-storage.d.ts +4 -2
  29. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  30. package/dist/do-runner/d1-storage.js +4 -2
  31. package/dist/do-runner/d1-storage.js.map +1 -1
  32. package/dist/do-runner/durable-object.d.ts.map +1 -1
  33. package/dist/do-runner/durable-object.js +22 -22
  34. package/dist/do-runner/durable-object.js.map +1 -1
  35. package/dist/do-runner/execution-context.d.ts +5 -1
  36. package/dist/do-runner/execution-context.d.ts.map +1 -1
  37. package/dist/do-runner/execution-context.js +5 -1
  38. package/dist/do-runner/execution-context.js.map +1 -1
  39. package/dist/do-runner/execution-fence.js +2 -2
  40. package/dist/do-runner/execution-fence.js.map +1 -1
  41. package/dist/do-runner/run-lifecycle.js +6 -6
  42. package/dist/do-runner/run-lifecycle.js.map +1 -1
  43. package/dist/do-runner/runtime.d.ts +23 -47
  44. package/dist/do-runner/runtime.d.ts.map +1 -1
  45. package/dist/do-runner/runtime.js +61 -68
  46. package/dist/do-runner/runtime.js.map +1 -1
  47. package/dist/do-runner/start-idempotency.js +4 -4
  48. package/dist/do-runner/start-idempotency.js.map +1 -1
  49. package/dist/host-kit/approval-bridge.d.ts +8 -8
  50. package/dist/host-kit/approval-bridge.js +8 -8
  51. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  52. package/dist/host-kit/flowsafe-worker.js +5 -0
  53. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  54. package/dist/schedules/schedules-d1.js +1 -1
  55. package/dist/schedules/tick.d.ts +1 -8
  56. package/dist/schedules/tick.d.ts.map +1 -1
  57. package/dist/schedules/tick.js +8 -19
  58. package/dist/schedules/tick.js.map +1 -1
  59. package/dist/signals/client.d.ts +7 -4
  60. package/dist/signals/client.d.ts.map +1 -1
  61. package/dist/signals/client.js +9 -7
  62. package/dist/signals/client.js.map +1 -1
  63. package/dist/signals/d1-shared.js +1 -1
  64. package/dist/signals/index.d.ts +1 -1
  65. package/dist/signals/index.d.ts.map +1 -1
  66. package/dist/signals/index.js.map +1 -1
  67. package/dist/signals/notification-dispatch.d.ts +1 -12
  68. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  69. package/dist/signals/notification-dispatch.js +0 -53
  70. package/dist/signals/notification-dispatch.js.map +1 -1
  71. package/dist/signals/thread-do-routes.d.ts +48 -9
  72. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  73. package/dist/signals/thread-do-routes.js +411 -230
  74. package/dist/signals/thread-do-routes.js.map +1 -1
  75. package/package.json +14 -9
  76. package/scripts/seed-deployment-identity.mjs +25 -11
  77. package/patches/@mastra__core@1.53.0.patch +0 -54
@@ -1,6 +1,8 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
+ import { isCreatedAgentSignal } from '@mastra/core/agent';
2
3
  import { AGENT_STREAM_TOPIC, globalRunRegistry, } from '@mastra/core/agent/durable';
3
4
  import { Mastra } from '@mastra/core/mastra';
5
+ import { assertAcceptedCallProviderOptions, assertNoGuardedSystemMessages, } from '@proofoftech/breakwater/agent';
4
6
  import { isPrincipalPermissions } from '@proofoftech/breakwater/rbac';
5
7
  import { AgentRunSelectorMismatchError, } from '../agent-runner/durable-agent-runner.js';
6
8
  import { AGENT_ENTRY_PATHS, AGENT_RUN_STORAGE_KEY_PREFIX, bindAgentThread, createFlowsafeDurableAgent, deleteAgentRunRecord, deleteAgentThreadBinding, readAgentRunRecord, readAgentThreadBinding, writeAgentRunRecord, } from '../agent-runner/index.js';
@@ -11,7 +13,7 @@ import { DoStatusError, isPathSafeId, resolveScheduleStartOwner, resourceIdFromK
11
13
  import { isDefinitiveInitialAdmissionRefusal } from '../do-runner/initial-admission-refusal.js';
12
14
  import { mastraRegistryEntries } from '../do-runner/mastra-registry.js';
13
15
  import { lifecycleFromRequestContext, terminalCleanupFor, } from '../do-runner/run-lifecycle.js';
14
- import { isTerminalRunStatus } from '../do-runner/run-terminal-state.js';
16
+ import { isTerminalRunStatus, } from '../do-runner/run-terminal-state.js';
15
17
  import { captureReservation, sameReservationIdentity, } from '../do-runner/start-reservation-contract.js';
16
18
  import { persistedStartRecord } from '../host-kit/do-response.js';
17
19
  import { abandonApprovalsForRun, reconcileApprovalsForSummary, } from '../host-kit/index.js';
@@ -145,13 +147,13 @@ function requestedBy(value) {
145
147
  return value;
146
148
  }
147
149
  /**
148
- * The reserved suspension-timeout envelope is minted by a run object's alarm and
149
- * by nothing else. Agent runs never arm a suspension deadline, so a forged
150
+ * The reserved suspension-timeout envelope is minted by a run object's alarm.
151
+ * Agent runs never arm a suspension deadline, so a forged
150
152
  * envelope here could only mislead a step — but this route forwards client
151
153
  * resume data verbatim under `requestedByKind: 'human'`, and the guarantee the
152
154
  * feature sells is that no caller can present itself to a step as an expired
153
- * deadline. The KEY is refused, exactly as the workflow resume route refuses it,
154
- * so a step that reads the key directly cannot be fooled either.
155
+ * deadline. The KEY is refused, so a step that reads the key directly cannot be
156
+ * fooled either.
155
157
  */
156
158
  function resumeData(value) {
157
159
  if (value !== null &&
@@ -305,11 +307,11 @@ export function createThreadAgentHost(options) {
305
307
  return runtime;
306
308
  };
307
309
  /**
308
- * The one entry gate, split by principal kind because the two kinds are
310
+ * The entry gate, split by principal kind because the two kinds are
309
311
  * authorized by different things and must not fall through to each other.
310
312
  *
311
313
  * A human passes the route-level start roles intersected with the agent's own
312
- * allowedRoles, exactly as before. An automated principal never consults
314
+ * allowedRoles. An automated principal never consults
313
315
  * roles at all: it must be declared in the agent's `allowedAutomation` for
314
316
  * this precise entry path, AND survive the host's optional authorizer. Absent
315
317
  * declaration denies — which is why a scheduled start of an agent that has
@@ -451,25 +453,30 @@ export function createThreadAgentHost(options) {
451
453
  return undefined;
452
454
  for (const key of records.keys()) {
453
455
  const runId = key.slice(AGENT_RUN_STORAGE_KEY_PREFIX.length);
454
- const record = await readRun(runId);
455
- if (!record)
456
+ const runRecord = await readRun(runId);
457
+ if (!runRecord)
456
458
  continue;
457
459
  if (executions.has(runId))
458
- return { runId, principal: record.principal };
460
+ return { runId, principal: runRecord.principal };
459
461
  const state = await selectedAgentState(scope, {
460
- agentId: record.agentId,
462
+ agentId: runRecord.agentId,
461
463
  resourceId: resourceIdFromKey(scope.threadId),
462
464
  runId,
463
465
  }, { includeLegacy: true });
464
- if (!state ||
465
- state.kind === 'initial' ||
466
- !isTerminalRunStatus(state.summary.status) ||
466
+ if (!state || state.kind === 'initial')
467
+ return { runId, principal: runRecord.principal };
468
+ const blocking = {
469
+ runId,
470
+ principal: runRecord.principal,
471
+ status: state.summary.status,
472
+ };
473
+ if (!isTerminalRunStatus(state.summary.status) ||
467
474
  (state.kind === 'legacy' && !isTerminalRunStatus(state.snapshot.status)))
468
- return { runId, principal: record.principal };
475
+ return blocking;
469
476
  const recovery = await storage.get(ownerRecoveryKey(runId));
470
477
  if (recovery !== undefined)
471
- return { runId, principal: record.principal };
472
- await withRecoveryLock(() => finalizeTerminalRecord(scope, runId, record, state));
478
+ return blocking;
479
+ await withRecoveryLock(() => finalizeTerminalRecord(scope, runId, runRecord, state));
473
480
  }
474
481
  return undefined;
475
482
  };
@@ -509,14 +516,14 @@ export function createThreadAgentHost(options) {
509
516
  }
510
517
  if (!threaded)
511
518
  throw new AgentHostRequestError(404, 'run not found');
512
- const [threadOwner, resourceOwner] = await Promise.all([
519
+ const [threadOwner, resolvedResourceOwner] = await Promise.all([
513
520
  ownership.owner('thread', ref.threadId),
514
521
  ownership.owner('resource', ref.resourceId),
515
522
  ]);
516
523
  if (!threadOwner ||
517
- !resourceOwner ||
518
- threadOwner.kind !== resourceOwner.kind ||
519
- threadOwner.id !== resourceOwner.id) {
524
+ !resolvedResourceOwner ||
525
+ threadOwner.kind !== resolvedResourceOwner.kind ||
526
+ threadOwner.id !== resolvedResourceOwner.id) {
520
527
  throw new AgentHostRequestError(404, 'run not found');
521
528
  }
522
529
  return { owner: threadOwner };
@@ -909,7 +916,7 @@ export function createThreadAgentHost(options) {
909
916
  // The bridge mints its own principal from this id, so the audit trail shows
910
917
  // an automated principal rather than a human operator.
911
918
  const systemPrincipalId = options.systemPrincipalId ?? 'flowsafe-system';
912
- // Deliberately NOT vouched. Its only consumer projects it to an ApprovalActor
919
+ // NOT vouched. Its consumer projects it to an ApprovalActor
913
920
  // for a role-gated READ, which grants nothing an automated principal does not
914
921
  // already have — so calling the trust assertion here would assert trust that
915
922
  // nothing consumes, and `trustAutomationPrincipal` has to stay greppable as
@@ -943,12 +950,12 @@ export function createThreadAgentHost(options) {
943
950
  runId: summary.runId,
944
951
  }, principalActor(systemPrincipal()));
945
952
  const keys = new Set((summary.suspended ?? []).map((path) => path.join('.')));
946
- return records.filter((record) => {
947
- const key = record.stepPath?.join('.');
953
+ return records.filter((runRecord) => {
954
+ const key = runRecord.stepPath?.join('.');
948
955
  return (key !== undefined &&
949
956
  keys.has(key) &&
950
- record.suspendedAt === summary.suspendedAt?.[key] &&
951
- record.resumeCount === summary.resumeCount?.[key]);
957
+ runRecord.suspendedAt === summary.suspendedAt?.[key] &&
958
+ runRecord.resumeCount === summary.resumeCount?.[key]);
952
959
  });
953
960
  };
954
961
  const envelopeFor = async (scope, ref, principal, summary) => {
@@ -1110,13 +1117,13 @@ export function createThreadAgentHost(options) {
1110
1117
  throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1111
1118
  }
1112
1119
  const storage = options.stateStorage();
1113
- const binding = await readBinding(), record = await readRun(stored.runId);
1120
+ const binding = await readBinding(), runRecord = await readRun(stored.runId);
1114
1121
  await assertRecoveryCurrent(stored);
1115
1122
  const matches = binding?.agentId === stored.agentId &&
1116
1123
  binding.resourceId === stored.resourceId;
1117
- if (record && !sameRunRecord(record, stored.runRecord))
1124
+ if (runRecord && !sameRunRecord(runRecord, stored.runRecord))
1118
1125
  throw new Error('agent run record changed');
1119
- if (record)
1126
+ if (runRecord)
1120
1127
  await deleteAgentRunRecord(storage, stored.runId);
1121
1128
  if (!stored.bindingPreexisting && matches)
1122
1129
  await deleteAgentThreadBinding(storage, {
@@ -1147,6 +1154,14 @@ export function createThreadAgentHost(options) {
1147
1154
  : values;
1148
1155
  },
1149
1156
  serializeDispatch: withDispatchLock,
1157
+ notificationDispatchAllowed: async (scope, agentId) => {
1158
+ instanceScopeFor(scope);
1159
+ return (await catalogFor(scope)).automationAllowed(agentId, {
1160
+ kind: 'system',
1161
+ id: systemPrincipalId,
1162
+ purpose: 'notification-dispatch',
1163
+ }, 'notification.dispatch');
1164
+ },
1150
1165
  blockingRun: (scope) => withBindingLock(() => findBlockingRun(instanceScopeFor(scope))),
1151
1166
  scheduleDispatchStatus: async (scope, input) => {
1152
1167
  const ref = runRef(scope, {
@@ -1274,6 +1289,34 @@ export function createThreadAgentHost(options) {
1274
1289
  const resolvedProviderOptions = source.target
1275
1290
  ? source.target.providerOptions
1276
1291
  : input.providerOptions;
1292
+ // This host bypasses the guarded handle, so checks run on forwarded
1293
+ // snapshots before state writes.
1294
+ let providerOptionsSnapshot;
1295
+ let messagesSnapshot;
1296
+ try {
1297
+ providerOptionsSnapshot = providerOptions(resolvedProviderOptions);
1298
+ // Created signals carry methods that structuredClone cannot copy.
1299
+ messagesSnapshot = isCreatedAgentSignal(messages)
1300
+ ? messages
1301
+ : Array.isArray(messages)
1302
+ ? messages.map((item) => isCreatedAgentSignal(item) ? item : structuredClone(item))
1303
+ : structuredClone(messages);
1304
+ }
1305
+ catch (error) {
1306
+ if (error instanceof AgentHostRequestError)
1307
+ throw error;
1308
+ throw new AgentHostRequestError(400, 'agent input must be cloneable');
1309
+ }
1310
+ try {
1311
+ assertNoGuardedSystemMessages(messagesSnapshot);
1312
+ assertAcceptedCallProviderOptions(providerOptionsSnapshot);
1313
+ }
1314
+ catch (error) {
1315
+ if (error instanceof TypeError) {
1316
+ throw new AgentHostRequestError(400, error.message);
1317
+ }
1318
+ throw error;
1319
+ }
1277
1320
  const { current, module, principalPermissions } = await authorize(scope, ref.agentId, entry, scope.principal);
1278
1321
  if (ref.resourceId !== resourceIdFromKey(scope.threadId)) {
1279
1322
  throw new AgentHostRequestError(404, 'run not found');
@@ -1336,7 +1379,7 @@ export function createThreadAgentHost(options) {
1336
1379
  throw new AgentHostRequestError(409, 'thread is bound to another agent');
1337
1380
  }
1338
1381
  }
1339
- const recovery = {
1382
+ const recoveryState = {
1340
1383
  version: 2,
1341
1384
  phase: 'preparing',
1342
1385
  runRecord: stored,
@@ -1356,14 +1399,14 @@ export function createThreadAgentHost(options) {
1356
1399
  .owner(claim.kind, claim.resourceId)))).some((registered) => registered !== undefined)) {
1357
1400
  throw new AgentHostRequestError(404, 'run not found');
1358
1401
  }
1359
- await armOwnerRecovery(recovery);
1402
+ await armOwnerRecovery(recoveryState);
1360
1403
  if (!(await options
1361
1404
  .resourceAccess()
1362
- .reserveAll(claims, owner, recovery.token))) {
1405
+ .reserveAll(claims, owner, recoveryState.token))) {
1363
1406
  await options
1364
1407
  .resourceAccess()
1365
- .settleReservation(recovery.token, claims);
1366
- await clearOwnerRecovery(recovery);
1408
+ .settleReservation(recoveryState.token, claims);
1409
+ await clearOwnerRecovery(recoveryState);
1367
1410
  throw new AgentHostRequestError(404, 'run not found');
1368
1411
  }
1369
1412
  if (threaded && !existing) {
@@ -1374,7 +1417,7 @@ export function createThreadAgentHost(options) {
1374
1417
  });
1375
1418
  }
1376
1419
  await writeAgentRunRecord(options.stateStorage(), ref.runId, stored);
1377
- return recovery;
1420
+ return recoveryState;
1378
1421
  });
1379
1422
  // From here to the finally below, this object IS the run's execution.
1380
1423
  // Registered BEFORE the stream so the window a replaying start asks
@@ -1394,8 +1437,8 @@ export function createThreadAgentHost(options) {
1394
1437
  : {}),
1395
1438
  maxSteps: module.agent.maxSteps,
1396
1439
  disableBackgroundTasks: true,
1397
- ...(resolvedProviderOptions !== undefined
1398
- ? { providerOptions: providerOptions(resolvedProviderOptions) }
1440
+ ...(providerOptionsSnapshot !== undefined
1441
+ ? { providerOptions: providerOptionsSnapshot }
1399
1442
  : {}),
1400
1443
  };
1401
1444
  const scheduleDispatch = source.target &&
@@ -1405,7 +1448,7 @@ export function createThreadAgentHost(options) {
1405
1448
  ? { scheduleId: input.scheduleId, dispatchId: input.dispatchId }
1406
1449
  : undefined;
1407
1450
  try {
1408
- await durable.streamUntilPersisted(messages, streamOptions, principal.id, principal.kind, recovery.token, scheduleDispatch, idempotencyKey, {
1451
+ await durable.streamUntilPersisted(messagesSnapshot, streamOptions, principal.id, principal.kind, recovery.token, scheduleDispatch, idempotencyKey, {
1409
1452
  ...(mutationEpoch === undefined ? {} : { mutationEpoch }),
1410
1453
  startIdentity,
1411
1454
  agentStart: { threaded },
@@ -1429,9 +1472,11 @@ export function createThreadAgentHost(options) {
1429
1472
  catch (error) {
1430
1473
  unwoundExecutions.add(execution);
1431
1474
  try {
1432
- const current = await options.stateStorage().get(recoveryKey);
1433
- if (current !== undefined) {
1434
- const latest = validateOwnerRecovery(scope.threadId, recoveryKey, current);
1475
+ const storedRecovery = await options
1476
+ .stateStorage()
1477
+ .get(recoveryKey);
1478
+ if (storedRecovery !== undefined) {
1479
+ const latest = validateOwnerRecovery(scope.threadId, recoveryKey, storedRecovery);
1435
1480
  if (!sameOwnerRecovery(latest, recovery))
1436
1481
  throw new Error('agent owner recovery changed');
1437
1482
  const summary = await recoverOwner(scope, recoveryKey, latest, execution, error);
@@ -1476,9 +1521,9 @@ export function createThreadAgentHost(options) {
1476
1521
  route: async (request, scope) => {
1477
1522
  let preflightedTermination = false;
1478
1523
  const preflightUrl = new URL(request.url);
1479
- const preflightSuffix = preflightUrl.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX)
1480
- ? preflightUrl.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length)
1481
- : '';
1524
+ if (!preflightUrl.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
1525
+ return null;
1526
+ const preflightSuffix = preflightUrl.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
1482
1527
  const preflightSegments = preflightSuffix.split('/').filter(Boolean);
1483
1528
  // The start holds the dispatch lock while its liveness probe must remain responsive.
1484
1529
  if (request.method === 'GET' &&
@@ -1544,10 +1589,17 @@ export function createThreadAgentHost(options) {
1544
1589
  preflightedTermination = true;
1545
1590
  }
1546
1591
  }
1592
+ // A queued start or resume keeps its parsed body if the sender disconnects.
1593
+ const startBody = request.method === 'POST' &&
1594
+ preflightUrl.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`
1595
+ ? await objectBody(request)
1596
+ : undefined;
1597
+ const resumeBody = request.method === 'POST' &&
1598
+ preflightUrl.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`
1599
+ ? await objectBody(request)
1600
+ : undefined;
1547
1601
  return withDispatchLock(async () => {
1548
1602
  const url = new URL(request.url);
1549
- if (!url.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
1550
- return null;
1551
1603
  if (request.method === 'GET' &&
1552
1604
  url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/binding`) {
1553
1605
  const resourceId = url.searchParams.get('resourceId');
@@ -1561,9 +1613,8 @@ export function createThreadAgentHost(options) {
1561
1613
  }
1562
1614
  return json({ bound: true });
1563
1615
  }
1564
- if (request.method === 'POST' &&
1565
- url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
1566
- const body = await objectBody(request);
1616
+ if (startBody) {
1617
+ const body = startBody;
1567
1618
  if ('resourceOwner' in body ||
1568
1619
  'requestedBy' in body ||
1569
1620
  [
@@ -1629,9 +1680,8 @@ export function createThreadAgentHost(options) {
1629
1680
  : {}),
1630
1681
  }));
1631
1682
  }
1632
- if (request.method === 'POST' &&
1633
- url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`) {
1634
- const body = await objectBody(request);
1683
+ if (resumeBody) {
1684
+ const body = resumeBody;
1635
1685
  const ref = runRef(scope, body);
1636
1686
  const snapshotExecution = await snapshotExecutionFor(scope, ref);
1637
1687
  await statusFor(scope, ref, snapshotExecution.state);
@@ -1739,7 +1789,7 @@ export function createThreadAgentHost(options) {
1739
1789
  if (segments.length === 4 &&
1740
1790
  segments[3] === 'terminate' &&
1741
1791
  request.method === 'POST') {
1742
- const runtime = scope.init.runtime;
1792
+ const scopedRuntime = scope.init.runtime;
1743
1793
  const replayOnly = url.searchParams.get('replay') === '1';
1744
1794
  const storedRun = await readRun(ref.runId);
1745
1795
  if (storedRun && storedRun.agentId !== ref.agentId) {
@@ -1750,17 +1800,17 @@ export function createThreadAgentHost(options) {
1750
1800
  .resourceAccess()
1751
1801
  .owner('run', ref.runId);
1752
1802
  if (!replayOnly && !preflightedTermination) {
1753
- await runtime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1803
+ await scopedRuntime.cancelActiveExecution(await workflowIdFor(scope, ref.agentId), ref.runId, 'cancelled', [scope.principal, preflightOwner ?? scope.principal]);
1754
1804
  }
1755
1805
  const owner = await options.resourceAccess().owner('run', ref.runId);
1756
1806
  if (replayOnly) {
1757
- const existing = await runtime.status(await workflowIdFor(scope, ref.agentId), ref.runId);
1807
+ const existing = await scopedRuntime.status(await workflowIdFor(scope, ref.agentId), ref.runId);
1758
1808
  if (existing?.status !== 'cancelled' &&
1759
1809
  existing?.status !== 'timed_out') {
1760
1810
  throw new AgentHostRequestError(404, 'run not found');
1761
1811
  }
1762
1812
  }
1763
- const transition = await runtime.terminateAsPrincipal(await workflowIdFor(scope, ref.agentId), ref.runId, scope.principal, owner ?? scope.principal);
1813
+ const transition = await scopedRuntime.terminateAsPrincipal(await workflowIdFor(scope, ref.agentId), ref.runId, scope.principal, owner ?? scope.principal);
1764
1814
  const selected = await selectedAgentState(scope, ref, {
1765
1815
  includeLegacy: true,
1766
1816
  });
@@ -1802,7 +1852,7 @@ export function createThreadAgentHost(options) {
1802
1852
  if (guard)
1803
1853
  await guard();
1804
1854
  if (selected.kind !== 'legacy')
1805
- await runtime.settleStartExecution(selected);
1855
+ await scopedRuntime.settleStartExecution(selected);
1806
1856
  let summary = legacy?.summary ?? transition.summary;
1807
1857
  if (!cleanup.cleanupCompleted) {
1808
1858
  if (guard)
@@ -1832,7 +1882,7 @@ export function createThreadAgentHost(options) {
1832
1882
  }
1833
1883
  if (guard)
1834
1884
  await guard();
1835
- summary = await runtime.completeTerminalCleanup(workflowId, ref.runId, cleanup.revision);
1885
+ summary = await scopedRuntime.completeTerminalCleanup(workflowId, ref.runId, cleanup.revision);
1836
1886
  }
1837
1887
  if (legacy) {
1838
1888
  if (guard)