@proofoftech/flowsafe 0.7.0 → 0.9.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 (129) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +14 -4
  3. package/dist/agent-host/approval-resumer.d.ts +18 -0
  4. package/dist/agent-host/approval-resumer.d.ts.map +1 -0
  5. package/dist/agent-host/approval-resumer.js +53 -0
  6. package/dist/agent-host/approval-resumer.js.map +1 -0
  7. package/dist/agent-host/catalog.d.ts +6 -0
  8. package/dist/agent-host/catalog.d.ts.map +1 -0
  9. package/dist/agent-host/catalog.js +194 -0
  10. package/dist/agent-host/catalog.js.map +1 -0
  11. package/dist/agent-host/index.d.ts +9 -0
  12. package/dist/agent-host/index.d.ts.map +1 -0
  13. package/dist/agent-host/index.js +11 -0
  14. package/dist/agent-host/index.js.map +1 -0
  15. package/dist/agent-host/router.d.ts +11 -0
  16. package/dist/agent-host/router.d.ts.map +1 -0
  17. package/dist/agent-host/router.js +240 -0
  18. package/dist/agent-host/router.js.map +1 -0
  19. package/dist/agent-host/thread-host.d.ts +74 -0
  20. package/dist/agent-host/thread-host.d.ts.map +1 -0
  21. package/dist/agent-host/thread-host.js +688 -0
  22. package/dist/agent-host/thread-host.js.map +1 -0
  23. package/dist/agent-host/thread-topology.d.ts +39 -0
  24. package/dist/agent-host/thread-topology.d.ts.map +1 -0
  25. package/dist/agent-host/thread-topology.js +127 -0
  26. package/dist/agent-host/thread-topology.js.map +1 -0
  27. package/dist/agent-host/trusted-context.d.ts +8 -0
  28. package/dist/agent-host/trusted-context.d.ts.map +1 -0
  29. package/dist/agent-host/trusted-context.js +38 -0
  30. package/dist/agent-host/trusted-context.js.map +1 -0
  31. package/dist/agent-host/types.d.ts +85 -0
  32. package/dist/agent-host/types.d.ts.map +1 -0
  33. package/dist/agent-host/types.js +3 -0
  34. package/dist/agent-host/types.js.map +1 -0
  35. package/dist/agent-runner/agent-run-state.d.ts +38 -0
  36. package/dist/agent-runner/agent-run-state.d.ts.map +1 -0
  37. package/dist/agent-runner/agent-run-state.js +118 -0
  38. package/dist/agent-runner/agent-run-state.js.map +1 -0
  39. package/dist/agent-runner/durable-agent-runner.d.ts +12 -0
  40. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  41. package/dist/agent-runner/durable-agent-runner.js +130 -13
  42. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  43. package/dist/agent-runner/index.d.ts +2 -0
  44. package/dist/agent-runner/index.d.ts.map +1 -1
  45. package/dist/agent-runner/index.js +1 -0
  46. package/dist/agent-runner/index.js.map +1 -1
  47. package/dist/approval-api/contract.d.ts.map +1 -1
  48. package/dist/approval-api/contract.js.map +1 -1
  49. package/dist/approval-api/d1-store.d.ts.map +1 -1
  50. package/dist/approval-api/d1-store.js +24 -9
  51. package/dist/approval-api/d1-store.js.map +1 -1
  52. package/dist/approval-api/index.d.ts +2 -0
  53. package/dist/approval-api/index.d.ts.map +1 -1
  54. package/dist/approval-api/index.js +7 -0
  55. package/dist/approval-api/index.js.map +1 -1
  56. package/dist/approval-api/principal.d.ts +214 -0
  57. package/dist/approval-api/principal.d.ts.map +1 -0
  58. package/dist/approval-api/principal.js +391 -0
  59. package/dist/approval-api/principal.js.map +1 -0
  60. package/dist/approval-api/service.d.ts +42 -1
  61. package/dist/approval-api/service.d.ts.map +1 -1
  62. package/dist/approval-api/service.js +142 -13
  63. package/dist/approval-api/service.js.map +1 -1
  64. package/dist/approval-api/tenant-context.d.ts +7 -0
  65. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  66. package/dist/approval-api/tenant-context.js +31 -3
  67. package/dist/approval-api/tenant-context.js.map +1 -1
  68. package/dist/approval-api/types.d.ts +19 -3
  69. package/dist/approval-api/types.d.ts.map +1 -1
  70. package/dist/approval-api/types.js.map +1 -1
  71. package/dist/do-runner/execution-context.d.ts +19 -0
  72. package/dist/do-runner/execution-context.d.ts.map +1 -0
  73. package/dist/do-runner/execution-context.js +70 -0
  74. package/dist/do-runner/execution-context.js.map +1 -0
  75. package/dist/do-runner/index.d.ts +2 -1
  76. package/dist/do-runner/index.d.ts.map +1 -1
  77. package/dist/do-runner/index.js +2 -1
  78. package/dist/do-runner/index.js.map +1 -1
  79. package/dist/do-runner/runtime.d.ts +8 -0
  80. package/dist/do-runner/runtime.d.ts.map +1 -1
  81. package/dist/do-runner/runtime.js +157 -19
  82. package/dist/do-runner/runtime.js.map +1 -1
  83. package/dist/do-runner/thread-do.d.ts +15 -1
  84. package/dist/do-runner/thread-do.d.ts.map +1 -1
  85. package/dist/do-runner/thread-do.js +31 -5
  86. package/dist/do-runner/thread-do.js.map +1 -1
  87. package/dist/do-runner/thread-header.d.ts +17 -2
  88. package/dist/do-runner/thread-header.d.ts.map +1 -1
  89. package/dist/do-runner/thread-header.js +17 -2
  90. package/dist/do-runner/thread-header.js.map +1 -1
  91. package/dist/host-kit/approval-bridge.d.ts +12 -13
  92. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  93. package/dist/host-kit/approval-bridge.js +63 -25
  94. package/dist/host-kit/approval-bridge.js.map +1 -1
  95. package/dist/host-kit/flowsafe-worker.d.ts +13 -0
  96. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  97. package/dist/host-kit/flowsafe-worker.js +11 -3
  98. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  99. package/dist/host-kit/host-approval-service.d.ts +10 -5
  100. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  101. package/dist/host-kit/host-approval-service.js +10 -10
  102. package/dist/host-kit/host-approval-service.js.map +1 -1
  103. package/dist/host-kit/index.d.ts +2 -2
  104. package/dist/host-kit/index.d.ts.map +1 -1
  105. package/dist/host-kit/index.js +1 -1
  106. package/dist/host-kit/index.js.map +1 -1
  107. package/dist/host-kit/run-router.d.ts.map +1 -1
  108. package/dist/host-kit/run-router.js +1 -6
  109. package/dist/host-kit/run-router.js.map +1 -1
  110. package/dist/host-kit/thread-topology.d.ts +1 -1
  111. package/dist/host-kit/thread-topology.d.ts.map +1 -1
  112. package/dist/host-kit/thread-topology.js +29 -3
  113. package/dist/host-kit/thread-topology.js.map +1 -1
  114. package/dist/index.d.ts.map +1 -1
  115. package/dist/index.js +3 -2
  116. package/dist/index.js.map +1 -1
  117. package/dist/schedules/tick.d.ts +3 -7
  118. package/dist/schedules/tick.d.ts.map +1 -1
  119. package/dist/schedules/tick.js +7 -41
  120. package/dist/schedules/tick.js.map +1 -1
  121. package/dist/signal-providers/delivery.d.ts +1 -1
  122. package/dist/signal-providers/delivery.d.ts.map +1 -1
  123. package/dist/signal-providers/delivery.js +9 -3
  124. package/dist/signal-providers/delivery.js.map +1 -1
  125. package/dist/signals/thread-do-routes.d.ts +12 -1
  126. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  127. package/dist/signals/thread-do-routes.js +48 -12
  128. package/dist/signals/thread-do-routes.js.map +1 -1
  129. package/package.json +6 -3
