@swirls/looms 0.12.3 → 0.13.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 +26 -0
- package/dist/agent/definitions.d.ts +5 -0
- package/dist/agent/effects.d.ts +261 -260
- package/dist/agent/effects.js +9 -2
- package/dist/agent/module.d.ts +2 -0
- package/dist/agent/stop-when.d.ts +5 -0
- package/dist/agent/stop-when.js +1 -0
- package/dist/agent/threads.js +9 -0
- package/dist/agent/types.d.ts +6 -0
- package/dist/cloudflare/index.d.ts +1 -1
- package/dist/cloudflare/router.d.ts +14 -0
- package/dist/cloudflare/router.js +32 -0
- package/dist/runtime/index.d.ts +1 -1
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/local-effect-executor.js +15 -7
- package/dist/runtime/runtime.js +3 -1
- package/dist/runtime/server/auth.d.ts +22 -0
- package/dist/runtime/server/auth.js +22 -0
- package/dist/runtime/server/fetch-handler.d.ts +10 -1
- package/dist/runtime/server/fetch-handler.js +46 -14
- package/dist/runtime/server/route-table.d.ts +2 -0
- package/dist/runtime/server/routes/runs.js +13 -4
- package/dist/runtime/server.d.ts +2 -2
- package/dist/runtime/server.js +2 -2
- package/dist/runtime/wake-engine.js +4 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,31 @@
|
|
|
1
1
|
# @swirls/looms
|
|
2
2
|
|
|
3
|
+
## 0.13.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 70b0f88: Let `authorize` say who a request acts as, and decide in a Cloudflare Worker.
|
|
8
|
+
|
|
9
|
+
- An allowed `AuthDecision` may carry `actorId` (`authAllowedAs(actorId)`). Events sent through
|
|
10
|
+
`POST /runs/:runId/events` and named signals are then recorded with
|
|
11
|
+
`origin: { type: 'external', actorId }`, replacing any origin the request claimed.
|
|
12
|
+
- `RouteInfo` has `signal` (`namespace/name`) for named signal requests, so a policy can allow
|
|
13
|
+
specific signals.
|
|
14
|
+
- `describeRoute(method, pathname)` describes a request's Looms route without a runtime.
|
|
15
|
+
- `routeToDurableObject` takes `authorize`, checked in the Worker before a request is forwarded. The
|
|
16
|
+
actor it names reaches the Durable Object in a header clients cannot set; `forwardedActorAuth()`
|
|
17
|
+
on the object records it.
|
|
18
|
+
|
|
19
|
+
## 0.12.4
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- b8b1759: Count `maxTurns` per user message for conversational agents. The turn counter ran over the whole conversation, so a chat with `maxTurns: 3` failed with "Max turns exceeded" on its fourth reply. A conversational agent now counts model turns from its latest user message (or steer), so the limit bounds the work spent on one reply. Agents that are not conversational still count every turn of the run.
|
|
24
|
+
- b8b1759: Make `stopAgentTurn()` and an interrupting `steer()` abort the in-flight model call when sent without a thread id. The signal was recorded on the root thread, but the interrupt lookup only matched an explicit `threadId`, so the adapter's `signal` never aborted and the full reply was appended after the stop. A signal without a thread id now interrupts the root thread and its children, for conversational agents and agent sessions alike.
|
|
25
|
+
- b8b1759: Count `stopWhen` steps per user message for conversational agents. `stopWhen` received the thread's lifetime turn number, so `stepCountIs(8)` on a conversational agent stopped every turn after the eighth and dropped its tool calls. The `turn` passed to `stopWhen` now counts from the latest user message for a conversational agent, the same way `maxTurns` does. Other agents are unchanged.
|
|
26
|
+
- b8b1759: Keep text deltas that were streamed just before a turn was stopped. Live events are written in the background, and a wake whose only attempt was aborted released the run without flushing them, so a delta emitted moments before `stopAgentTurn()` could be missing from the log. The wake now flushes pending live events before it parks.
|
|
27
|
+
- b8b1759: Keep a run alive when a message follows a stopped agent turn. A model call that was stopped mid-stream could emit one more text delta after its turn was abandoned. That late write failed, and the failure stuck to the run, so the next turn's first `onTextDelta` threw "Cannot append live events without a store" and the run failed. Live events from an attempt that has been aborted or has finished are now dropped.
|
|
28
|
+
|
|
3
29
|
## 0.12.3
|
|
4
30
|
|
|
5
31
|
### Patch Changes
|
|
@@ -114,7 +114,12 @@ export interface AgentDefinition<TName extends string = string, TInput = JsonVal
|
|
|
114
114
|
resolveTools?(ctx: AgentToolResolutionContext<TInput>): Promise<readonly AgentToolEntry[]> | readonly AgentToolEntry[];
|
|
115
115
|
/** Shrinks the conversation after the model reports a context overflow. */
|
|
116
116
|
readonly compact?: AgentCompactor;
|
|
117
|
+
/**
|
|
118
|
+
* Most model turns the agent may take before its thread fails. Default 20. A conversational
|
|
119
|
+
* agent counts from its latest user message, so the limit bounds one reply.
|
|
120
|
+
*/
|
|
117
121
|
readonly maxTurns?: number;
|
|
122
|
+
/** Keep the run open after a reply so the next user message starts another turn. */
|
|
118
123
|
readonly conversational?: boolean;
|
|
119
124
|
readonly stopWhen?: StopWhen;
|
|
120
125
|
runTurn?(ctx: AgentTurnContext<TInput>): Promise<AgentTurnResult<TOutput>> | AgentTurnResult<TOutput>;
|
package/dist/agent/effects.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { LlmTag } from './llm';
|
|
|
5
5
|
import { type ToolCall } from './types';
|
|
6
6
|
export declare const callLlmEffect: NoInfer<import("@swirls/looms/core").LocalEffectDefinition<{
|
|
7
7
|
readonly turn: number;
|
|
8
|
+
readonly messageTurn?: number | undefined;
|
|
8
9
|
readonly definitionName?: string | undefined;
|
|
9
10
|
readonly definitionVersion: string;
|
|
10
11
|
readonly messages?: readonly {
|
|
@@ -23,252 +24,6 @@ export declare const callLlmEffect: NoInfer<import("@swirls/looms/core").LocalEf
|
|
|
23
24
|
readonly alreadyCompacted?: boolean | undefined;
|
|
24
25
|
readonly consumedSteerMessageIds?: readonly string[] | undefined;
|
|
25
26
|
}, AgentDefinitionsTag | LlmTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
26
|
-
readonly type: "runtime.child.close.requested";
|
|
27
|
-
readonly payload: {
|
|
28
|
-
readonly policy: "terminate" | "wait";
|
|
29
|
-
};
|
|
30
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
31
|
-
readonly type: "runtime.child.settled";
|
|
32
|
-
readonly payload: {
|
|
33
|
-
readonly runId: string;
|
|
34
|
-
readonly status: "cancelled" | "completed" | "failed";
|
|
35
|
-
readonly output: Schema.Json;
|
|
36
|
-
readonly error: string | null;
|
|
37
|
-
};
|
|
38
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
39
|
-
readonly type: "runtime.effect.ambiguous";
|
|
40
|
-
readonly payload: {
|
|
41
|
-
readonly effectId: string;
|
|
42
|
-
readonly attempt: number;
|
|
43
|
-
readonly error: string;
|
|
44
|
-
};
|
|
45
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
46
|
-
readonly type: "runtime.effect.attempt.started";
|
|
47
|
-
readonly payload: {
|
|
48
|
-
readonly effectId: string;
|
|
49
|
-
readonly attempt: number;
|
|
50
|
-
};
|
|
51
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
52
|
-
readonly type: "runtime.effect.cancel.requested";
|
|
53
|
-
readonly payload: {
|
|
54
|
-
readonly effectId: string;
|
|
55
|
-
readonly attempt: number;
|
|
56
|
-
readonly deadlineAt: number | null;
|
|
57
|
-
};
|
|
58
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
59
|
-
readonly type: "runtime.effect.cancelled";
|
|
60
|
-
readonly payload: {
|
|
61
|
-
readonly effectId: string;
|
|
62
|
-
readonly attempt: number;
|
|
63
|
-
};
|
|
64
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
65
|
-
readonly type: "runtime.effect.completed";
|
|
66
|
-
readonly payload: {
|
|
67
|
-
readonly effectId: string;
|
|
68
|
-
readonly attempt: number;
|
|
69
|
-
};
|
|
70
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
71
|
-
readonly type: "runtime.effect.dispatch.deferred";
|
|
72
|
-
readonly payload: {
|
|
73
|
-
readonly effectId: string;
|
|
74
|
-
readonly attempt: number;
|
|
75
|
-
readonly retryAt: number;
|
|
76
|
-
readonly error: string;
|
|
77
|
-
readonly try: number;
|
|
78
|
-
};
|
|
79
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
80
|
-
readonly type: "runtime.effect.dispatched";
|
|
81
|
-
readonly payload: {
|
|
82
|
-
readonly effectId: string;
|
|
83
|
-
readonly attempt: number;
|
|
84
|
-
readonly deadlineAt: number | null;
|
|
85
|
-
};
|
|
86
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
87
|
-
readonly type: "runtime.effect.failed";
|
|
88
|
-
readonly payload: {
|
|
89
|
-
readonly effectId: string;
|
|
90
|
-
readonly error: string;
|
|
91
|
-
readonly nonRetryable?: boolean | undefined;
|
|
92
|
-
readonly retryAfterMs?: number | undefined;
|
|
93
|
-
};
|
|
94
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
95
|
-
readonly type: "runtime.effect.heartbeat";
|
|
96
|
-
readonly payload: {
|
|
97
|
-
readonly effectId: string;
|
|
98
|
-
readonly attempt: number;
|
|
99
|
-
readonly heartbeatAt: number;
|
|
100
|
-
readonly deadlineAt: number | null;
|
|
101
|
-
readonly details?: Schema.Json | undefined;
|
|
102
|
-
};
|
|
103
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
104
|
-
readonly type: "runtime.effect.queued";
|
|
105
|
-
readonly payload: {
|
|
106
|
-
readonly effectId: string;
|
|
107
|
-
readonly attempt: number;
|
|
108
|
-
readonly deadlineAt: number | null;
|
|
109
|
-
};
|
|
110
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
111
|
-
readonly type: "runtime.effect.retry.scheduled";
|
|
112
|
-
readonly payload: {
|
|
113
|
-
readonly effectId: string;
|
|
114
|
-
readonly attempt: number;
|
|
115
|
-
readonly nextAttemptAt: number;
|
|
116
|
-
readonly error: string;
|
|
117
|
-
};
|
|
118
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
119
|
-
readonly type: "runtime.effect.timed_out";
|
|
120
|
-
readonly payload: {
|
|
121
|
-
readonly effectId: string;
|
|
122
|
-
readonly attempt: number;
|
|
123
|
-
readonly timeout: string;
|
|
124
|
-
};
|
|
125
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
126
|
-
readonly type: "runtime.effect.worker.started";
|
|
127
|
-
readonly payload: {
|
|
128
|
-
readonly effectId: string;
|
|
129
|
-
readonly attempt: number;
|
|
130
|
-
readonly deadlineAt: number | null;
|
|
131
|
-
};
|
|
132
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
133
|
-
readonly type: "runtime.fork.elided";
|
|
134
|
-
readonly payload: {
|
|
135
|
-
readonly type: string;
|
|
136
|
-
};
|
|
137
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
138
|
-
readonly type: "runtime.run.cancelled";
|
|
139
|
-
readonly payload: {
|
|
140
|
-
readonly reason?: string | undefined;
|
|
141
|
-
};
|
|
142
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
143
|
-
readonly type: "runtime.run.completed";
|
|
144
|
-
readonly payload: {
|
|
145
|
-
readonly output: Schema.Json;
|
|
146
|
-
readonly error: string | null;
|
|
147
|
-
};
|
|
148
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
149
|
-
readonly type: "runtime.run.forked";
|
|
150
|
-
readonly payload: {
|
|
151
|
-
readonly sourceRunId: string;
|
|
152
|
-
readonly sourceSeq: number;
|
|
153
|
-
};
|
|
154
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
155
|
-
readonly type: "runtime.run.launched";
|
|
156
|
-
readonly payload: {
|
|
157
|
-
readonly runId: string;
|
|
158
|
-
readonly kind: string;
|
|
159
|
-
readonly definitionName: string;
|
|
160
|
-
readonly definitionVersion: string;
|
|
161
|
-
readonly effectId: string;
|
|
162
|
-
readonly close: "terminate" | "wait";
|
|
163
|
-
};
|
|
164
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
165
|
-
readonly type: "runtime.run.started";
|
|
166
|
-
readonly payload: {
|
|
167
|
-
readonly rootThreadId?: string | undefined;
|
|
168
|
-
readonly kind: string;
|
|
169
|
-
readonly definitionName: string;
|
|
170
|
-
readonly definitionVersion: string;
|
|
171
|
-
readonly input: Schema.Json;
|
|
172
|
-
readonly requestedThreadId?: string | null | undefined;
|
|
173
|
-
readonly launchedBy?: {
|
|
174
|
-
readonly runId: string;
|
|
175
|
-
readonly threadId: string;
|
|
176
|
-
readonly effectId: string;
|
|
177
|
-
readonly causationId: string;
|
|
178
|
-
readonly causationSeq: number;
|
|
179
|
-
} | undefined;
|
|
180
|
-
readonly attributes?: {
|
|
181
|
-
readonly [x: string]: string;
|
|
182
|
-
} | undefined;
|
|
183
|
-
readonly trace?: {
|
|
184
|
-
readonly traceparent: string;
|
|
185
|
-
readonly tracestate?: string | undefined;
|
|
186
|
-
} | undefined;
|
|
187
|
-
};
|
|
188
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
189
|
-
readonly type: "runtime.signal.received";
|
|
190
|
-
readonly payload: {
|
|
191
|
-
readonly signalType: string;
|
|
192
|
-
};
|
|
193
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
194
|
-
readonly type: "runtime.snapshot.taken";
|
|
195
|
-
readonly payload: {
|
|
196
|
-
readonly seq: number;
|
|
197
|
-
readonly stateHash: string;
|
|
198
|
-
readonly state?: Schema.Json | undefined;
|
|
199
|
-
};
|
|
200
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
201
|
-
readonly type: "runtime.thread.cancel.requested";
|
|
202
|
-
readonly payload: {
|
|
203
|
-
readonly threadId: string;
|
|
204
|
-
};
|
|
205
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
206
|
-
readonly type: "runtime.thread.cancelled";
|
|
207
|
-
readonly payload: {
|
|
208
|
-
readonly threadId: string;
|
|
209
|
-
readonly reason?: string | undefined;
|
|
210
|
-
readonly resumeSeq?: number | undefined;
|
|
211
|
-
};
|
|
212
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
213
|
-
readonly type: "runtime.thread.completed";
|
|
214
|
-
readonly payload: {
|
|
215
|
-
readonly threadId: string;
|
|
216
|
-
readonly output: Schema.Json;
|
|
217
|
-
};
|
|
218
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
219
|
-
readonly type: "runtime.thread.failed";
|
|
220
|
-
readonly payload: {
|
|
221
|
-
readonly threadId: string;
|
|
222
|
-
readonly error: string;
|
|
223
|
-
};
|
|
224
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
225
|
-
readonly type: "runtime.thread.started";
|
|
226
|
-
readonly payload: {
|
|
227
|
-
readonly threadId: string;
|
|
228
|
-
readonly kind: string;
|
|
229
|
-
readonly definitionName: string;
|
|
230
|
-
readonly definitionVersion: string;
|
|
231
|
-
readonly input: Schema.Json;
|
|
232
|
-
readonly parentThreadId: string | null;
|
|
233
|
-
};
|
|
234
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
235
|
-
readonly type: "runtime.timer.fired";
|
|
236
|
-
readonly payload: {
|
|
237
|
-
readonly timerId: string;
|
|
238
|
-
readonly waitId: string;
|
|
239
|
-
};
|
|
240
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
241
|
-
readonly type: "runtime.timer.set";
|
|
242
|
-
readonly payload: {
|
|
243
|
-
readonly timerId: string;
|
|
244
|
-
readonly waitId: string;
|
|
245
|
-
readonly wakeAt: number;
|
|
246
|
-
};
|
|
247
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
248
|
-
readonly type: "runtime.wait.registered";
|
|
249
|
-
readonly payload: {
|
|
250
|
-
readonly waitId: string;
|
|
251
|
-
readonly threadId?: string | undefined;
|
|
252
|
-
readonly on: {
|
|
253
|
-
readonly type: string | readonly string[];
|
|
254
|
-
readonly match?: Schema.Json | undefined;
|
|
255
|
-
} | {
|
|
256
|
-
readonly timerAt: number;
|
|
257
|
-
};
|
|
258
|
-
readonly tag?: Schema.Json | undefined;
|
|
259
|
-
};
|
|
260
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
261
|
-
readonly type: "runtime.wait.satisfied";
|
|
262
|
-
readonly payload: {
|
|
263
|
-
readonly waitId: string;
|
|
264
|
-
readonly tag?: Schema.Json | undefined;
|
|
265
|
-
readonly event: {
|
|
266
|
-
readonly id: string;
|
|
267
|
-
readonly type: string;
|
|
268
|
-
readonly payload: Schema.Json;
|
|
269
|
-
};
|
|
270
|
-
};
|
|
271
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
272
27
|
readonly type: "agent.context.compacted";
|
|
273
28
|
readonly payload: {
|
|
274
29
|
readonly turn: number;
|
|
@@ -516,19 +271,7 @@ export declare const callLlmEffect: NoInfer<import("@swirls/looms/core").LocalEf
|
|
|
516
271
|
readonly input: number;
|
|
517
272
|
readonly output: number;
|
|
518
273
|
};
|
|
519
|
-
})
|
|
520
|
-
export declare const executeToolEffect: NoInfer<import("@swirls/looms/core").LocalEffectDefinition<{
|
|
521
|
-
readonly turn: number;
|
|
522
|
-
readonly definitionName?: string | undefined;
|
|
523
|
-
readonly definitionVersion: string;
|
|
524
|
-
readonly toolCall: {
|
|
525
|
-
readonly id: string;
|
|
526
|
-
readonly name: string;
|
|
527
|
-
readonly arguments: Schema.Json;
|
|
528
|
-
};
|
|
529
|
-
readonly input?: Schema.Json | undefined;
|
|
530
|
-
readonly depth?: number | undefined;
|
|
531
|
-
}, AgentDefinitionsTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
274
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
532
275
|
readonly type: "runtime.child.close.requested";
|
|
533
276
|
readonly payload: {
|
|
534
277
|
readonly policy: "terminate" | "wait";
|
|
@@ -774,7 +517,19 @@ export declare const executeToolEffect: NoInfer<import("@swirls/looms/core").Loc
|
|
|
774
517
|
readonly payload: Schema.Json;
|
|
775
518
|
};
|
|
776
519
|
};
|
|
777
|
-
})
|
|
520
|
+
})>>;
|
|
521
|
+
export declare const executeToolEffect: NoInfer<import("@swirls/looms/core").LocalEffectDefinition<{
|
|
522
|
+
readonly turn: number;
|
|
523
|
+
readonly definitionName?: string | undefined;
|
|
524
|
+
readonly definitionVersion: string;
|
|
525
|
+
readonly toolCall: {
|
|
526
|
+
readonly id: string;
|
|
527
|
+
readonly name: string;
|
|
528
|
+
readonly arguments: Schema.Json;
|
|
529
|
+
};
|
|
530
|
+
readonly input?: Schema.Json | undefined;
|
|
531
|
+
readonly depth?: number | undefined;
|
|
532
|
+
}, AgentDefinitionsTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
778
533
|
readonly type: "agent.context.compacted";
|
|
779
534
|
readonly payload: {
|
|
780
535
|
readonly turn: number;
|
|
@@ -1022,5 +777,251 @@ export declare const executeToolEffect: NoInfer<import("@swirls/looms/core").Loc
|
|
|
1022
777
|
readonly input: number;
|
|
1023
778
|
readonly output: number;
|
|
1024
779
|
};
|
|
780
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
781
|
+
readonly type: "runtime.child.close.requested";
|
|
782
|
+
readonly payload: {
|
|
783
|
+
readonly policy: "terminate" | "wait";
|
|
784
|
+
};
|
|
785
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
786
|
+
readonly type: "runtime.child.settled";
|
|
787
|
+
readonly payload: {
|
|
788
|
+
readonly runId: string;
|
|
789
|
+
readonly status: "cancelled" | "completed" | "failed";
|
|
790
|
+
readonly output: Schema.Json;
|
|
791
|
+
readonly error: string | null;
|
|
792
|
+
};
|
|
793
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
794
|
+
readonly type: "runtime.effect.ambiguous";
|
|
795
|
+
readonly payload: {
|
|
796
|
+
readonly effectId: string;
|
|
797
|
+
readonly attempt: number;
|
|
798
|
+
readonly error: string;
|
|
799
|
+
};
|
|
800
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
801
|
+
readonly type: "runtime.effect.attempt.started";
|
|
802
|
+
readonly payload: {
|
|
803
|
+
readonly effectId: string;
|
|
804
|
+
readonly attempt: number;
|
|
805
|
+
};
|
|
806
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
807
|
+
readonly type: "runtime.effect.cancel.requested";
|
|
808
|
+
readonly payload: {
|
|
809
|
+
readonly effectId: string;
|
|
810
|
+
readonly attempt: number;
|
|
811
|
+
readonly deadlineAt: number | null;
|
|
812
|
+
};
|
|
813
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
814
|
+
readonly type: "runtime.effect.cancelled";
|
|
815
|
+
readonly payload: {
|
|
816
|
+
readonly effectId: string;
|
|
817
|
+
readonly attempt: number;
|
|
818
|
+
};
|
|
819
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
820
|
+
readonly type: "runtime.effect.completed";
|
|
821
|
+
readonly payload: {
|
|
822
|
+
readonly effectId: string;
|
|
823
|
+
readonly attempt: number;
|
|
824
|
+
};
|
|
825
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
826
|
+
readonly type: "runtime.effect.dispatch.deferred";
|
|
827
|
+
readonly payload: {
|
|
828
|
+
readonly effectId: string;
|
|
829
|
+
readonly attempt: number;
|
|
830
|
+
readonly retryAt: number;
|
|
831
|
+
readonly error: string;
|
|
832
|
+
readonly try: number;
|
|
833
|
+
};
|
|
834
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
835
|
+
readonly type: "runtime.effect.dispatched";
|
|
836
|
+
readonly payload: {
|
|
837
|
+
readonly effectId: string;
|
|
838
|
+
readonly attempt: number;
|
|
839
|
+
readonly deadlineAt: number | null;
|
|
840
|
+
};
|
|
841
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
842
|
+
readonly type: "runtime.effect.failed";
|
|
843
|
+
readonly payload: {
|
|
844
|
+
readonly effectId: string;
|
|
845
|
+
readonly error: string;
|
|
846
|
+
readonly nonRetryable?: boolean | undefined;
|
|
847
|
+
readonly retryAfterMs?: number | undefined;
|
|
848
|
+
};
|
|
849
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
850
|
+
readonly type: "runtime.effect.heartbeat";
|
|
851
|
+
readonly payload: {
|
|
852
|
+
readonly effectId: string;
|
|
853
|
+
readonly attempt: number;
|
|
854
|
+
readonly heartbeatAt: number;
|
|
855
|
+
readonly deadlineAt: number | null;
|
|
856
|
+
readonly details?: Schema.Json | undefined;
|
|
857
|
+
};
|
|
858
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
859
|
+
readonly type: "runtime.effect.queued";
|
|
860
|
+
readonly payload: {
|
|
861
|
+
readonly effectId: string;
|
|
862
|
+
readonly attempt: number;
|
|
863
|
+
readonly deadlineAt: number | null;
|
|
864
|
+
};
|
|
865
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
866
|
+
readonly type: "runtime.effect.retry.scheduled";
|
|
867
|
+
readonly payload: {
|
|
868
|
+
readonly effectId: string;
|
|
869
|
+
readonly attempt: number;
|
|
870
|
+
readonly nextAttemptAt: number;
|
|
871
|
+
readonly error: string;
|
|
872
|
+
};
|
|
873
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
874
|
+
readonly type: "runtime.effect.timed_out";
|
|
875
|
+
readonly payload: {
|
|
876
|
+
readonly effectId: string;
|
|
877
|
+
readonly attempt: number;
|
|
878
|
+
readonly timeout: string;
|
|
879
|
+
};
|
|
880
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
881
|
+
readonly type: "runtime.effect.worker.started";
|
|
882
|
+
readonly payload: {
|
|
883
|
+
readonly effectId: string;
|
|
884
|
+
readonly attempt: number;
|
|
885
|
+
readonly deadlineAt: number | null;
|
|
886
|
+
};
|
|
887
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
888
|
+
readonly type: "runtime.fork.elided";
|
|
889
|
+
readonly payload: {
|
|
890
|
+
readonly type: string;
|
|
891
|
+
};
|
|
892
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
893
|
+
readonly type: "runtime.run.cancelled";
|
|
894
|
+
readonly payload: {
|
|
895
|
+
readonly reason?: string | undefined;
|
|
896
|
+
};
|
|
897
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
898
|
+
readonly type: "runtime.run.completed";
|
|
899
|
+
readonly payload: {
|
|
900
|
+
readonly output: Schema.Json;
|
|
901
|
+
readonly error: string | null;
|
|
902
|
+
};
|
|
903
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
904
|
+
readonly type: "runtime.run.forked";
|
|
905
|
+
readonly payload: {
|
|
906
|
+
readonly sourceRunId: string;
|
|
907
|
+
readonly sourceSeq: number;
|
|
908
|
+
};
|
|
909
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
910
|
+
readonly type: "runtime.run.launched";
|
|
911
|
+
readonly payload: {
|
|
912
|
+
readonly runId: string;
|
|
913
|
+
readonly kind: string;
|
|
914
|
+
readonly definitionName: string;
|
|
915
|
+
readonly definitionVersion: string;
|
|
916
|
+
readonly effectId: string;
|
|
917
|
+
readonly close: "terminate" | "wait";
|
|
918
|
+
};
|
|
919
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
920
|
+
readonly type: "runtime.run.started";
|
|
921
|
+
readonly payload: {
|
|
922
|
+
readonly rootThreadId?: string | undefined;
|
|
923
|
+
readonly kind: string;
|
|
924
|
+
readonly definitionName: string;
|
|
925
|
+
readonly definitionVersion: string;
|
|
926
|
+
readonly input: Schema.Json;
|
|
927
|
+
readonly requestedThreadId?: string | null | undefined;
|
|
928
|
+
readonly launchedBy?: {
|
|
929
|
+
readonly runId: string;
|
|
930
|
+
readonly threadId: string;
|
|
931
|
+
readonly effectId: string;
|
|
932
|
+
readonly causationId: string;
|
|
933
|
+
readonly causationSeq: number;
|
|
934
|
+
} | undefined;
|
|
935
|
+
readonly attributes?: {
|
|
936
|
+
readonly [x: string]: string;
|
|
937
|
+
} | undefined;
|
|
938
|
+
readonly trace?: {
|
|
939
|
+
readonly traceparent: string;
|
|
940
|
+
readonly tracestate?: string | undefined;
|
|
941
|
+
} | undefined;
|
|
942
|
+
};
|
|
943
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
944
|
+
readonly type: "runtime.signal.received";
|
|
945
|
+
readonly payload: {
|
|
946
|
+
readonly signalType: string;
|
|
947
|
+
};
|
|
948
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
949
|
+
readonly type: "runtime.snapshot.taken";
|
|
950
|
+
readonly payload: {
|
|
951
|
+
readonly seq: number;
|
|
952
|
+
readonly stateHash: string;
|
|
953
|
+
readonly state?: Schema.Json | undefined;
|
|
954
|
+
};
|
|
955
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
956
|
+
readonly type: "runtime.thread.cancel.requested";
|
|
957
|
+
readonly payload: {
|
|
958
|
+
readonly threadId: string;
|
|
959
|
+
};
|
|
960
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
961
|
+
readonly type: "runtime.thread.cancelled";
|
|
962
|
+
readonly payload: {
|
|
963
|
+
readonly threadId: string;
|
|
964
|
+
readonly reason?: string | undefined;
|
|
965
|
+
readonly resumeSeq?: number | undefined;
|
|
966
|
+
};
|
|
967
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
968
|
+
readonly type: "runtime.thread.completed";
|
|
969
|
+
readonly payload: {
|
|
970
|
+
readonly threadId: string;
|
|
971
|
+
readonly output: Schema.Json;
|
|
972
|
+
};
|
|
973
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
974
|
+
readonly type: "runtime.thread.failed";
|
|
975
|
+
readonly payload: {
|
|
976
|
+
readonly threadId: string;
|
|
977
|
+
readonly error: string;
|
|
978
|
+
};
|
|
979
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
980
|
+
readonly type: "runtime.thread.started";
|
|
981
|
+
readonly payload: {
|
|
982
|
+
readonly threadId: string;
|
|
983
|
+
readonly kind: string;
|
|
984
|
+
readonly definitionName: string;
|
|
985
|
+
readonly definitionVersion: string;
|
|
986
|
+
readonly input: Schema.Json;
|
|
987
|
+
readonly parentThreadId: string | null;
|
|
988
|
+
};
|
|
989
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
990
|
+
readonly type: "runtime.timer.fired";
|
|
991
|
+
readonly payload: {
|
|
992
|
+
readonly timerId: string;
|
|
993
|
+
readonly waitId: string;
|
|
994
|
+
};
|
|
995
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
996
|
+
readonly type: "runtime.timer.set";
|
|
997
|
+
readonly payload: {
|
|
998
|
+
readonly timerId: string;
|
|
999
|
+
readonly waitId: string;
|
|
1000
|
+
readonly wakeAt: number;
|
|
1001
|
+
};
|
|
1002
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
1003
|
+
readonly type: "runtime.wait.registered";
|
|
1004
|
+
readonly payload: {
|
|
1005
|
+
readonly waitId: string;
|
|
1006
|
+
readonly threadId?: string | undefined;
|
|
1007
|
+
readonly on: {
|
|
1008
|
+
readonly type: string | readonly string[];
|
|
1009
|
+
readonly match?: Schema.Json | undefined;
|
|
1010
|
+
} | {
|
|
1011
|
+
readonly timerAt: number;
|
|
1012
|
+
};
|
|
1013
|
+
readonly tag?: Schema.Json | undefined;
|
|
1014
|
+
};
|
|
1015
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
1016
|
+
readonly type: "runtime.wait.satisfied";
|
|
1017
|
+
readonly payload: {
|
|
1018
|
+
readonly waitId: string;
|
|
1019
|
+
readonly tag?: Schema.Json | undefined;
|
|
1020
|
+
readonly event: {
|
|
1021
|
+
readonly id: string;
|
|
1022
|
+
readonly type: string;
|
|
1023
|
+
readonly payload: Schema.Json;
|
|
1024
|
+
};
|
|
1025
|
+
};
|
|
1025
1026
|
})>>;
|
|
1026
1027
|
export declare function readToolCall(value: JsonValue): ToolCall | null;
|
package/dist/agent/effects.js
CHANGED
|
@@ -8,6 +8,8 @@ import { toolSpecs } from './tool-schema.js';
|
|
|
8
8
|
import { MessageSchema, ToolCallSchema } from './types.js';
|
|
9
9
|
const CallLlmInput = Schema.Struct({
|
|
10
10
|
turn: Schema.Finite,
|
|
11
|
+
/** Turns since the latest user message, this one included. */
|
|
12
|
+
messageTurn: Schema.optional(Schema.Finite),
|
|
11
13
|
definitionName: Schema.optional(Schema.String),
|
|
12
14
|
definitionVersion: Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed(DEFAULT_DEFINITION_VERSION))),
|
|
13
15
|
messages: Schema.optional(Schema.Array(MessageSchema)),
|
|
@@ -78,6 +80,7 @@ export const callLlmEffect = agentModule.effect({
|
|
|
78
80
|
input: CallLlmInput,
|
|
79
81
|
execute: (input, ctx) => runCallLlm({
|
|
80
82
|
turn: input.turn,
|
|
83
|
+
messageTurn: input.messageTurn ?? input.turn,
|
|
81
84
|
definitionName: input.definitionName,
|
|
82
85
|
definitionVersion: input.definitionVersion,
|
|
83
86
|
messages: [...(input.messages ?? [])],
|
|
@@ -108,7 +111,11 @@ function runCallLlm(args) {
|
|
|
108
111
|
},
|
|
109
112
|
];
|
|
110
113
|
}
|
|
111
|
-
|
|
114
|
+
// A conversation has no natural end, so its limits (`maxTurns`, and the turn `stopWhen`
|
|
115
|
+
// sees) count the turns spent answering one message. Any other agent runs one task and
|
|
116
|
+
// counts every turn against it.
|
|
117
|
+
const countedTurn = definition.conversational ? args.messageTurn : turn;
|
|
118
|
+
if (countedTurn > (definition.maxTurns ?? 20)) {
|
|
112
119
|
return [
|
|
113
120
|
{
|
|
114
121
|
type: 'runtime.thread.failed',
|
|
@@ -201,7 +208,7 @@ function runCallLlm(args) {
|
|
|
201
208
|
}));
|
|
202
209
|
const toolCalls = result.toolCalls ?? result.message.toolCalls ?? [];
|
|
203
210
|
const shouldStop = definition.stopWhen?.({
|
|
204
|
-
turn,
|
|
211
|
+
turn: countedTurn,
|
|
205
212
|
maxTurns: definition.maxTurns ?? 20,
|
|
206
213
|
messages: currentMessages,
|
|
207
214
|
toolCalls,
|
package/dist/agent/module.d.ts
CHANGED
|
@@ -221,6 +221,7 @@ export declare function agent(options?: AgentModuleOptions): import("@swirls/loo
|
|
|
221
221
|
}>, {
|
|
222
222
|
callLLM: import("@swirls/looms/core").LocalEffectDefinition<{
|
|
223
223
|
readonly turn: number;
|
|
224
|
+
readonly messageTurn?: number | undefined;
|
|
224
225
|
readonly definitionName?: string | undefined;
|
|
225
226
|
readonly definitionVersion: string;
|
|
226
227
|
readonly messages?: readonly {
|
|
@@ -1370,6 +1371,7 @@ export declare function agent(options?: AgentModuleOptions): import("@swirls/loo
|
|
|
1370
1371
|
readonly effects: {
|
|
1371
1372
|
callLLM: import("@swirls/looms/core").LocalEffectDefinition<{
|
|
1372
1373
|
readonly turn: number;
|
|
1374
|
+
readonly messageTurn?: number | undefined;
|
|
1373
1375
|
readonly definitionName?: string | undefined;
|
|
1374
1376
|
readonly definitionVersion: string;
|
|
1375
1377
|
readonly messages?: readonly {
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { AgentTurnResult } from './definitions';
|
|
2
2
|
import type { Message, ToolCall } from './types';
|
|
3
3
|
export interface StopWhenContext {
|
|
4
|
+
/**
|
|
5
|
+
* The model turn that just ran, counted the way `maxTurns` counts: from the start of the
|
|
6
|
+
* thread, or from the latest user message for a conversational agent.
|
|
7
|
+
*/
|
|
4
8
|
readonly turn: number;
|
|
5
9
|
readonly maxTurns: number;
|
|
6
10
|
readonly messages: Message[];
|
|
@@ -9,4 +13,5 @@ export interface StopWhenContext {
|
|
|
9
13
|
}
|
|
10
14
|
export type StopWhen = (ctx: StopWhenContext) => boolean;
|
|
11
15
|
export declare function hasToolCall(name: string): StopWhen;
|
|
16
|
+
/** Stop once `n` model turns have run. For a conversational agent that is `n` turns per user message. */
|
|
12
17
|
export declare function stepCountIs(n: number): StopWhen;
|
package/dist/agent/stop-when.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export function hasToolCall(name) {
|
|
2
2
|
return (ctx) => ctx.toolCalls.some((toolCall) => toolCall.name === name);
|
|
3
3
|
}
|
|
4
|
+
/** Stop once `n` model turns have run. For a conversational agent that is `n` turns per user message. */
|
|
4
5
|
export function stepCountIs(n) {
|
|
5
6
|
return (ctx) => ctx.turn >= n;
|
|
6
7
|
}
|
package/dist/agent/threads.js
CHANGED
|
@@ -120,6 +120,11 @@ export const agentThread = agentModule.thread({
|
|
|
120
120
|
needsLlmCall: false,
|
|
121
121
|
deferWake: arrivedMidCall,
|
|
122
122
|
midCallMessages: arrivedMidCall ? midCallMessages : [],
|
|
123
|
+
// This call never saw a user message that arrived while it ran, so that message's
|
|
124
|
+
// turn count starts after it.
|
|
125
|
+
turnsBeforeMessage: midCallMessages.some((line) => line.role === 'user')
|
|
126
|
+
? event.payload.turn
|
|
127
|
+
: state.turnsBeforeMessage,
|
|
123
128
|
pendingSteer: null,
|
|
124
129
|
abandonedChildThreadIds: [],
|
|
125
130
|
};
|
|
@@ -139,6 +144,7 @@ export const agentThread = agentModule.thread({
|
|
|
139
144
|
...state,
|
|
140
145
|
lines: [...state.lines, message],
|
|
141
146
|
needsLlmCall: wakeIfIdle(state),
|
|
147
|
+
turnsBeforeMessage: state.turn,
|
|
142
148
|
};
|
|
143
149
|
}
|
|
144
150
|
case 'agent.message': {
|
|
@@ -200,6 +206,7 @@ export const agentThread = agentModule.thread({
|
|
|
200
206
|
pendingSteer: message,
|
|
201
207
|
needsLlmCall: true,
|
|
202
208
|
consumedSteerMessageIds,
|
|
209
|
+
turnsBeforeMessage: state.turn,
|
|
203
210
|
};
|
|
204
211
|
}
|
|
205
212
|
// Queue for the next turn. If the agent is idle (no open tool calls), that turn
|
|
@@ -211,6 +218,7 @@ export const agentThread = agentModule.thread({
|
|
|
211
218
|
pendingSteer: message,
|
|
212
219
|
needsLlmCall: wakeIfIdle(state),
|
|
213
220
|
consumedSteerMessageIds,
|
|
221
|
+
turnsBeforeMessage: state.turn,
|
|
214
222
|
};
|
|
215
223
|
}
|
|
216
224
|
case 'agent.context.compacted': {
|
|
@@ -386,6 +394,7 @@ export const agentThread = agentModule.thread({
|
|
|
386
394
|
if (state.needsLlmCall) {
|
|
387
395
|
effects.push(invoke(callLlmEffect, {
|
|
388
396
|
turn: state.turn + 1,
|
|
397
|
+
messageTurn: state.turn + 1 - (state.turnsBeforeMessage ?? 0),
|
|
389
398
|
definitionName: state.definitionName,
|
|
390
399
|
definitionVersion: state.definitionVersion ?? DEFAULT_DEFINITION_VERSION,
|
|
391
400
|
messages: state.lines,
|
package/dist/agent/types.d.ts
CHANGED
|
@@ -111,6 +111,12 @@ export interface AgentState {
|
|
|
111
111
|
* mid-call steer is not lost when `lines` are replaced.
|
|
112
112
|
*/
|
|
113
113
|
midCallMessages?: Message[];
|
|
114
|
+
/**
|
|
115
|
+
* Value of `turn` when the latest user message arrived. A conversational agent counts
|
|
116
|
+
* `maxTurns` from here, so the limit bounds one message and not the whole conversation.
|
|
117
|
+
* Optional so snapshots taken before the count was per message still fold.
|
|
118
|
+
*/
|
|
119
|
+
turnsBeforeMessage?: number;
|
|
114
120
|
}
|
|
115
121
|
export type AgentMessageDelivery = 'steer' | 'followUp' | 'nextTurn';
|
|
116
122
|
export type AgentSessionTurnStatus = 'completed' | 'failed' | 'cancelled';
|
|
@@ -3,7 +3,7 @@ export { deleteTerminalRunStorage, ProjectorCoverageError, RunNotTerminalError,
|
|
|
3
3
|
export { durableObjectEventStore, type DurableObjectEventStore, type DurableObjectStoreOptions, } from './event-store';
|
|
4
4
|
export { durableObjectLauncher, durableObjectScheduleHost, LoomsDurableObject, type DurableObjectRunStub, type LoomsDurableObjectConfig, } from './durable-object';
|
|
5
5
|
export { r2BlobStore, type R2BucketLike, type R2ListResult, type R2ObjectBodyLike, type R2StoredObject, } from './r2-blob-store';
|
|
6
|
-
export { routeToDurableObject, type DurableObjectNamespaceLike, type DurableObjectStubLike, } from './router';
|
|
6
|
+
export { routeToDurableObject, type DurableObjectNamespaceLike, type DurableObjectStubLike, type RouteAuthorize, } from './router';
|
|
7
7
|
export { createMemoryQueue, type MemoryQueue, type MemoryQueueOptions } from './memory-queue';
|
|
8
8
|
export { processQueueMessage, queueConsumer, QueueTaskError, workerHandlers, type QueueBatchLike, type QueueConsumerOptions, type QueueTask, type QueueTaskHandler, type WorkerCallbackClient, } from './queue-consumer';
|
|
9
9
|
export { readQueueEffectMessage, type QueueEffectMessage, type QueueMessageLike, } from './queue-message';
|
|
@@ -1,15 +1,29 @@
|
|
|
1
1
|
import type { AnyRuntimeModule } from '@swirls/looms/core';
|
|
2
|
+
import { type AuthDecision, type RouteInfo } from '@swirls/looms/runtime';
|
|
2
3
|
export interface DurableObjectStubLike {
|
|
3
4
|
fetch(request: Request): Promise<Response>;
|
|
4
5
|
}
|
|
5
6
|
export interface DurableObjectNamespaceLike<T extends DurableObjectStubLike = DurableObjectStubLike> {
|
|
6
7
|
getByName(name: string): T;
|
|
7
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Decides, in the Worker, whether a request may be forwarded to a run's Durable Object. `route` is
|
|
11
|
+
* what `describeRoute` says about the request: it has no run attributes, because the Worker does
|
|
12
|
+
* not read the run.
|
|
13
|
+
*/
|
|
14
|
+
export type RouteAuthorize = (request: Request, route: RouteInfo) => AuthDecision | Promise<AuthDecision>;
|
|
8
15
|
/**
|
|
9
16
|
* Routes incoming HTTP requests to the appropriate Durable Object actor cell.
|
|
10
17
|
* Handles `/health` locally, returns 501 for global run lists and forks, and forwards
|
|
11
18
|
* all other run and event-stream requests to `namespace.getByName(runId)`.
|
|
19
|
+
*
|
|
20
|
+
* With `authorize`, every request for a Looms route is checked in the Worker first, and a denied
|
|
21
|
+
* one never reaches a Durable Object. When the decision names an actor, the forwarded request
|
|
22
|
+
* carries it in `ACTOR_HEADER`; give the Durable Object `forwardedActorAuth()` as its `authorize`
|
|
23
|
+
* to record the request's events as sent by that actor. A client can never set the header itself:
|
|
24
|
+
* it is removed from every request that comes through here.
|
|
12
25
|
*/
|
|
13
26
|
export declare function routeToDurableObject(namespace: DurableObjectNamespaceLike, req: Request, options?: {
|
|
14
27
|
readonly modules?: readonly AnyRuntimeModule[] | (() => readonly AnyRuntimeModule[]);
|
|
28
|
+
readonly authorize?: RouteAuthorize;
|
|
15
29
|
}): Promise<Response | null>;
|
|
@@ -1,14 +1,46 @@
|
|
|
1
1
|
import { crossRunResponse, definitionsResponse, resolveRunTarget, RunTargetError, } from '@swirls/looms/actor';
|
|
2
|
+
import { ACTOR_HEADER, authResponse, describeRoute, } from '@swirls/looms/runtime';
|
|
3
|
+
/** `req` with `ACTOR_HEADER` set to `actorId`, or removed when there is none. */
|
|
4
|
+
function withActor(req, actorId) {
|
|
5
|
+
if (actorId === undefined && !req.headers.has(ACTOR_HEADER)) {
|
|
6
|
+
return req;
|
|
7
|
+
}
|
|
8
|
+
const headers = new Headers(req.headers);
|
|
9
|
+
if (actorId === undefined) {
|
|
10
|
+
headers.delete(ACTOR_HEADER);
|
|
11
|
+
}
|
|
12
|
+
else {
|
|
13
|
+
headers.set(ACTOR_HEADER, actorId);
|
|
14
|
+
}
|
|
15
|
+
return new Request(req, { headers });
|
|
16
|
+
}
|
|
2
17
|
/**
|
|
3
18
|
* Routes incoming HTTP requests to the appropriate Durable Object actor cell.
|
|
4
19
|
* Handles `/health` locally, returns 501 for global run lists and forks, and forwards
|
|
5
20
|
* all other run and event-stream requests to `namespace.getByName(runId)`.
|
|
21
|
+
*
|
|
22
|
+
* With `authorize`, every request for a Looms route is checked in the Worker first, and a denied
|
|
23
|
+
* one never reaches a Durable Object. When the decision names an actor, the forwarded request
|
|
24
|
+
* carries it in `ACTOR_HEADER`; give the Durable Object `forwardedActorAuth()` as its `authorize`
|
|
25
|
+
* to record the request's events as sent by that actor. A client can never set the header itself:
|
|
26
|
+
* it is removed from every request that comes through here.
|
|
6
27
|
*/
|
|
7
28
|
export function routeToDurableObject(namespace, req, options) {
|
|
8
29
|
const url = new URL(req.url);
|
|
9
30
|
if (url.pathname === '/health') {
|
|
10
31
|
return Promise.resolve(Response.json({ ok: true }));
|
|
11
32
|
}
|
|
33
|
+
const route = options?.authorize ? describeRoute(req.method, url.pathname) : null;
|
|
34
|
+
if (options?.authorize && route) {
|
|
35
|
+
return Promise.resolve(options.authorize(req, route)).then((decision) => {
|
|
36
|
+
const denied = authResponse(decision);
|
|
37
|
+
return (denied ??
|
|
38
|
+
forward(namespace, withActor(req, decision.allowed ? decision.actorId : undefined), options));
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
return forward(namespace, withActor(req, undefined), options);
|
|
42
|
+
}
|
|
43
|
+
function forward(namespace, req, options) {
|
|
12
44
|
const definitions = definitionsResponse(req, options?.modules);
|
|
13
45
|
if (definitions) {
|
|
14
46
|
return Promise.resolve(definitions);
|
package/dist/runtime/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, Fo
|
|
|
2
2
|
export { listEffectPlacements } from './worker-effect-dispatch';
|
|
3
3
|
export { createLooms, type Looms, type CreateLoomsOptions, type StartResult } from './looms';
|
|
4
4
|
export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription';
|
|
5
|
-
export { serveHttp, createFetchHandler, isLoomsApiPath, type FetchHandlerOptions, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, runRouteInfo, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, type RunningServer, type LoomsFetchResult, } from './server';
|
|
5
|
+
export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, type FetchHandlerOptions, ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, runRouteInfo, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, type RunningServer, type LoomsFetchResult, } from './server';
|
|
6
6
|
export { filesystemBlobStore } from './filesystem-blob-store';
|
|
7
7
|
export { createEventStreamResponse, type EventStreamOptions } from './sse';
|
|
8
8
|
export { notifyObserver, type RuntimeObservation, type RuntimeObserver } from './observer';
|
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ export { createRuntime, createTimeoutScheduler, DuplicateEffectDispatchError, Fo
|
|
|
2
2
|
export { listEffectPlacements } from './worker-effect-dispatch.js';
|
|
3
3
|
export { createLooms } from './looms.js';
|
|
4
4
|
export { loadSubscriptionOpening, readSubscriptionBounds } from './subscription.js';
|
|
5
|
-
export { serveHttp, createFetchHandler, isLoomsApiPath, authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, runRouteInfo, } from './server.js';
|
|
5
|
+
export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, runRouteInfo, } from './server.js';
|
|
6
6
|
export { filesystemBlobStore } from './filesystem-blob-store.js';
|
|
7
7
|
export { createEventStreamResponse } from './sse.js';
|
|
8
8
|
export { notifyObserver } from './observer.js';
|
|
@@ -86,13 +86,6 @@ export function executeLocalEffects(options, input) {
|
|
|
86
86
|
produced.push(createEffectFailedEvent(input.runId, item, withdrawnError(failedEffectId)));
|
|
87
87
|
continue;
|
|
88
88
|
}
|
|
89
|
-
const appendLive = (eventInput) => runInContext(Effect.gen(function* () {
|
|
90
|
-
const validated = yield* validateEventInput(registry.catalogs, eventInput);
|
|
91
|
-
const liveEvent = createLiveEvent(input.runId, item, validated);
|
|
92
|
-
if (liveEvent) {
|
|
93
|
-
yield* liveAppends.push(input.runId, liveEvent);
|
|
94
|
-
}
|
|
95
|
-
}));
|
|
96
89
|
const retry = registry.effects.get(item.effect.type)?.retry;
|
|
97
90
|
const launched = [];
|
|
98
91
|
const attemptNumber = input.attempts.get(item.effectId) ?? 1;
|
|
@@ -116,6 +109,20 @@ export function executeLocalEffects(options, input) {
|
|
|
116
109
|
continue;
|
|
117
110
|
}
|
|
118
111
|
const controller = makeAbortController();
|
|
112
|
+
let attemptOpen = true;
|
|
113
|
+
// A handler can outlive its attempt: an aborted model call may still have a delta in
|
|
114
|
+
// hand. Once the attempt is over its live events are dropped. Appending one after the
|
|
115
|
+
// wake has released the run fails, and that failure poisons the run's live appender
|
|
116
|
+
// for the next wake, which then fails the first live event of an unrelated attempt.
|
|
117
|
+
const appendLive = (eventInput) => !attemptOpen || controller.signal.aborted
|
|
118
|
+
? Promise.resolve()
|
|
119
|
+
: runInContext(Effect.gen(function* () {
|
|
120
|
+
const validated = yield* validateEventInput(registry.catalogs, eventInput);
|
|
121
|
+
const liveEvent = createLiveEvent(input.runId, item, validated);
|
|
122
|
+
if (liveEvent) {
|
|
123
|
+
yield* liveAppends.push(input.runId, liveEvent);
|
|
124
|
+
}
|
|
125
|
+
}));
|
|
119
126
|
executionContext.activeEffects.set(item.effectId, {
|
|
120
127
|
controller,
|
|
121
128
|
threadId: item.threadId,
|
|
@@ -136,6 +143,7 @@ export function executeLocalEffects(options, input) {
|
|
|
136
143
|
const settled = yield* (retry?.startToCloseTimeoutMs
|
|
137
144
|
? dispatched.pipe(Effect.timeoutOption(retry.startToCloseTimeoutMs), Effect.map(Option.getOrElse(() => ({ _tag: 'timed-out' }))))
|
|
138
145
|
: dispatched).pipe(Effect.ensuring(Effect.sync(() => {
|
|
146
|
+
attemptOpen = false;
|
|
139
147
|
executionContext.activeEffects.delete(item.effectId);
|
|
140
148
|
})));
|
|
141
149
|
// A launch the target accepted happened even if the attempt was later aborted or failed.
|
package/dist/runtime/runtime.js
CHANGED
|
@@ -26,7 +26,9 @@ function interruptedThreadIds(events, rules, state) {
|
|
|
26
26
|
const cancelled = event.type === 'runtime.thread.cancel.requested' && Predicate.isString(payload.threadId)
|
|
27
27
|
? [payload.threadId]
|
|
28
28
|
: [];
|
|
29
|
-
|
|
29
|
+
// A signal without a thread id is delivered to the root thread, so the rules see it there.
|
|
30
|
+
const delivered = { ...event, threadId: event.threadId ?? state.rootThreadId };
|
|
31
|
+
return [...cancelled, ...rules.flatMap((rule) => rule(delivered))];
|
|
30
32
|
});
|
|
31
33
|
return new Set(named.flatMap((threadId) => [threadId, ...descendantThreadIds(state, threadId)]));
|
|
32
34
|
}
|
|
@@ -12,11 +12,18 @@ export interface RouteInfo {
|
|
|
12
12
|
/** Stable route name, such as `runs.signal` or `effects.retry`. */
|
|
13
13
|
readonly name: string;
|
|
14
14
|
readonly runId?: string;
|
|
15
|
+
/** The signal a `runs.signal.named` request sends, as `namespace/name`. */
|
|
16
|
+
readonly signal?: string;
|
|
15
17
|
/** Present when the run has labels. Safe for the authorizer to branch on. */
|
|
16
18
|
readonly attributes?: RunAttributes;
|
|
17
19
|
}
|
|
18
20
|
export type AuthDecision = {
|
|
19
21
|
readonly allowed: true;
|
|
22
|
+
/**
|
|
23
|
+
* Who the request acts as. Events the request sends are recorded with this as their
|
|
24
|
+
* `origin.actorId`, replacing anything the request claimed for itself.
|
|
25
|
+
*/
|
|
26
|
+
readonly actorId?: string;
|
|
20
27
|
} | {
|
|
21
28
|
readonly allowed: false;
|
|
22
29
|
readonly status: number;
|
|
@@ -24,6 +31,8 @@ export type AuthDecision = {
|
|
|
24
31
|
};
|
|
25
32
|
export type Authorize = (request: Request, route: RouteInfo) => Effect.Effect<AuthDecision>;
|
|
26
33
|
export declare const authAllowed: AuthDecision;
|
|
34
|
+
/** Allows the request and names who it acts as; see `AuthDecision`. */
|
|
35
|
+
export declare function authAllowedAs(actorId: string): AuthDecision;
|
|
27
36
|
export declare function authDenied(status: number, error: string): AuthDecision;
|
|
28
37
|
export declare function authResponse(decision: AuthDecision): Response | null;
|
|
29
38
|
/**
|
|
@@ -31,6 +40,19 @@ export declare function authResponse(decision: AuthDecision): Response | null;
|
|
|
31
40
|
* and operational endpoints are unavailable until a host opts in.
|
|
32
41
|
*/
|
|
33
42
|
export declare const defaultAuthorize: Authorize;
|
|
43
|
+
/**
|
|
44
|
+
* The header a trusted front (such as `routeToDurableObject` with an `authorize` option) uses to
|
|
45
|
+
* tell the host behind it who a request acts as.
|
|
46
|
+
*/
|
|
47
|
+
export declare const ACTOR_HEADER = "x-looms-actor-id";
|
|
48
|
+
/**
|
|
49
|
+
* For a host that only a trusted front can reach, such as a Durable Object behind a Worker that
|
|
50
|
+
* routes with `routeToDurableObject`. Applies `inner`, then records the request as acting for the
|
|
51
|
+
* actor the front named in `ACTOR_HEADER`.
|
|
52
|
+
*
|
|
53
|
+
* Do not use this on a host that clients reach directly: they could name any actor.
|
|
54
|
+
*/
|
|
55
|
+
export declare function forwardedActorAuth(inner?: Authorize): Authorize;
|
|
34
56
|
export interface BearerTokens {
|
|
35
57
|
readonly read?: string;
|
|
36
58
|
readonly write?: string;
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { Effect } from 'effect';
|
|
2
2
|
export const authAllowed = { allowed: true };
|
|
3
|
+
/** Allows the request and names who it acts as; see `AuthDecision`. */
|
|
4
|
+
export function authAllowedAs(actorId) {
|
|
5
|
+
return { allowed: true, actorId };
|
|
6
|
+
}
|
|
3
7
|
export function authDenied(status, error) {
|
|
4
8
|
return { allowed: false, status, error };
|
|
5
9
|
}
|
|
@@ -21,6 +25,24 @@ function notConfigured(access) {
|
|
|
21
25
|
export const defaultAuthorize = (_request, route) => Effect.succeed(route.access === 'worker' || route.access === 'operations'
|
|
22
26
|
? notConfigured(route.access)
|
|
23
27
|
: authAllowed);
|
|
28
|
+
/**
|
|
29
|
+
* The header a trusted front (such as `routeToDurableObject` with an `authorize` option) uses to
|
|
30
|
+
* tell the host behind it who a request acts as.
|
|
31
|
+
*/
|
|
32
|
+
export const ACTOR_HEADER = 'x-looms-actor-id';
|
|
33
|
+
/**
|
|
34
|
+
* For a host that only a trusted front can reach, such as a Durable Object behind a Worker that
|
|
35
|
+
* routes with `routeToDurableObject`. Applies `inner`, then records the request as acting for the
|
|
36
|
+
* actor the front named in `ACTOR_HEADER`.
|
|
37
|
+
*
|
|
38
|
+
* Do not use this on a host that clients reach directly: they could name any actor.
|
|
39
|
+
*/
|
|
40
|
+
export function forwardedActorAuth(inner = defaultAuthorize) {
|
|
41
|
+
return (request, route) => inner(request, route).pipe(Effect.map((decision) => {
|
|
42
|
+
const actorId = request.headers.get(ACTOR_HEADER);
|
|
43
|
+
return decision.allowed && actorId ? { ...decision, actorId } : decision;
|
|
44
|
+
}));
|
|
45
|
+
}
|
|
24
46
|
function constantTimeEquals(actual, expected) {
|
|
25
47
|
const length = Math.max(actual.length, expected.length);
|
|
26
48
|
let difference = actual.length ^ expected.length;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type EventStore } from '@swirls/looms/core';
|
|
2
2
|
import type { LoomsRuntime } from '../runtime';
|
|
3
|
-
import { type Authorize } from './auth';
|
|
3
|
+
import { type Authorize, type RouteInfo } from './auth';
|
|
4
4
|
import { type DebuggerMount } from './debugger-host';
|
|
5
5
|
export interface FetchHandlerOptions {
|
|
6
6
|
readonly runtime: LoomsRuntime;
|
|
@@ -13,6 +13,15 @@ export interface FetchHandlerOptions {
|
|
|
13
13
|
/** Debugger UI served beside the API and authorized as `{ access: 'read', name: 'debugger' }`. */
|
|
14
14
|
readonly debugger?: DebuggerMount;
|
|
15
15
|
}
|
|
16
|
+
/**
|
|
17
|
+
* Says which Looms route a request is for, without a runtime: the same access level, route name,
|
|
18
|
+
* run id and signal that `authorize` receives, but never the run's attributes. Returns null for a
|
|
19
|
+
* path Looms does not serve and for public routes.
|
|
20
|
+
*
|
|
21
|
+
* A front that forwards requests to a host, such as a Worker in front of Durable Objects, uses
|
|
22
|
+
* this to decide what to let through.
|
|
23
|
+
*/
|
|
24
|
+
export declare function describeRoute(method: string, pathname: string): RouteInfo | null;
|
|
16
25
|
/** Whether the fetch handler answers `pathname`: the HTTP API or the debugger mount. */
|
|
17
26
|
export declare function handlesPath(pathname: string, mount: DebuggerMount | undefined): boolean;
|
|
18
27
|
export declare function createFetchHandler(options: FetchHandlerOptions): (req: Request) => Promise<Response | null>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Data, Effect, Option, Predicate, Schema } from 'effect';
|
|
2
2
|
import { hasEntries, RunAttributesSchema } from '@swirls/looms/core';
|
|
3
|
-
import { authResponse, defaultAuthorize } from './auth.js';
|
|
3
|
+
import { authAllowed, authResponse, defaultAuthorize, } from './auth.js';
|
|
4
4
|
import { debuggerPath, serveDebugger } from './debugger-host.js';
|
|
5
5
|
import { acceptsEventStream, isLoomsApiPath, toErrorResponse } from './http.js';
|
|
6
6
|
import { matchRoute } from './route-table.js';
|
|
@@ -33,26 +33,54 @@ function readRequestAttributes(req) {
|
|
|
33
33
|
onSome: (decoded) => decoded.attributes ?? noAttributes,
|
|
34
34
|
})), Effect.catchTag('UnreadableStartBody', () => Effect.succeed(noAttributes)));
|
|
35
35
|
}
|
|
36
|
-
|
|
36
|
+
const NAMED_SIGNAL_ROUTE = 'runs.signal.named';
|
|
37
|
+
/** What a matched route is about, before the run's attributes are known. */
|
|
38
|
+
function matchedRouteInfo(matched) {
|
|
37
39
|
const { access, name } = matched.route;
|
|
38
40
|
if (access === 'public') {
|
|
39
|
-
return
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const { runId, namespace, name: signalName } = matched.params;
|
|
44
|
+
if (!Predicate.isString(runId)) {
|
|
45
|
+
return { access, name };
|
|
46
|
+
}
|
|
47
|
+
// Only a run's named signal route has these two parameters.
|
|
48
|
+
return name === NAMED_SIGNAL_ROUTE &&
|
|
49
|
+
Predicate.isString(namespace) &&
|
|
50
|
+
Predicate.isString(signalName)
|
|
51
|
+
? { access, name, runId, signal: `${namespace}/${signalName}` }
|
|
52
|
+
: { access, name, runId };
|
|
53
|
+
}
|
|
54
|
+
let routeShapes;
|
|
55
|
+
/**
|
|
56
|
+
* Says which Looms route a request is for, without a runtime: the same access level, route name,
|
|
57
|
+
* run id and signal that `authorize` receives, but never the run's attributes. Returns null for a
|
|
58
|
+
* path Looms does not serve and for public routes.
|
|
59
|
+
*
|
|
60
|
+
* A front that forwards requests to a host, such as a Worker in front of Durable Objects, uses
|
|
61
|
+
* this to decide what to let through.
|
|
62
|
+
*/
|
|
63
|
+
export function describeRoute(method, pathname) {
|
|
64
|
+
// SAFETY: route handlers are the only code that reads the options, and they are never called
|
|
65
|
+
// here; only each route's method, path, name and access are used.
|
|
66
|
+
// oxlint-disable-next-line typescript/no-unsafe-type-assertion
|
|
67
|
+
routeShapes ??= createRoutes({});
|
|
68
|
+
const matched = matchRoute(routeShapes, method, pathname);
|
|
69
|
+
return matched ? matchedRouteInfo(matched) : null;
|
|
70
|
+
}
|
|
71
|
+
function authorizeRoute(req, matched, authorize, runtime, store) {
|
|
72
|
+
const info = matchedRouteInfo(matched);
|
|
73
|
+
if (!info) {
|
|
74
|
+
return Effect.succeed(authAllowed);
|
|
40
75
|
}
|
|
41
|
-
const runId =
|
|
76
|
+
const { name, runId } = info;
|
|
42
77
|
return Effect.gen(function* () {
|
|
43
78
|
const stored = Predicate.isString(runId)
|
|
44
79
|
? yield* readStoredAttributes(runtime, store, runId)
|
|
45
80
|
: noAttributes;
|
|
46
81
|
const requested = START_ROUTES.has(name) ? yield* readRequestAttributes(req) : noAttributes;
|
|
47
82
|
const attributes = hasEntries(stored) ? stored : requested;
|
|
48
|
-
|
|
49
|
-
? hasEntries(attributes)
|
|
50
|
-
? { access, name, runId, attributes }
|
|
51
|
-
: { access, name, runId }
|
|
52
|
-
: hasEntries(attributes)
|
|
53
|
-
? { access, name, attributes }
|
|
54
|
-
: { access, name };
|
|
55
|
-
return yield* authorize(req, route).pipe(Effect.map(authResponse));
|
|
83
|
+
return yield* authorize(req, hasEntries(attributes) ? { ...info, attributes } : info);
|
|
56
84
|
});
|
|
57
85
|
}
|
|
58
86
|
/** Whether the fetch handler answers `pathname`: the HTTP API or the debugger mount. */
|
|
@@ -81,11 +109,15 @@ export function createFetchHandler(options) {
|
|
|
81
109
|
if (!matched) {
|
|
82
110
|
return new Response('Not Found', { status: 404 });
|
|
83
111
|
}
|
|
84
|
-
const
|
|
112
|
+
const decision = yield* authorizeRoute(req, matched, authorize, options.runtime, options.store);
|
|
113
|
+
const denied = authResponse(decision);
|
|
85
114
|
if (denied) {
|
|
86
115
|
return denied;
|
|
87
116
|
}
|
|
88
|
-
|
|
117
|
+
const context = { req, url, params: matched.params };
|
|
118
|
+
return yield* matched.route.handle(decision.allowed && decision.actorId
|
|
119
|
+
? { ...context, actorId: decision.actorId }
|
|
120
|
+
: context);
|
|
89
121
|
}));
|
|
90
122
|
};
|
|
91
123
|
}
|
|
@@ -19,6 +19,8 @@ export interface RouteContext<TParams> {
|
|
|
19
19
|
readonly req: Request;
|
|
20
20
|
readonly url: URL;
|
|
21
21
|
readonly params: TParams;
|
|
22
|
+
/** Who the request acts as, when `authorize` named someone. */
|
|
23
|
+
readonly actorId?: string;
|
|
22
24
|
}
|
|
23
25
|
export interface RouteDefinition<TPath extends string, TDecoders extends ParamDecoders<TPath>> {
|
|
24
26
|
readonly method: 'GET' | 'POST';
|
|
@@ -53,6 +53,15 @@ function readStartRunArgs(req) {
|
|
|
53
53
|
};
|
|
54
54
|
});
|
|
55
55
|
}
|
|
56
|
+
/**
|
|
57
|
+
* Records `events` as sent by `actorId`. Whatever origin the caller wrote on them is replaced: the
|
|
58
|
+
* host's `authorize` decides who a request acts as, not the request.
|
|
59
|
+
*/
|
|
60
|
+
function sentBy(events, actorId) {
|
|
61
|
+
return actorId === undefined
|
|
62
|
+
? events
|
|
63
|
+
: events.map((event) => ({ ...event, origin: { type: 'external', actorId } }));
|
|
64
|
+
}
|
|
56
65
|
function wantsRunStream(req, url) {
|
|
57
66
|
return url.searchParams.get('stream') === 'true' || acceptsEventStream(req);
|
|
58
67
|
}
|
|
@@ -208,14 +217,14 @@ export function runRoutes({ runtime, store }) {
|
|
|
208
217
|
path: '/runs/:runId/events',
|
|
209
218
|
name: 'runs.signal',
|
|
210
219
|
access: 'write',
|
|
211
|
-
handle: ({ req, params }) => Effect.gen(function* () {
|
|
220
|
+
handle: ({ req, params, actorId }) => Effect.gen(function* () {
|
|
212
221
|
const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(SignalBodySchema)));
|
|
213
222
|
const events = body.events ??
|
|
214
223
|
(body.type
|
|
215
224
|
? [{ type: body.type, payload: body.payload ?? null, threadId: body.threadId }]
|
|
216
225
|
: []);
|
|
217
226
|
const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
|
|
218
|
-
const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
|
|
227
|
+
const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
|
|
219
228
|
return Response.json({ runId: params.runId, state });
|
|
220
229
|
}),
|
|
221
230
|
}),
|
|
@@ -224,7 +233,7 @@ export function runRoutes({ runtime, store }) {
|
|
|
224
233
|
path: '/runs/:runId/signals/:namespace/:name',
|
|
225
234
|
name: 'runs.signal.named',
|
|
226
235
|
access: 'write',
|
|
227
|
-
handle: ({ req, params }) =>
|
|
236
|
+
handle: ({ req, params, actorId }) =>
|
|
228
237
|
// SAFETY: Effect.gen residual R is never here; decode/run errors map to Error via route handlers.
|
|
229
238
|
Effect.gen(function* () {
|
|
230
239
|
const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
|
|
@@ -234,7 +243,7 @@ export function runRoutes({ runtime, store }) {
|
|
|
234
243
|
const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(NamedSignalBodySchema)));
|
|
235
244
|
const events = yield* runSignal(definition, body.input ?? null, body.threadId);
|
|
236
245
|
const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
|
|
237
|
-
const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
|
|
246
|
+
const state = yield* provideStore(runtime.signal(params.runId, sentBy(events, actorId), { idempotencyKey }), store);
|
|
238
247
|
return Response.json({ runId: params.runId, state });
|
|
239
248
|
}),
|
|
240
249
|
}),
|
package/dist/runtime/server.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { createFetchHandler, handlesPath, type FetchHandlerOptions } from './server/fetch-handler';
|
|
1
|
+
export { createFetchHandler, describeRoute, handlesPath, type FetchHandlerOptions, } from './server/fetch-handler';
|
|
2
2
|
export { isLoomsApiPath } from './server/http';
|
|
3
3
|
export { mountDebugger, type DebuggerMount } from './server/debugger-host';
|
|
4
4
|
export { runRouteInfo } from './server/run-route';
|
|
5
|
-
export { authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, } from './server/auth';
|
|
5
|
+
export { ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, type AuthDecision, type AuthorizedAccess, type Authorize, type BearerTokens, type RouteAccess, type RouteInfo, } from './server/auth';
|
|
6
6
|
export { grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, type GrantAuthOptions, type GrantFailure, type RunGrant, } from './server/grant';
|
|
7
7
|
export interface RunningServer {
|
|
8
8
|
port: number;
|
package/dist/runtime/server.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { createFetchHandler, handlesPath } from './server/fetch-handler.js';
|
|
1
|
+
export { createFetchHandler, describeRoute, handlesPath, } from './server/fetch-handler.js';
|
|
2
2
|
export { isLoomsApiPath } from './server/http.js';
|
|
3
3
|
export { mountDebugger } from './server/debugger-host.js';
|
|
4
4
|
export { runRouteInfo } from './server/run-route.js';
|
|
5
|
-
export { authAllowed, authDenied, authResponse, bearerAuth, defaultAuthorize, } from './server/auth.js';
|
|
5
|
+
export { ACTOR_HEADER, authAllowed, authAllowedAs, authDenied, authResponse, bearerAuth, defaultAuthorize, forwardedActorAuth, } from './server/auth.js';
|
|
6
6
|
export { grantAuth, issueRunGrant, grantSubprotocol, runGrantToken, verifyRunGrant, GrantError, } from './server/grant.js';
|
|
7
7
|
export function serveHttp(fetchHandler, options) {
|
|
8
8
|
const port = options?.port ?? 8787;
|
|
@@ -386,6 +386,10 @@ export function createWakeEngine(options) {
|
|
|
386
386
|
yield* Fiber.interruptAll([...inFlight.values()].map((entry) => entry.fiber));
|
|
387
387
|
inFlight.clear();
|
|
388
388
|
}
|
|
389
|
+
// Live events are flushed in the background and only drained when an effect produces
|
|
390
|
+
// events. An attempt that was aborted produces none, so flush here: releasing the wake
|
|
391
|
+
// clears the buffer, and a delta emitted just before a stop would be lost.
|
|
392
|
+
yield* liveAppends.drain(runId);
|
|
389
393
|
const root = cursor.state.rootThreadId
|
|
390
394
|
? cursor.state.threads[cursor.state.rootThreadId]
|
|
391
395
|
: undefined;
|