@proofoftech/flowsafe 0.6.0 → 0.8.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.
- package/CHANGELOG.md +31 -1
- package/README.md +305 -251
- package/dist/agent-host/approval-resumer.d.ts +13 -0
- package/dist/agent-host/approval-resumer.d.ts.map +1 -0
- package/dist/agent-host/approval-resumer.js +43 -0
- package/dist/agent-host/approval-resumer.js.map +1 -0
- package/dist/agent-host/catalog.d.ts +6 -0
- package/dist/agent-host/catalog.d.ts.map +1 -0
- package/dist/agent-host/catalog.js +98 -0
- package/dist/agent-host/catalog.js.map +1 -0
- package/dist/agent-host/index.d.ts +9 -0
- package/dist/agent-host/index.d.ts.map +1 -0
- package/dist/agent-host/index.js +11 -0
- package/dist/agent-host/index.js.map +1 -0
- package/dist/agent-host/router.d.ts +11 -0
- package/dist/agent-host/router.d.ts.map +1 -0
- package/dist/agent-host/router.js +240 -0
- package/dist/agent-host/router.js.map +1 -0
- package/dist/agent-host/thread-host.d.ts +55 -0
- package/dist/agent-host/thread-host.d.ts.map +1 -0
- package/dist/agent-host/thread-host.js +636 -0
- package/dist/agent-host/thread-host.js.map +1 -0
- package/dist/agent-host/thread-topology.d.ts +39 -0
- package/dist/agent-host/thread-topology.d.ts.map +1 -0
- package/dist/agent-host/thread-topology.js +127 -0
- package/dist/agent-host/thread-topology.js.map +1 -0
- package/dist/agent-host/trusted-context.d.ts +9 -0
- package/dist/agent-host/trusted-context.d.ts.map +1 -0
- package/dist/agent-host/trusted-context.js +40 -0
- package/dist/agent-host/trusted-context.js.map +1 -0
- package/dist/agent-host/types.d.ts +49 -0
- package/dist/agent-host/types.d.ts.map +1 -0
- package/dist/agent-host/types.js +3 -0
- package/dist/agent-host/types.js.map +1 -0
- package/dist/agent-runner/agent-run-state.d.ts +30 -0
- package/dist/agent-runner/agent-run-state.d.ts.map +1 -0
- package/dist/agent-runner/agent-run-state.js +128 -0
- package/dist/agent-runner/agent-run-state.js.map +1 -0
- package/dist/agent-runner/approval-shapes.d.ts +1 -1
- package/dist/agent-runner/approval-shapes.js +1 -1
- package/dist/agent-runner/durable-agent-runner.d.ts +32 -16
- package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
- package/dist/agent-runner/durable-agent-runner.js +149 -28
- package/dist/agent-runner/durable-agent-runner.js.map +1 -1
- package/dist/agent-runner/index.d.ts +2 -0
- package/dist/agent-runner/index.d.ts.map +1 -1
- package/dist/agent-runner/index.js +1 -0
- package/dist/agent-runner/index.js.map +1 -1
- package/dist/approval-api/contract.d.ts +2 -2
- package/dist/approval-api/d1-store.d.ts.map +1 -1
- package/dist/approval-api/d1-store.js +27 -11
- package/dist/approval-api/d1-store.js.map +1 -1
- package/dist/approval-api/grants.d.ts +1 -1
- package/dist/approval-api/grants.js +1 -1
- package/dist/approval-api/router.d.ts +1 -1
- package/dist/approval-api/service.d.ts +8 -9
- package/dist/approval-api/service.d.ts.map +1 -1
- package/dist/approval-api/service.js +37 -16
- package/dist/approval-api/service.js.map +1 -1
- package/dist/approval-api/store.d.ts +17 -16
- package/dist/approval-api/store.d.ts.map +1 -1
- package/dist/approval-api/store.js +10 -9
- package/dist/approval-api/store.js.map +1 -1
- package/dist/approval-api/tenant-context.d.ts +6 -6
- package/dist/approval-api/tenant-context.d.ts.map +1 -1
- package/dist/approval-api/tenant-context.js +20 -3
- package/dist/approval-api/tenant-context.js.map +1 -1
- package/dist/approval-api/tenant-store.d.ts +1 -1
- package/dist/approval-api/tenant-store.d.ts.map +1 -1
- package/dist/approval-api/types.d.ts +14 -7
- package/dist/approval-api/types.d.ts.map +1 -1
- package/dist/approval-api/types.js +2 -1
- package/dist/approval-api/types.js.map +1 -1
- package/dist/approval-ui/App.d.ts +2 -2
- package/dist/approval-ui/FilterBar.d.ts +3 -3
- package/dist/approval-ui/FilterBar.js +3 -3
- package/dist/approval-ui/client.d.ts +1 -1
- package/dist/approval-ui/components.d.ts +1 -1
- package/dist/approval-ui/stream.d.ts +3 -3
- package/dist/approval-ui/stream.js +2 -2
- package/dist/approval-ui/use-approval-dashboard.d.ts +9 -12
- package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
- package/dist/approval-ui/use-approval-dashboard.js +6 -9
- package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
- package/dist/approval-ui/use-web-socket-transport.d.ts +1 -1
- package/dist/approval-ui/use-web-socket-transport.js +1 -1
- package/dist/background-tasks/d1-storage.d.ts +3 -3
- package/dist/background-tasks/d1-storage.js +3 -3
- package/dist/background-tasks/host.d.ts +4 -4
- package/dist/background-tasks/host.js +2 -2
- package/dist/background-tasks/routes.js +3 -3
- package/dist/do-runner/breakwater-keys.d.ts +1 -1
- package/dist/do-runner/breakwater-keys.js +1 -1
- package/dist/do-runner/cf-types.d.ts +1 -1
- package/dist/do-runner/d1-storage.d.ts +37 -36
- package/dist/do-runner/d1-storage.d.ts.map +1 -1
- package/dist/do-runner/d1-storage.js +24 -23
- package/dist/do-runner/d1-storage.js.map +1 -1
- package/dist/do-runner/durable-object.d.ts +2 -2
- package/dist/do-runner/durable-object.d.ts.map +1 -1
- package/dist/do-runner/durable-object.js +5 -5
- package/dist/do-runner/durable-object.js.map +1 -1
- package/dist/do-runner/execution-context.d.ts +19 -0
- package/dist/do-runner/execution-context.d.ts.map +1 -0
- package/dist/do-runner/execution-context.js +70 -0
- package/dist/do-runner/execution-context.js.map +1 -0
- package/dist/do-runner/hub-do.d.ts +2 -2
- package/dist/do-runner/index.d.ts +2 -1
- package/dist/do-runner/index.d.ts.map +1 -1
- package/dist/do-runner/index.js +2 -1
- package/dist/do-runner/index.js.map +1 -1
- package/dist/do-runner/init.d.ts +1 -1
- package/dist/do-runner/memory-id.d.ts +3 -3
- package/dist/do-runner/memory-id.js +3 -3
- package/dist/do-runner/path-safe-id.d.ts +6 -6
- package/dist/do-runner/path-safe-id.js +6 -6
- package/dist/do-runner/runtime.d.ts +12 -5
- package/dist/do-runner/runtime.d.ts.map +1 -1
- package/dist/do-runner/runtime.js +158 -21
- package/dist/do-runner/runtime.js.map +1 -1
- package/dist/do-runner/thread-do.d.ts +8 -5
- package/dist/do-runner/thread-do.d.ts.map +1 -1
- package/dist/do-runner/thread-do.js +23 -6
- package/dist/do-runner/thread-do.js.map +1 -1
- package/dist/do-runner/thread-header.d.ts +2 -0
- package/dist/do-runner/thread-header.d.ts.map +1 -1
- package/dist/do-runner/thread-header.js +2 -0
- package/dist/do-runner/thread-header.js.map +1 -1
- package/dist/goals/objective-routes.d.ts +6 -6
- package/dist/goals/objective-routes.d.ts.map +1 -1
- package/dist/goals/objective-routes.js +3 -3
- package/dist/host-kit/approval-bridge.d.ts +14 -17
- package/dist/host-kit/approval-bridge.d.ts.map +1 -1
- package/dist/host-kit/approval-bridge.js +20 -20
- package/dist/host-kit/approval-bridge.js.map +1 -1
- package/dist/host-kit/bearer-auth.d.ts +1 -1
- package/dist/host-kit/bearer-auth.js +1 -1
- package/dist/host-kit/flowsafe-worker.d.ts +27 -14
- package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
- package/dist/host-kit/flowsafe-worker.js +9 -1
- package/dist/host-kit/flowsafe-worker.js.map +1 -1
- package/dist/host-kit/host-approval-service.d.ts +13 -13
- package/dist/host-kit/host-approval-service.js +10 -10
- package/dist/host-kit/index.d.ts +1 -1
- package/dist/host-kit/index.d.ts.map +1 -1
- package/dist/host-kit/index.js.map +1 -1
- package/dist/host-kit/memory-boundary.d.ts +1 -1
- package/dist/host-kit/memory-boundary.js +1 -1
- package/dist/host-kit/run-router.d.ts +10 -11
- package/dist/host-kit/run-router.d.ts.map +1 -1
- package/dist/host-kit/run-router.js.map +1 -1
- package/dist/host-kit/stream-router.d.ts +1 -1
- package/dist/host-kit/stream-router.d.ts.map +1 -1
- package/dist/host-kit/stream-ticket.d.ts +3 -3
- package/dist/host-kit/stream-ticket.d.ts.map +1 -1
- package/dist/host-kit/stream-ticket.js +1 -1
- package/dist/host-kit/tenant-registry.d.ts +1 -1
- package/dist/host-kit/tenant-registry.js +1 -1
- package/dist/host-kit/thread-topology.d.ts.map +1 -1
- package/dist/host-kit/thread-topology.js +3 -1
- package/dist/host-kit/thread-topology.js.map +1 -1
- package/dist/host-kit/verifier.d.ts +1 -1
- package/dist/host-kit/verifier.js +1 -1
- package/dist/index.d.ts +4 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -6
- package/dist/index.js.map +1 -1
- package/dist/schedules/router.d.ts +3 -3
- package/dist/schedules/router.d.ts.map +1 -1
- package/dist/schedules/router.js +2 -2
- package/dist/schedules/tick.d.ts +8 -11
- package/dist/schedules/tick.d.ts.map +1 -1
- package/dist/schedules/tick.js +11 -45
- package/dist/schedules/tick.js.map +1 -1
- package/dist/signal-providers/delivery.d.ts +1 -1
- package/dist/signal-providers/delivery.js +1 -1
- package/dist/signal-providers/host-do.d.ts +9 -7
- package/dist/signal-providers/host-do.d.ts.map +1 -1
- package/dist/signal-providers/host-do.js +28 -15
- package/dist/signal-providers/host-do.js.map +1 -1
- package/dist/signal-providers/host-topology.d.ts +27 -0
- package/dist/signal-providers/host-topology.d.ts.map +1 -0
- package/dist/signal-providers/host-topology.js +36 -0
- package/dist/signal-providers/host-topology.js.map +1 -0
- package/dist/signal-providers/index.d.ts +1 -0
- package/dist/signal-providers/index.d.ts.map +1 -1
- package/dist/signal-providers/index.js +2 -0
- package/dist/signal-providers/index.js.map +1 -1
- package/dist/signal-providers/provider.d.ts +8 -7
- package/dist/signal-providers/provider.d.ts.map +1 -1
- package/dist/signal-providers/provider.js +11 -9
- package/dist/signal-providers/provider.js.map +1 -1
- package/dist/signal-providers/subscription-d1.d.ts +3 -3
- package/dist/signal-providers/subscription-d1.d.ts.map +1 -1
- package/dist/signal-providers/subscription-d1.js +1 -1
- package/dist/signal-providers/subscription-d1.js.map +1 -1
- package/dist/signal-providers/webhook-route.d.ts +10 -2
- package/dist/signal-providers/webhook-route.d.ts.map +1 -1
- package/dist/signal-providers/webhook-route.js +55 -2
- package/dist/signal-providers/webhook-route.js.map +1 -1
- package/dist/signals/notifications-d1.d.ts +3 -4
- package/dist/signals/notifications-d1.d.ts.map +1 -1
- package/dist/signals/notifications-d1.js +3 -4
- package/dist/signals/notifications-d1.js.map +1 -1
- package/dist/signals/router.d.ts +1 -1
- package/dist/signals/router.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.d.ts +10 -5
- package/dist/signals/thread-do-routes.d.ts.map +1 -1
- package/dist/signals/thread-do-routes.js +54 -18
- package/dist/signals/thread-do-routes.js.map +1 -1
- package/package.json +6 -3
|
@@ -0,0 +1,636 @@
|
|
|
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 { RUN_START_ROLES, } 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
|
+
function sameActor(left, right) {
|
|
53
|
+
return (left.id === right.id &&
|
|
54
|
+
left.role === right.role &&
|
|
55
|
+
left.tenantId === right.tenantId);
|
|
56
|
+
}
|
|
57
|
+
const TERMINAL_RUN_STATUSES = [
|
|
58
|
+
'success',
|
|
59
|
+
'failed',
|
|
60
|
+
'tripwire',
|
|
61
|
+
'canceled',
|
|
62
|
+
'bailed',
|
|
63
|
+
'skipped',
|
|
64
|
+
];
|
|
65
|
+
function isTerminalRunStatus(status) {
|
|
66
|
+
return TERMINAL_RUN_STATUSES.includes(status);
|
|
67
|
+
}
|
|
68
|
+
function entryPath(value) {
|
|
69
|
+
const allowed = [
|
|
70
|
+
'http.start',
|
|
71
|
+
'approval.resume',
|
|
72
|
+
'signal.message',
|
|
73
|
+
'signal.queue',
|
|
74
|
+
'signal.reactive',
|
|
75
|
+
'signal.state',
|
|
76
|
+
'signal.notification',
|
|
77
|
+
'signal.wake',
|
|
78
|
+
'notification.dispatch',
|
|
79
|
+
'schedule.fire',
|
|
80
|
+
];
|
|
81
|
+
if (typeof value !== 'string' ||
|
|
82
|
+
!allowed.includes(value)) {
|
|
83
|
+
throw new AgentHostRequestError(400, 'entryPath is required');
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
function safeContext(value) {
|
|
88
|
+
if (value === undefined ||
|
|
89
|
+
(value !== null && typeof value === 'object' && !Array.isArray(value))) {
|
|
90
|
+
return sanitizeStoredAgentContext(value);
|
|
91
|
+
}
|
|
92
|
+
throw new AgentHostRequestError(400, 'safeContext must be an object');
|
|
93
|
+
}
|
|
94
|
+
function runRef(scope, input) {
|
|
95
|
+
const { agentId, threadId, resourceId, runId } = input;
|
|
96
|
+
if (typeof agentId !== 'string' ||
|
|
97
|
+
threadId !== scope.threadId ||
|
|
98
|
+
typeof resourceId !== 'string' ||
|
|
99
|
+
!tenantOwnsMemoryId(scope.tenantId, resourceId) ||
|
|
100
|
+
typeof runId !== 'string' ||
|
|
101
|
+
!tenantOwnsSaltedId(scope.tenantId, runId)) {
|
|
102
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
103
|
+
}
|
|
104
|
+
return { agentId, threadId: scope.threadId, resourceId, runId };
|
|
105
|
+
}
|
|
106
|
+
function audit(sink, event) {
|
|
107
|
+
try {
|
|
108
|
+
const result = sink?.(event);
|
|
109
|
+
if (result instanceof Promise)
|
|
110
|
+
void result.catch(() => undefined);
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
// Authorization is never made unavailable by an audit export failure.
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function ndjson(stream, initialOffset) {
|
|
117
|
+
const reader = stream.getReader();
|
|
118
|
+
const encoder = new TextEncoder();
|
|
119
|
+
let offset = initialOffset;
|
|
120
|
+
return new Response(new ReadableStream({
|
|
121
|
+
async pull(controller) {
|
|
122
|
+
const next = await reader.read();
|
|
123
|
+
if (next.done) {
|
|
124
|
+
controller.close();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
offset += 1;
|
|
128
|
+
controller.enqueue(encoder.encode(`${JSON.stringify({ offset, event: next.value })}\n`));
|
|
129
|
+
},
|
|
130
|
+
async cancel(reason) {
|
|
131
|
+
await reader.cancel(reason);
|
|
132
|
+
},
|
|
133
|
+
}), {
|
|
134
|
+
headers: {
|
|
135
|
+
'content-type': 'application/x-ndjson; charset=utf-8',
|
|
136
|
+
'cache-control': 'no-store',
|
|
137
|
+
'x-content-type-options': 'nosniff',
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
export function createThreadAgentHost(options) {
|
|
142
|
+
let catalogPromise;
|
|
143
|
+
let runtime;
|
|
144
|
+
const executions = new Map();
|
|
145
|
+
let stableScope;
|
|
146
|
+
let bindingTail = Promise.resolve();
|
|
147
|
+
const instanceScopeFor = (scope) => {
|
|
148
|
+
if (stableScope) {
|
|
149
|
+
if (stableScope.threadId !== scope.threadId ||
|
|
150
|
+
stableScope.tenantId !== scope.tenantId ||
|
|
151
|
+
stableScope.init !== scope.init) {
|
|
152
|
+
throw new Error('thread agent host cannot be shared across DO instances');
|
|
153
|
+
}
|
|
154
|
+
return stableScope;
|
|
155
|
+
}
|
|
156
|
+
stableScope = Object.freeze({
|
|
157
|
+
threadId: scope.threadId,
|
|
158
|
+
tenantId: scope.tenantId,
|
|
159
|
+
init: scope.init,
|
|
160
|
+
});
|
|
161
|
+
return stableScope;
|
|
162
|
+
};
|
|
163
|
+
const withBindingLock = async (operation) => {
|
|
164
|
+
const previous = bindingTail;
|
|
165
|
+
let release = () => undefined;
|
|
166
|
+
bindingTail = new Promise((resolve) => {
|
|
167
|
+
release = resolve;
|
|
168
|
+
});
|
|
169
|
+
await previous;
|
|
170
|
+
try {
|
|
171
|
+
return await operation();
|
|
172
|
+
}
|
|
173
|
+
finally {
|
|
174
|
+
release();
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
const catalogFor = async (scope) => {
|
|
178
|
+
catalogPromise ??= Promise.resolve(options.buildModules(instanceScopeFor(scope)))
|
|
179
|
+
.then(createAgentModuleCatalog)
|
|
180
|
+
.catch((error) => {
|
|
181
|
+
catalogPromise = undefined;
|
|
182
|
+
throw error;
|
|
183
|
+
});
|
|
184
|
+
return catalogPromise;
|
|
185
|
+
};
|
|
186
|
+
const runtimeFor = async (scope) => {
|
|
187
|
+
if (runtime) {
|
|
188
|
+
if (runtime.scopeRuntime !== scope.init.runtime) {
|
|
189
|
+
throw new Error('thread agent host cannot be shared across DO instances');
|
|
190
|
+
}
|
|
191
|
+
return runtime;
|
|
192
|
+
}
|
|
193
|
+
const catalog = await catalogFor(scope);
|
|
194
|
+
const mastra = new Mastra({
|
|
195
|
+
storage: options.storage(instanceScopeFor(scope)),
|
|
196
|
+
agents: Object.fromEntries(catalog.modules.map((module) => [
|
|
197
|
+
module.meta.id,
|
|
198
|
+
module.agent,
|
|
199
|
+
])),
|
|
200
|
+
...(scope.init.pubsub ? { pubsub: scope.init.pubsub } : {}),
|
|
201
|
+
});
|
|
202
|
+
const agents = new Map();
|
|
203
|
+
for (const module of catalog.modules) {
|
|
204
|
+
agents.set(module.meta.id, createFlowsafeDurableAgent({
|
|
205
|
+
agent: mastra.getAgent(module.meta.id),
|
|
206
|
+
runtime: scope.init.runtime,
|
|
207
|
+
pubsub: scope.init.pubsub,
|
|
208
|
+
threadRuntime: mastra.agentThreadStreamRuntime,
|
|
209
|
+
maxSteps: module.agent.maxSteps,
|
|
210
|
+
cache: options.cache,
|
|
211
|
+
}));
|
|
212
|
+
}
|
|
213
|
+
runtime = { scopeRuntime: scope.init.runtime, catalog, agents };
|
|
214
|
+
return runtime;
|
|
215
|
+
};
|
|
216
|
+
const authorize = async (scope, agentId, entry) => {
|
|
217
|
+
const current = await runtimeFor(scope);
|
|
218
|
+
const module = current.catalog.get(agentId);
|
|
219
|
+
const allowed = current.catalog.allowedRoles(agentId);
|
|
220
|
+
const granted = module !== undefined &&
|
|
221
|
+
RUN_START_ROLES.includes(scope.actor.role) &&
|
|
222
|
+
allowed?.includes(scope.actor.role) === true;
|
|
223
|
+
audit(options.audit, {
|
|
224
|
+
actor: scope.actor,
|
|
225
|
+
action: 'agent.entry.authorize',
|
|
226
|
+
resource: `agent:${agentId}`,
|
|
227
|
+
decision: granted ? 'allowed' : 'denied',
|
|
228
|
+
...(!granted
|
|
229
|
+
? { reason: 'role is not allowed to mutate this agent' }
|
|
230
|
+
: {}),
|
|
231
|
+
detail: {
|
|
232
|
+
agentId,
|
|
233
|
+
tenantId: scope.tenantId,
|
|
234
|
+
threadId: scope.threadId,
|
|
235
|
+
entryPath: entry,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
if (!module)
|
|
239
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
240
|
+
if (!granted)
|
|
241
|
+
throw new AgentHostRequestError(403, 'forbidden');
|
|
242
|
+
return { current, module };
|
|
243
|
+
};
|
|
244
|
+
const readBinding = () => readAgentThreadBinding(options.stateStorage());
|
|
245
|
+
const readRun = (runId) => readAgentRunRecord(options.stateStorage(), runId);
|
|
246
|
+
const withExecution = async (execution, operation) => {
|
|
247
|
+
if (executions.has(execution.runId)) {
|
|
248
|
+
throw new AgentHostRequestError(409, `run '${execution.runId}' already has an active operation`);
|
|
249
|
+
}
|
|
250
|
+
executions.set(execution.runId, execution);
|
|
251
|
+
try {
|
|
252
|
+
return await operation();
|
|
253
|
+
}
|
|
254
|
+
finally {
|
|
255
|
+
executions.delete(execution.runId);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
const systemActor = (scope) => ({
|
|
259
|
+
id: options.systemActorId ?? 'flowsafe-system',
|
|
260
|
+
role: 'operator',
|
|
261
|
+
tenantId: scope.tenantId,
|
|
262
|
+
});
|
|
263
|
+
const currentApprovals = async (scope, summary, principal, agentId, resourceId) => {
|
|
264
|
+
if (summary.status !== 'suspended')
|
|
265
|
+
return [];
|
|
266
|
+
const service = options.approvalService(instanceScopeFor(scope));
|
|
267
|
+
await reconcileApprovalsForSummary(service, DURABLE_AGENTIC_LOOP_WORKFLOW_ID, summary, systemActor(scope), {
|
|
268
|
+
kind: 'agent-thread',
|
|
269
|
+
agentId,
|
|
270
|
+
threadId: scope.threadId,
|
|
271
|
+
resourceId,
|
|
272
|
+
principal,
|
|
273
|
+
}, principal.id);
|
|
274
|
+
const records = await service.list({
|
|
275
|
+
workflowId: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
|
|
276
|
+
runId: summary.runId,
|
|
277
|
+
}, systemActor(scope));
|
|
278
|
+
const keys = new Set((summary.suspended ?? []).map((path) => path.join('.')));
|
|
279
|
+
return records.filter((record) => {
|
|
280
|
+
const key = record.stepPath?.join('.');
|
|
281
|
+
return (key !== undefined &&
|
|
282
|
+
keys.has(key) &&
|
|
283
|
+
record.suspendedAt === summary.suspendedAt?.[key] &&
|
|
284
|
+
record.resumeCount === summary.resumeCount?.[key]);
|
|
285
|
+
});
|
|
286
|
+
};
|
|
287
|
+
const envelopeFor = async (scope, ref, principal, summary) => {
|
|
288
|
+
const base = {
|
|
289
|
+
agentId: ref.agentId,
|
|
290
|
+
threadId: scope.threadId,
|
|
291
|
+
resourceId: ref.resourceId,
|
|
292
|
+
runId: ref.runId,
|
|
293
|
+
summary,
|
|
294
|
+
};
|
|
295
|
+
if (summary.status !== 'suspended')
|
|
296
|
+
return base;
|
|
297
|
+
const approvals = await currentApprovals(scope, summary, principal, ref.agentId, ref.resourceId);
|
|
298
|
+
return {
|
|
299
|
+
...base,
|
|
300
|
+
...(approvals[0] ? { approval: approvals[0] } : {}),
|
|
301
|
+
approvals,
|
|
302
|
+
};
|
|
303
|
+
};
|
|
304
|
+
const snapshotExecutionFor = async (scope, ref) => {
|
|
305
|
+
const workflows = await options
|
|
306
|
+
.storage(instanceScopeFor(scope))
|
|
307
|
+
.getStore('workflows');
|
|
308
|
+
const snapshot = await workflows?.loadWorkflowSnapshot({
|
|
309
|
+
workflowName: DURABLE_AGENTIC_LOOP_WORKFLOW_ID,
|
|
310
|
+
runId: ref.runId,
|
|
311
|
+
});
|
|
312
|
+
const input = snapshot?.context.input;
|
|
313
|
+
const requestContext = snapshot?.requestContext;
|
|
314
|
+
const correlation = requestContext?.['breakwater.auditContext'];
|
|
315
|
+
const memory = input?.messageListState?.memoryInfo;
|
|
316
|
+
const memoryMatches = memory === null ||
|
|
317
|
+
(memory?.threadId === scope.threadId &&
|
|
318
|
+
memory.resourceId === ref.resourceId);
|
|
319
|
+
if (input?.agentId !== ref.agentId ||
|
|
320
|
+
requestContext?.runId !== ref.runId ||
|
|
321
|
+
requestContext.threadId !== scope.threadId ||
|
|
322
|
+
requestContext.resourceId !== ref.resourceId ||
|
|
323
|
+
correlation?.agentId !== ref.agentId ||
|
|
324
|
+
correlation.threadId !== scope.threadId ||
|
|
325
|
+
correlation.resourceId !== ref.resourceId ||
|
|
326
|
+
!memoryMatches) {
|
|
327
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
threaded: memory !== null,
|
|
331
|
+
safeContext: sanitizeStoredAgentContext(requestContext),
|
|
332
|
+
};
|
|
333
|
+
};
|
|
334
|
+
const statusFor = async (scope, ref, knownThreaded) => {
|
|
335
|
+
const binding = await readBinding();
|
|
336
|
+
const current = await runtimeFor(scope);
|
|
337
|
+
if (!current.catalog.get(ref.agentId)) {
|
|
338
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
339
|
+
}
|
|
340
|
+
const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
|
|
341
|
+
if (!summary)
|
|
342
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
343
|
+
const threaded = knownThreaded ?? (await snapshotExecutionFor(scope, ref)).threaded;
|
|
344
|
+
const bindingMatches = binding?.agentId === ref.agentId && binding.resourceId === ref.resourceId;
|
|
345
|
+
if ((threaded && !bindingMatches) || (!threaded && binding)) {
|
|
346
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
347
|
+
}
|
|
348
|
+
const stored = await readRun(ref.runId);
|
|
349
|
+
if (stored && stored.agentId !== ref.agentId) {
|
|
350
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
351
|
+
}
|
|
352
|
+
if (summary.status === 'suspended' && !stored) {
|
|
353
|
+
throw new AgentHostRequestError(409, 'suspended agent run has no recoverable execution principal');
|
|
354
|
+
}
|
|
355
|
+
const principal = stored?.principal ?? scope.actor;
|
|
356
|
+
const result = await envelopeFor(scope, ref, principal, summary);
|
|
357
|
+
if (isTerminalRunStatus(summary.status) && stored) {
|
|
358
|
+
await deleteAgentRunRecord(options.stateStorage(), ref.runId);
|
|
359
|
+
}
|
|
360
|
+
return result;
|
|
361
|
+
};
|
|
362
|
+
const host = {
|
|
363
|
+
requestContextForRun: (base) => async (workflowId, runId, leg) => {
|
|
364
|
+
const values = base ? await base(workflowId, runId, leg) : undefined;
|
|
365
|
+
const execution = executions.get(runId);
|
|
366
|
+
return execution && workflowId === DURABLE_AGENTIC_LOOP_WORKFLOW_ID
|
|
367
|
+
? {
|
|
368
|
+
...execution.safeContext,
|
|
369
|
+
...values,
|
|
370
|
+
...deriveTrustedAgentContext(execution, {}),
|
|
371
|
+
}
|
|
372
|
+
: values;
|
|
373
|
+
},
|
|
374
|
+
start: async (scope, input) => {
|
|
375
|
+
const ref = runRef(scope, input);
|
|
376
|
+
const hasPrompt = input.prompt !== undefined;
|
|
377
|
+
const hasMessages = input.messages !== undefined;
|
|
378
|
+
if (hasPrompt === hasMessages ||
|
|
379
|
+
(hasPrompt &&
|
|
380
|
+
(typeof input.prompt !== 'string' ||
|
|
381
|
+
input.prompt.trim() === '' ||
|
|
382
|
+
input.prompt.length > 10_000))) {
|
|
383
|
+
throw new AgentHostRequestError(400, 'exactly one valid prompt or messages input is required');
|
|
384
|
+
}
|
|
385
|
+
const messages = input.messages ?? input.prompt;
|
|
386
|
+
if (messages === undefined) {
|
|
387
|
+
throw new AgentHostRequestError(400, 'agent input is required');
|
|
388
|
+
}
|
|
389
|
+
const entry = entryPath(input.entryPath);
|
|
390
|
+
const { current, module } = await authorize(scope, ref.agentId, entry);
|
|
391
|
+
if (ref.resourceId !== mintResourceId(scope.tenantId, scope.threadId)) {
|
|
392
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
393
|
+
}
|
|
394
|
+
const execution = {
|
|
395
|
+
agentId: ref.agentId,
|
|
396
|
+
actor: scope.actor,
|
|
397
|
+
threadId: scope.threadId,
|
|
398
|
+
resourceId: ref.resourceId,
|
|
399
|
+
runId: ref.runId,
|
|
400
|
+
entryPath: entry,
|
|
401
|
+
safeContext: safeContext(input.safeContext),
|
|
402
|
+
};
|
|
403
|
+
const durable = current.agents.get(module.meta.id);
|
|
404
|
+
if (!durable)
|
|
405
|
+
throw new Error('guarded agent was not registered');
|
|
406
|
+
return withExecution(execution, async () => {
|
|
407
|
+
const existingRecord = await readRun(ref.runId);
|
|
408
|
+
const existingSummary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
|
|
409
|
+
if (existingRecord || existingSummary) {
|
|
410
|
+
throw new AgentHostRequestError(409, `run '${ref.runId}' already exists`);
|
|
411
|
+
}
|
|
412
|
+
if (input.threaded !== false) {
|
|
413
|
+
await withBindingLock(async () => {
|
|
414
|
+
const existing = await readBinding();
|
|
415
|
+
const bindingMatches = existing?.agentId === ref.agentId &&
|
|
416
|
+
existing.resourceId === ref.resourceId;
|
|
417
|
+
if (entry === 'schedule.fire') {
|
|
418
|
+
if (!bindingMatches) {
|
|
419
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
420
|
+
}
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (existing && !bindingMatches) {
|
|
424
|
+
throw new AgentHostRequestError(409, 'thread is bound to another agent');
|
|
425
|
+
}
|
|
426
|
+
if (!existing) {
|
|
427
|
+
await bindAgentThread(options.stateStorage(), {
|
|
428
|
+
version: 1,
|
|
429
|
+
agentId: ref.agentId,
|
|
430
|
+
resourceId: ref.resourceId,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
const stored = {
|
|
436
|
+
version: 1,
|
|
437
|
+
agentId: ref.agentId,
|
|
438
|
+
principal: scope.actor,
|
|
439
|
+
originEntryPath: entry,
|
|
440
|
+
};
|
|
441
|
+
await writeAgentRunRecord(options.stateStorage(), ref.runId, stored);
|
|
442
|
+
try {
|
|
443
|
+
await durable.streamUntilPersisted(messages, {
|
|
444
|
+
runId: ref.runId,
|
|
445
|
+
requestContext: createTrustedAgentRequestContext(execution),
|
|
446
|
+
...(input.threaded !== false
|
|
447
|
+
? {
|
|
448
|
+
memory: {
|
|
449
|
+
thread: scope.threadId,
|
|
450
|
+
resource: ref.resourceId,
|
|
451
|
+
},
|
|
452
|
+
}
|
|
453
|
+
: {}),
|
|
454
|
+
maxSteps: module.agent.maxSteps,
|
|
455
|
+
disableBackgroundTasks: true,
|
|
456
|
+
});
|
|
457
|
+
const summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
|
|
458
|
+
if (!summary)
|
|
459
|
+
throw new Error('agent run did not persist a summary');
|
|
460
|
+
const result = await envelopeFor(scope, ref, scope.actor, summary);
|
|
461
|
+
if (isTerminalRunStatus(result.summary.status)) {
|
|
462
|
+
await deleteAgentRunRecord(options.stateStorage(), ref.runId);
|
|
463
|
+
}
|
|
464
|
+
return result;
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
let summary;
|
|
468
|
+
try {
|
|
469
|
+
summary = await scope.init.runtime.status(DURABLE_AGENTIC_LOOP_WORKFLOW_ID, ref.runId);
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
// Unknown authoritative state: retain metadata and fail closed.
|
|
473
|
+
}
|
|
474
|
+
if (!summary || isTerminalRunStatus(summary.status)) {
|
|
475
|
+
await deleteAgentRunRecord(options.stateStorage(), ref.runId);
|
|
476
|
+
}
|
|
477
|
+
throw error;
|
|
478
|
+
}
|
|
479
|
+
});
|
|
480
|
+
},
|
|
481
|
+
resolveBoundAgent: async (scope, input) => {
|
|
482
|
+
const binding = await readBinding();
|
|
483
|
+
if (!binding)
|
|
484
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
485
|
+
if (binding.resourceId !== mintResourceId(scope.tenantId, scope.threadId)) {
|
|
486
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
487
|
+
}
|
|
488
|
+
if (input.agentId && input.agentId !== binding.agentId) {
|
|
489
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
490
|
+
}
|
|
491
|
+
const { current } = await authorize(scope, binding.agentId, entryPath(input.entryPath));
|
|
492
|
+
const durableAgent = current.agents.get(binding.agentId);
|
|
493
|
+
if (!durableAgent)
|
|
494
|
+
throw new Error('guarded agent was not registered');
|
|
495
|
+
return {
|
|
496
|
+
agentId: binding.agentId,
|
|
497
|
+
resourceId: binding.resourceId,
|
|
498
|
+
durableAgent,
|
|
499
|
+
};
|
|
500
|
+
},
|
|
501
|
+
route: async (request, scope) => {
|
|
502
|
+
const url = new URL(request.url);
|
|
503
|
+
if (!url.pathname.startsWith(AGENT_HOST_ROUTE_PREFIX))
|
|
504
|
+
return null;
|
|
505
|
+
if (request.method === 'POST' &&
|
|
506
|
+
url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/start`) {
|
|
507
|
+
const body = await objectBody(request);
|
|
508
|
+
const ref = runRef(scope, body);
|
|
509
|
+
if (typeof body.prompt !== 'string') {
|
|
510
|
+
throw new AgentHostRequestError(400, 'prompt is required');
|
|
511
|
+
}
|
|
512
|
+
return json(await host.start(scope, {
|
|
513
|
+
...ref,
|
|
514
|
+
prompt: body.prompt,
|
|
515
|
+
entryPath: entryPath(body.entryPath),
|
|
516
|
+
threaded: body.threaded !== false,
|
|
517
|
+
safeContext: safeContext(body.safeContext),
|
|
518
|
+
}));
|
|
519
|
+
}
|
|
520
|
+
if (request.method === 'POST' &&
|
|
521
|
+
url.pathname === `${AGENT_HOST_ROUTE_PREFIX}/resume`) {
|
|
522
|
+
const body = await objectBody(request);
|
|
523
|
+
const ref = runRef(scope, body);
|
|
524
|
+
const snapshotExecution = await snapshotExecutionFor(scope, ref);
|
|
525
|
+
await statusFor(scope, ref, snapshotExecution.threaded);
|
|
526
|
+
const stored = await readRun(ref.runId);
|
|
527
|
+
if (!stored ||
|
|
528
|
+
stored.agentId !== ref.agentId ||
|
|
529
|
+
!sameActor(stored.principal, scope.actor)) {
|
|
530
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
531
|
+
}
|
|
532
|
+
const { current, module } = await authorize(scope, ref.agentId, entryPath(body.entryPath));
|
|
533
|
+
const durable = current.agents.get(module.meta.id);
|
|
534
|
+
if (!durable)
|
|
535
|
+
throw new Error('guarded agent was not registered');
|
|
536
|
+
const step = typeof body.step === 'string' ||
|
|
537
|
+
(Array.isArray(body.step) &&
|
|
538
|
+
body.step.every((part) => typeof part === 'string'))
|
|
539
|
+
? body.step
|
|
540
|
+
: undefined;
|
|
541
|
+
const execution = {
|
|
542
|
+
agentId: ref.agentId,
|
|
543
|
+
actor: stored.principal,
|
|
544
|
+
threadId: scope.threadId,
|
|
545
|
+
resourceId: ref.resourceId,
|
|
546
|
+
runId: ref.runId,
|
|
547
|
+
entryPath: 'approval.resume',
|
|
548
|
+
safeContext: snapshotExecution.safeContext,
|
|
549
|
+
};
|
|
550
|
+
const summary = await withExecution(execution, () => durable.resumeViaRuntime({
|
|
551
|
+
runId: ref.runId,
|
|
552
|
+
...(step !== undefined ? { step } : {}),
|
|
553
|
+
...('resumeData' in body ? { resumeData: body.resumeData } : {}),
|
|
554
|
+
...(snapshotExecution.threaded
|
|
555
|
+
? {
|
|
556
|
+
memory: {
|
|
557
|
+
thread: scope.threadId,
|
|
558
|
+
resource: ref.resourceId,
|
|
559
|
+
},
|
|
560
|
+
}
|
|
561
|
+
: {}),
|
|
562
|
+
}));
|
|
563
|
+
const result = await envelopeFor(scope, ref, stored.principal, summary);
|
|
564
|
+
if (isTerminalRunStatus(summary.status)) {
|
|
565
|
+
await deleteAgentRunRecord(options.stateStorage(), ref.runId);
|
|
566
|
+
}
|
|
567
|
+
return json(result);
|
|
568
|
+
}
|
|
569
|
+
const suffix = url.pathname.slice(AGENT_HOST_ROUTE_PREFIX.length);
|
|
570
|
+
const segments = suffix.split('/').filter(Boolean);
|
|
571
|
+
if (segments[0] !== 'runs')
|
|
572
|
+
return json({ error: 'not found' }, 404);
|
|
573
|
+
const agentId = decode(segments[1]);
|
|
574
|
+
const runId = decode(segments[2]);
|
|
575
|
+
const resourceId = url.searchParams.get('resourceId');
|
|
576
|
+
if (!agentId || !runId || !resourceId) {
|
|
577
|
+
throw new AgentHostRequestError(404, 'run not found');
|
|
578
|
+
}
|
|
579
|
+
const ref = runRef(scope, {
|
|
580
|
+
agentId,
|
|
581
|
+
threadId: scope.threadId,
|
|
582
|
+
resourceId,
|
|
583
|
+
runId,
|
|
584
|
+
});
|
|
585
|
+
if (segments.length === 3 && request.method === 'GET') {
|
|
586
|
+
return json(await statusFor(scope, ref));
|
|
587
|
+
}
|
|
588
|
+
if (segments.length === 4 &&
|
|
589
|
+
segments[3] === 'stream' &&
|
|
590
|
+
request.method === 'GET') {
|
|
591
|
+
const run = await statusFor(scope, ref);
|
|
592
|
+
const offset = Number(url.searchParams.get('offset') ?? '0');
|
|
593
|
+
if (!Number.isSafeInteger(offset) || offset < 0) {
|
|
594
|
+
throw new AgentHostRequestError(400, 'invalid stream offset');
|
|
595
|
+
}
|
|
596
|
+
const current = await runtimeFor(scope);
|
|
597
|
+
const durable = current.agents.get(ref.agentId);
|
|
598
|
+
if (!durable)
|
|
599
|
+
throw new AgentHostRequestError(404, 'agent not found');
|
|
600
|
+
const live = durable.runRegistry.has(ref.runId);
|
|
601
|
+
let historyLength = 0;
|
|
602
|
+
try {
|
|
603
|
+
const history = await durable.pubsub.getHistory(AGENT_STREAM_TOPIC(ref.runId));
|
|
604
|
+
historyLength = Array.isArray(history) ? history.length : 0;
|
|
605
|
+
}
|
|
606
|
+
catch {
|
|
607
|
+
// A live registry can still serve future events in this isolate.
|
|
608
|
+
}
|
|
609
|
+
if (!live && historyLength === 0) {
|
|
610
|
+
throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
|
|
611
|
+
}
|
|
612
|
+
if (isTerminalRunStatus(run.summary.status)) {
|
|
613
|
+
if (historyLength === 0) {
|
|
614
|
+
throw new AgentHostRequestError(409, 'stream replay is unavailable; inspect the authoritative status endpoint');
|
|
615
|
+
}
|
|
616
|
+
if (offset >= historyLength) {
|
|
617
|
+
return ndjson(new ReadableStream({
|
|
618
|
+
start(controller) {
|
|
619
|
+
controller.close();
|
|
620
|
+
},
|
|
621
|
+
}), offset);
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
const observed = await durable.observe(ref.runId, { offset });
|
|
625
|
+
return ndjson(observed.fullStream, offset);
|
|
626
|
+
}
|
|
627
|
+
const known = segments.length === 3 ||
|
|
628
|
+
(segments.length === 4 && segments[3] === 'stream');
|
|
629
|
+
return known
|
|
630
|
+
? json({ error: 'method not allowed' }, 405)
|
|
631
|
+
: json({ error: 'not found' }, 404);
|
|
632
|
+
},
|
|
633
|
+
};
|
|
634
|
+
return host;
|
|
635
|
+
}
|
|
636
|
+
//# sourceMappingURL=thread-host.js.map
|