@@ -0,0 +1,688 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { AGENT_STREAM_TOPIC } from '@mastra/core/agent/durable';
3
+ import { Mastra } from '@mastra/core/mastra';
4
+ import { bindAgentThread, createFlowsafeDurableAgent, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, deleteAgentRunRecord, readAgentRunRecord, readAgentThreadBinding, writeAgentRunRecord, } from '../agent-runner/index.js';
5
+ import { principalActor, principalAuditFields, RUN_START_ROLES, samePrincipal, } from '../approval-api/index.js';
6
+ import { DoStatusError, mintResourceId, tenantOwnsMemoryId, tenantOwnsSaltedId, } from '../do-runner/index.js';
7
+ import { reconcileApprovalsForSummary } from '../host-kit/index.js';
8
+ import { createAgentModuleCatalog } from './catalog.js';
9
+ import { AGENT_HOST_ROUTE_PREFIX } from './thread-topology.js';
10
+ import { createTrustedAgentRequestContext, deriveTrustedAgentContext, sanitizeStoredAgentContext, } from './trusted-context.js';
11
+ class AgentHostRequestError extends DoStatusError {
12
+ status;
13
+ constructor(status, message) {
14
+ super(message);
15
+ this.name = 'AgentHostRequestError';
16
+ this.status = status;
17
+ }
18
+ }
19
+ function json(payload, status = 200) {
20
+ return new Response(JSON.stringify(payload), {
21
+ status,
22
+ headers: {
23
+ 'content-type': 'application/json',
24
+ 'cache-control': 'no-store',
25
+ 'x-content-type-options': 'nosniff',
26
+ },
27
+ });
28
+ }
29
+ function decode(value) {
30
+ if (value === undefined)
31
+ return undefined;
32
+ try {
33
+ return decodeURIComponent(value);
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ async function objectBody(request) {
40
+ let value;
41
+ try {
42
+ value = await request.json();
43
+ }
44
+ catch {
45
+ throw new AgentHostRequestError(400, 'a JSON object body is required');
46
+ }
47
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
48
+ throw new AgentHostRequestError(400, 'a JSON object body is required');
49
+ }
50
+ return value;
51
+ }
52
+ const TERMINAL_RUN_STATUSES = [
53
+ 'success',
54
+ 'failed',
55
+ 'tripwire',
56
+ 'canceled',
57
+ 'bailed',
58
+ 'skipped',
59
+ ];
60
+ function isTerminalRunStatus(status) {
61
+ return TERMINAL_RUN_STATUSES.includes(status);
62
+ }
63
+ function entryPath(value) {
64
+ const allowed = [
65
+ 'http.start',
66
+ 'approval.resume',
67
+ 'signal.message',
68
+ 'signal.queue',
69
+ 'signal.reactive',
70
+ 'signal.state',
71
+ 'signal.notification',
72
+ 'signal.wake',
73
+ 'notification.dispatch',
74
+ 'schedule.fire',
75
+ ];
76
+ if (typeof value !== 'string' ||
77
+ !allowed.includes(value)) {
78
+ throw new AgentHostRequestError(400, 'entryPath is required');
79
+ }
80
+ return value;
81
+ }
82
+ function safeContext(value) {
83
+ if (value === undefined ||
84
+ (value !== null && typeof value === 'object' && !Array.isArray(value))) {
85
+ return sanitizeStoredAgentContext(value);
86
+ }
87
+ throw new AgentHostRequestError(400, 'safeContext must be an object');
88
+ }
89
+ function runRef(scope, input) {
90
+ const { agentId, threadId, resourceId, runId } = input;
91
+ if (typeof agentId !== 'string' ||
92
+ threadId !== scope.threadId ||
93
+ typeof resourceId !== 'string' ||
94
+ !tenantOwnsMemoryId(scope.tenantId, resourceId) ||
95
+ typeof runId !== 'string' ||
96
+ !tenantOwnsSaltedId(scope.tenantId, runId)) {
97
+ throw new AgentHostRequestError(404, 'run not found');
98
+ }
99
+ return { agentId, threadId: scope.threadId, resourceId, runId };
100
+ }
101
+ function audit(sink, event) {
102
+ try {
103
+ const result = sink?.(event);
104
+ if (result instanceof Promise)
105
+ void result.catch(() => undefined);
106
+ }
107
+ catch {
108
+ // Authorization is never made unavailable by an audit export failure.
109
+ }
110
+ }
111
+ function ndjson(stream, initialOffset) {
112
+ const reader = stream.getReader();
113
+ const encoder = new TextEncoder();
114
+ let offset = initialOffset;
115
+ return new Response(new ReadableStream({
116
+ async pull(controller) {
117
+ const next = await reader.read();
118
+ if (next.done) {
119
+ controller.close();
120
+ return;
121
+ }
122
+ offset += 1;
123
+ controller.enqueue(encoder.encode(`${JSON.stringify({ offset, event: next.value })}\n`));
124
+ },
125
+ async cancel(reason) {
126
+ await reader.cancel(reason);
127
+ },
128
+ }), {
129
+ headers: {
130
+ 'content-type': 'application/x-ndjson; charset=utf-8',
131
+ 'cache-control': 'no-store',
132
+ 'x-content-type-options': 'nosniff',
133
+ },
134
+ });
135
+ }
136
+ export function createThreadAgentHost(options) {
137
+ let catalogPromise;
138
+ let runtime;
139
+ const executions = new Map();
140
+ let stableScope;
141
+ let bindingTail = Promise.resolve();
142
+ const instanceScopeFor = (scope) => {
143
+ if (stableScope) {
144
+ if (stableScope.threadId !== scope.threadId ||
145
+ stableScope.tenantId !== scope.tenantId ||
146
+ stableScope.init !== scope.init) {
147
+ throw new Error('thread agent host cannot be shared across DO instances');
148
+ }
149
+ return stableScope;
150
+ }
151
+ stableScope = Object.freeze({
152
+ threadId: scope.threadId,
153
+ tenantId: scope.tenantId,
154
+ init: scope.init,
155
+ });
156
+ return stableScope;
157
+ };
158
+ const withBindingLock = async (operation) => {
159
+ const previous = bindingTail;
160
+ let release = () => undefined;
161
+ bindingTail = new Promise((resolve) => {
162
+ release = resolve;
163
+ });
164
+ await previous;
165
+ try {
166
+ return await operation();
167
+ }
168
+ finally {
169
+ release();
170
+ }
171
+ };
172
+ const catalogFor = async (scope) => {
173
+ catalogPromise ??= Promise.resolve(options.buildModules(instanceScopeFor(scope)))
174
+ .then(createAgentModuleCatalog)
175
+ .catch((error) => {
176
+ catalogPromise = undefined;
177
+ throw error;
178
+ });
179
+ return catalogPromise;
180
+ };
181
+ const runtimeFor = async (scope) => {
182
+ if (runtime) {
183
+ if (runtime.scopeRuntime !== scope.init.runtime) {
184
+ throw new Error('thread agent host cannot be shared across DO instances');
185
+ }
186
+ return runtime;
187
+ }
188
+ const catalog = await catalogFor(scope);
189
+ const mastra = new Mastra({
190
+ storage: options.storage(instanceScopeFor(scope)),
191
+ agents: Object.fromEntries(catalog.modules.map((module) => [
192
+ module.meta.id,
193
+ module.agent,
194
+ ])),
195
+ ...(scope.init.pubsub ? { pubsub: scope.init.pubsub } : {}),
196
+ });
197
+ const agents = new Map();
198
+ for (const module of catalog.modules) {
199
+ agents.set(module.meta.id, createFlowsafeDurableAgent({
200
+ agent: mastra.getAgent(module.meta.id),
201
+ runtime: scope.init.runtime,
202
+ pubsub: scope.init.pubsub,
203
+ threadRuntime: mastra.agentThreadStreamRuntime,
204
+ maxSteps: module.agent.maxSteps,
205
+ cache: options.cache,
206
+ }));
207
+ }
208
+ runtime = { scopeRuntime: scope.init.runtime, catalog, agents };
209
+ return runtime;
210
+ };
211
+ /**
212
+ * The one entry gate, split by principal kind because the two kinds are
213
+ * authorized by different things and must not fall through to each other.
214
+ *
215
+ * A human passes the route-level start roles intersected with the agent's own
216
+ * allowedRoles, exactly as before. An automated principal never consults
217
+ * roles at all: it must be declared in the agent's `allowedAutomation` for
218
+ * this precise entry path, AND survive the host's optional authorizer. Absent
219
+ * declaration denies — which is why a scheduled start of an agent that has
220
+ * not opted in fails here rather than executing as a synthetic operator.
221
+ */
222
+ const authorize = async (scope, agentId, entry, principal) => {
223
+ const current = await runtimeFor(scope);
224
+ const module = current.catalog.get(agentId);
225
+ let reason;
226
+ let granted = false;
227
+ if (module === undefined) {
228
+ reason = 'agent is not registered';
229
+ }
230
+ else if (principal.kind === 'human') {
231
+ const allowed = current.catalog.allowedRoles(agentId);
232
+ granted =
233
+ RUN_START_ROLES.includes(principal.role) &&
234
+ allowed?.includes(principal.role) === true;
235
+ if (!granted)
236
+ reason = 'role is not allowed to mutate this agent';
237
+ }
238
+ else if (!current.catalog.automationAllowed(agentId, principal, entry)) {
239
+ reason = `agent does not accept '${principal.kind}' principals on entry path '${entry}'`;
240
+ }
241
+ else {
242
+ // AND-composed: the injected authorizer can only narrow what the agent
243
+ // already declared. A host cannot widen automation from wiring.
244
+ const hostAllows = (await options.authorizeAutomatedEntry?.({
245
+ principal,
246
+ agentId,
247
+ entryPath: entry,
248
+ tenantId: scope.tenantId,
249
+ threadId: scope.threadId,
250
+ })) ?? true;
251
+ granted = hostAllows;
252
+ if (!granted)
253
+ reason = 'host denied this automated entry';
254
+ }
255
+ audit(options.audit, {
256
+ actor: principalActor(principal),
257
+ action: 'agent.entry.authorize',
258
+ resource: `agent:${agentId}`,
259
+ decision: granted ? 'allowed' : 'denied',
260
+ ...(reason !== undefined ? { reason } : {}),
261
+ detail: {
262
+ agentId,
263
+ tenantId: scope.tenantId,
264
+ threadId: scope.threadId,
265
+ entryPath: entry,
266
+ ...principalAuditFields(principal),
267
+ },
268
+ });
269
+ if (!module)
270
+ throw new AgentHostRequestError(404, 'agent not found');
271
+ if (!granted)
272
+ throw new AgentHostRequestError(403, 'forbidden');
273
+ return { current, module };
274
+ };
275
+ const readBinding = () => readAgentThreadBinding(options.stateStorage());
276
+ const readRun = (runId) => readAgentRunRecord(options.stateStorage(), runId);
277
+ const withExecution = async (execution, operation) => {
278
+ if (executions.has(execution.runId)) {
279
+ throw new AgentHostRequestError(409, `run '${execution.runId}' already has an active operation`);
280
+ }
281
+ executions.set(execution.runId, execution);
282
+ try {
283
+ return await operation();
284
+ }
285
+ finally {
286
+ executions.delete(execution.runId);
287
+ }
288
+ };
289
+ // Reconciling approvals is trusted platform work with no person behind it.
290
+ // It used to mint role:'operator', which is why an approval bridge looked
291
+ // indistinguishable from a human operator in the audit trail. The bridge
292
+ // mints its own principal from this id against the service's tenant.
293
+ const systemActorId = options.systemActorId ?? 'flowsafe-system';
294
+ // Deliberately NOT vouched. Its only consumer projects it to an ApprovalActor
295
+ // for a role-gated READ, which grants nothing an automated principal does not
296
+ // already have — so calling the trust assertion here would assert trust that
297
+ // nothing consumes, and `trustAutomationPrincipal` has to stay greppable as
298
+ // "this is where authority is conferred" to be worth anything.
299
+ //
300
+ // `purpose` is likewise inert here: principalActor drops it, and a successful
301
+ // list() emits no audit event, so this string reaches nothing. It is not
302
+ // shared with the bridge's RECONCILE_PURPOSE for that reason — there is no
303
+ // provenance here to drift.
304
+ const systemPrincipal = (scope) => ({
305
+ kind: 'system',
306
+ id: systemActorId,
307
+ tenantId: scope.tenantId,
308
+ purpose: 'approval-suspension-reconcile',
309
+ });
310
+ const currentApprovals = async (scope, summary, principal, agentId, resourceId) => {
311
+ if (summary.status !== 'suspended')
312
+ return [];
313
+ const service = options.approvalService(instanceScopeFor(scope));
314
+ await reconcileApprovalsForSummary(service, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, summary, systemActorId, {
315
+ kind: 'agent-thread',
316
+ agentId,
317
+ threadId: scope.threadId,
318
+ resourceId,
319
+ principal,
320
+ }, principal.id);
321
+ const records = await service.list({
322
+ workflowId: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
323
+ runId: summary.runId,
324
+ }, principalActor(systemPrincipal(scope)));
325
+ const keys = new Set((summary.suspended ?? []).map((path) => path.join('.')));
326
+ return records.filter((record) => {
327
+ const key = record.stepPath?.join('.');
328
+ return (key !== undefined &&
329
+ keys.has(key) &&
330
+ record.suspendedAt === summary.suspendedAt?.[key] &&
331
+ record.resumeCount === summary.resumeCount?.[key]);
332
+ });
333
+ };
334
+ const envelopeFor = async (scope, ref, principal, summary) => {
335
+ const base = {
336
+ agentId: ref.agentId,
337
+ threadId: scope.threadId,
338
+ resourceId: ref.resourceId,
339
+ runId: ref.runId,
340
+ summary,
341
+ };
342
+ if (summary.status !== 'suspended')
343
+ return base;
344
+ const approvals = await currentApprovals(scope, summary, principal, ref.agentId, ref.resourceId);
345
+ return {
346
+ ...base,
347
+ ...(approvals[0] ? { approval: approvals[0] } : {}),
348
+ approvals,
349
+ };
350
+ };
351
+ const snapshotExecutionFor = async (scope, ref) => {
352
+ const workflows = await options
353
+ .storage(instanceScopeFor(scope))
354
+ .getStore('workflows');
355
+ const snapshot = await workflows?.loadWorkflowSnapshot({
356
+ workflowName: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
357
+ runId: ref.runId,
358
+ });
359
+ const input = snapshot?.context.input;
360
+ const requestContext = snapshot?.requestContext;
361
+ const correlation = requestContext?.['breakwater.auditContext'];
362
+ const memory = input?.messageListState?.memoryInfo;
363
+ const memoryMatches = memory === null ||
364
+ (memory?.threadId === scope.threadId &&
365
+ memory.resourceId === ref.resourceId);
366
+ if (input?.agentId !== ref.agentId ||
367
+ requestContext?.runId !== ref.runId ||
368
+ requestContext.threadId !== scope.threadId ||
369
+ requestContext.resourceId !== ref.resourceId ||
370
+ correlation?.agentId !== ref.agentId ||
371
+ correlation.threadId !== scope.threadId ||
372
+ correlation.resourceId !== ref.resourceId ||
373
+ !memoryMatches) {
374
+ throw new AgentHostRequestError(404, 'run not found');
375
+ }
376
+ return {
377
+ threaded: memory !== null,
378
+ safeContext: sanitizeStoredAgentContext(requestContext),
379
+ };
380
+ };
381
+ const statusFor = async (scope, ref, knownThreaded) => {
382
+ const binding = await readBinding();
383
+ const current = await runtimeFor(scope);
384
+ if (!current.catalog.get(ref.agentId)) {
385
+ throw new AgentHostRequestError(404, 'agent not found');
386
+ }
387
+ const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
388
+ if (!summary)
389
+ throw new AgentHostRequestError(404, 'run not found');
390
+ const threaded = knownThreaded ?? (await snapshotExecutionFor(scope, ref)).threaded;
391
+ const bindingMatches = binding?.agentId === ref.agentId && binding.resourceId === ref.resourceId;
392
+ if ((threaded && !bindingMatches) || (!threaded && binding)) {
393
+ throw new AgentHostRequestError(404, 'run not found');
394
+ }
395
+ const stored = await readRun(ref.runId);
396
+ if (stored && stored.agentId !== ref.agentId) {
397
+ throw new AgentHostRequestError(404, 'run not found');
398
+ }
399
+ if (summary.status === 'suspended' && !stored) {
400
+ throw new AgentHostRequestError(409, 'suspended agent run has no recoverable execution principal');
401
+ }
402
+ // Inert today — a suspended run without a stored record already threw 409
403
+ // above, and only a suspended run consults this. Kept as the scope's
404
+ // PRINCIPAL rather than its actor so that if those two conditions are ever
405
+ // decoupled, the fallback still cannot relabel an automated run as whoever
406
+ // happened to poll its status.
407
+ const principal = stored?.principal ?? scope.principal;
408
+ const result = await envelopeFor(scope, ref, principal, summary);
409
+ if (isTerminalRunStatus(summary.status) && stored) {
410
+ await deleteAgentRunRecord(options.stateStorage(), ref.runId);
411
+ }
412
+ return result;
413
+ };
414
+ const host = {
415
+ requestContextForRun: (base) => async (workflowId, runId, leg) => {
416
+ const values = base ? await base(workflowId, runId, leg) : undefined;
417
+ const execution = executions.get(runId);
418
+ return execution && workflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID
419
+ ? {
420
+ ...execution.safeContext,
421
+ ...values,
422
+ ...deriveTrustedAgentContext(execution, {}),
423
+ }
424
+ : values;
425
+ },
426
+ start: async (scope, input) => {
427
+ const ref = runRef(scope, input);
428
+ const hasPrompt = input.prompt !== undefined;
429
+ const hasMessages = input.messages !== undefined;
430
+ if (hasPrompt === hasMessages ||
431
+ (hasPrompt &&
432
+ (typeof input.prompt !== 'string' ||
433
+ input.prompt.trim() === '' ||
434
+ input.prompt.length > 10_000))) {
435
+ throw new AgentHostRequestError(400, 'exactly one valid prompt or messages input is required');
436
+ }
437
+ const messages = input.messages ?? input.prompt;
438
+ if (messages === undefined) {
439
+ throw new AgentHostRequestError(400, 'agent input is required');
440
+ }
441
+ const entry = entryPath(input.entryPath);
442
+ const { current, module } = await authorize(scope, ref.agentId, entry, scope.principal);
443
+ if (ref.resourceId !== mintResourceId(scope.tenantId, scope.threadId)) {
444
+ throw new AgentHostRequestError(404, 'run not found');
445
+ }
446
+ const execution = {
447
+ agentId: ref.agentId,
448
+ principal: scope.principal,
449
+ threadId: scope.threadId,
450
+ resourceId: ref.resourceId,
451
+ runId: ref.runId,
452
+ entryPath: entry,
453
+ safeContext: safeContext(input.safeContext),
454
+ };
455
+ const durable = current.agents.get(module.meta.id);
456
+ if (!durable)
457
+ throw new Error('guarded agent was not registered');
458
+ return withExecution(execution, async () => {
459
+ const existingRecord = await readRun(ref.runId);
460
+ const existingSummary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
461
+ if (existingRecord || existingSummary) {
462
+ throw new AgentHostRequestError(409, `run '${ref.runId}' already exists`);
463
+ }
464
+ if (input.threaded !== false) {
465
+ await withBindingLock(async () => {
466
+ const existing = await readBinding();
467
+ const bindingMatches = existing?.agentId === ref.agentId &&
468
+ existing.resourceId === ref.resourceId;
469
+ if (entry === 'schedule.fire') {
470
+ if (!bindingMatches) {
471
+ throw new AgentHostRequestError(404, 'run not found');
472
+ }
473
+ return;
474
+ }
475
+ if (existing && !bindingMatches) {
476
+ throw new AgentHostRequestError(409, 'thread is bound to another agent');
477
+ }
478
+ if (!existing) {
479
+ await bindAgentThread(options.stateStorage(), {
480
+ version: 1,
481
+ agentId: ref.agentId,
482
+ resourceId: ref.resourceId,
483
+ });
484
+ }
485
+ });
486
+ }
487
+ const stored = {
488
+ version: 2,
489
+ agentId: ref.agentId,
490
+ principal: scope.principal,
491
+ originEntryPath: entry,
492
+ };
493
+ await writeAgentRunRecord(options.stateStorage(), ref.runId, stored);
494
+ try {
495
+ await durable.streamUntilPersisted(messages, {
496
+ runId: ref.runId,
497
+ requestContext: createTrustedAgentRequestContext(execution),
498
+ ...(input.threaded !== false
499
+ ? {
500
+ memory: {
501
+ thread: scope.threadId,
502
+ resource: ref.resourceId,
503
+ },
504
+ }
505
+ : {}),
506
+ maxSteps: module.agent.maxSteps,
507
+ disableBackgroundTasks: true,
508
+ });
509
+ const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
510
+ if (!summary)
511
+ throw new Error('agent run did not persist a summary');
512
+ const result = await envelopeFor(scope, ref, scope.principal, summary);
513
+ if (isTerminalRunStatus(result.summary.status)) {
514
+ await deleteAgentRunRecord(options.stateStorage(), ref.runId);
515
+ }
516
+ return result;
517
+ }
518
+ catch (error) {
519
+ let summary;
520
+ try {
521
+ summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
522
+ }
523
+ catch {
524
+ // Unknown authoritative state: retain metadata and fail closed.
525
+ }
526
+ if (!summary || isTerminalRunStatus(summary.status)) {
527
+ await deleteAgentRunRecord(options.stateStorage(), ref.runId);
528
+ }
529
+ throw error;
530
+ }
531
+ });
532
+ },
533
+ resolveBoundAgent: async (scope, input) => {
534
+ const binding = await readBinding();
535
+ if (!binding)
536
+ throw new AgentHostRequestError(404, 'agent not found');
537
+ if (binding.resourceId !== mintResourceId(scope.tenantId, scope.threadId)) {
538
+ throw new AgentHostRequestError(404, 'agent not found');
539
+ }
540
+ if (input.agentId && input.agentId !== binding.agentId) {
541
+ throw new AgentHostRequestError(404, 'agent not found');
542
+ }
543
+ const { current } = await authorize(scope, binding.agentId, entryPath(input.entryPath), scope.principal);
544
+ const durableAgent = current.agents.get(binding.agentId);
545
+ if (!durableAgent)
546
+ throw new Error('guarded agent was not registered');
547
+ return {
548
+ agentId: binding.agentId,
549
+ resourceId: binding.resourceId,
550
+ durableAgent,
551
+ };
552
+ },
553
+ route: async (request, scope) => {
554
+ const url = new URL(request.url);
555
+ if (!url.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
556
+ return null;
557
+ if (request.method === 'POST' &&
558
+ url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
559
+ const body = await objectBody(request);
560
+ const ref = runRef(scope, body);
561
+ if (typeof body.prompt !== 'string') {
562
+ throw new AgentHostRequestError(400, 'prompt is required');
563
+ }
564
+ return json(await host.start(scope, {
565
+ ...ref,
566
+ prompt: body.prompt,
567
+ entryPath: entryPath(body.entryPath),
568
+ threaded: body.threaded !== false,
569
+ safeContext: safeContext(body.safeContext),
570
+ }));
571
+ }
572
+ if (request.method === 'POST' &&
573
+ url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`) {
574
+ const body = await objectBody(request);
575
+ const ref = runRef(scope, body);
576
+ const snapshotExecution = await snapshotExecutionFor(scope, ref);
577
+ await statusFor(scope, ref, snapshotExecution.threaded);
578
+ const stored = await readRun(ref.runId);
579
+ if (!stored ||
580
+ stored.agentId !== ref.agentId ||
581
+ !samePrincipal(stored.principal, scope.principal)) {
582
+ throw new AgentHostRequestError(404, 'run not found');
583
+ }
584
+ const { current, module } = await authorize(scope, ref.agentId, entryPath(body.entryPath), stored.principal);
585
+ const durable = current.agents.get(module.meta.id);
586
+ if (!durable)
587
+ throw new Error('guarded agent was not registered');
588
+ const step = typeof body.step === 'string' ||
589
+ (Array.isArray(body.step) &&
590
+ body.step.every((part) => typeof part === 'string'))
591
+ ? body.step
592
+ : undefined;
593
+ const execution = {
594
+ agentId: ref.agentId,
595
+ principal: stored.principal,
596
+ threadId: scope.threadId,
597
+ resourceId: ref.resourceId,
598
+ runId: ref.runId,
599
+ entryPath: 'approval.resume',
600
+ safeContext: snapshotExecution.safeContext,
601
+ };
602
+ const summary = await withExecution(execution, () => durable.resumeViaRuntime({
603
+ runId: ref.runId,
604
+ ...(step !== undefined ? { step } : {}),
605
+ ...('resumeData' in body ? { resumeData: body.resumeData } : {}),
606
+ ...(snapshotExecution.threaded
607
+ ? {
608
+ memory: {
609
+ thread: scope.threadId,
610
+ resource: ref.resourceId,
611
+ },
612
+ }
613
+ : {}),
614
+ }));
615
+ const result = await envelopeFor(scope, ref, stored.principal, summary);
616
+ if (isTerminalRunStatus(summary.status)) {
617
+ await deleteAgentRunRecord(options.stateStorage(), ref.runId);
618
+ }
619
+ return json(result);
620
+ }
621
+ const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
622
+ const segments = suffix.split('/').filter(Boolean);
623
+ if (segments[0] !== 'runs')
624
+ return json({ error: 'not found' }, 404);
625
+ const agentId = decode(segments[1]);
626
+ const runId = decode(segments[2]);
627
+ const resourceId = url.searchParams.get('resourceId');
628
+ if (!agentId || !runId || !resourceId) {
629
+ throw new AgentHostRequestError(404, 'run not found');
630
+ }
631
+ const ref = runRef(scope, {
632
+ agentId,
633
+ threadId: scope.threadId,
634
+ resourceId,
635
+ runId,
636
+ });
637
+ if (segments.length === 3 && request.method === 'GET') {
638
+ return json(await statusFor(scope, ref));
639
+ }
640
+ if (segments.length === 4 &&
641
+ segments[3] === 'stream' &&
642
+ request.method === 'GET') {
643
+ const run = await statusFor(scope, ref);
644
+ const offset = Number(url.searchParams.get('offset') ?? '0');
645
+ if (!Number.isSafeInteger(offset) || offset < 0) {
646
+ throw new AgentHostRequestError(400, 'invalid stream offset');
647
+ }
648
+ const current = await runtimeFor(scope);
649
+ const durable = current.agents.get(ref.agentId);
650
+ if (!durable)
651
+ throw new AgentHostRequestError(404, 'agent not found');
652
+ const live = durable.runRegistry.has(ref.runId);
653
+ let historyLength = 0;
654
+ try {
655
+ const history = await durable.pubsub.getHistory(AGENT_STREAM_TOPIC(ref.runId));
656
+ historyLength = Array.isArray(history) ? history.length : 0;
657
+ }
658
+ catch {
659
+ // A live registry can still serve future events in this isolate.
660
+ }
661
+ if (!live && historyLength === 0) {
662
+ throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
663
+ }
664
+ if (isTerminalRunStatus(run.summary.status)) {
665
+ if (historyLength === 0) {
666
+ throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
667
+ }
668
+ if (offset >= historyLength) {
669
+ return ndjson(new ReadableStream({
670
+ start(controller) {
671
+ controller.close();
672
+ },
673
+ }), offset);
674
+ }
675
+ }
676
+ const observed = await durable.observe(ref.runId, { offset });
677
+ return ndjson(observed.fullStream, offset);
678
+ }
679
+ const known = segments.length === 3 ||
680
+ (segments.length === 4 && segments[3] === 'stream');
681
+ return known
682
+ ? json({ error: 'method not allowed' }, 405)
683
+ : json({ error: 'not found' }, 404);
684
+ },
685
+ };
686
+ return host;
687
+ }
688
+ //# sourceMappingURL=thread-host.js.map