@tangle-network/agent-app 0.51.16 → 0.52.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/dist/turn-stream/adapters.d.ts +41 -105
- package/dist/turn-stream/core.d.ts +31 -172
- package/dist/turn-stream/do.d.ts +41 -48
- package/dist/turn-stream/index.d.ts +9 -59
- package/dist/turn-stream/index.js +127 -122
- package/dist/turn-stream/index.js.map +1 -1
- package/dist/turn-stream/memory.d.ts +14 -1
- package/package.json +1 -1
|
@@ -1,32 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Worker
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* Everything takes the namespace STRUCTURALLY ({@link TurnStreamNamespaceLike}
|
|
8
|
-
* — Cloudflare's `DurableObjectNamespace` satisfies it), so nothing here
|
|
9
|
-
* imports Cloudflare types and the same adapters run against the memory
|
|
10
|
-
* harness in vitest.
|
|
11
|
-
*
|
|
12
|
-
* Live fanout is deliberately NOT a side effect of the turn-event store: the
|
|
13
|
-
* store is keyed by turnId/scopeId while viewer sockets live on the
|
|
14
|
-
* `${workspaceId}:${threadId}` channel, and only the product's per-turn
|
|
15
|
-
* context knows both. Products wire the workspace signal helpers into
|
|
16
|
-
* `createChatTurnRoutes`' `onEvent`.
|
|
17
|
-
*
|
|
18
|
-
* Which adapters are still the right answer (see `./core`'s header for the
|
|
19
|
-
* production measurement behind this split):
|
|
20
|
-
*
|
|
21
|
-
* | adapter | status |
|
|
22
|
-
* | ------------------------------------ | --------------------------------- |
|
|
23
|
-
* | {@link createDurableTurnLock} | KEPT — no SDK equivalent |
|
|
24
|
-
* | {@link reconcileStaleDurableTurnLock}| KEPT — no SDK equivalent |
|
|
25
|
-
* | {@link createDurableObjectTurnEventStore} | KEPT — the DETACHED lane |
|
|
26
|
-
* | {@link broadcastWorkspaceActivity} | KEPT — workspace signal |
|
|
27
|
-
* | {@link broadcastThreadCreated} | KEPT — workspace signal |
|
|
28
|
-
* | {@link createTurnStreamUpgradeHandler} | KEPT for the workspace channel |
|
|
29
|
-
* | {@link broadcastTurnStreamEvent} | `@deprecated` for sandbox turns |
|
|
2
|
+
* Worker adapters for durable turn storage, single-flight locks, and workspace signals.
|
|
3
|
+
* Namespace interfaces remain structural so Cloudflare bindings and the memory harness
|
|
4
|
+
* run the same authenticated request path.
|
|
5
|
+
* Products provide workspace authorization and their binding's TURN_STREAM_AUTH_SECRET.
|
|
30
6
|
*/
|
|
31
7
|
import { type ReconcileStaleTurnLockOptions } from '../chat-routes/stale-turn-lock';
|
|
32
8
|
import type { TurnEventStore } from '../stream/turn-buffer';
|
|
@@ -40,24 +16,20 @@ export interface TurnStreamNamespaceLike {
|
|
|
40
16
|
idFromName(name: string): unknown;
|
|
41
17
|
get(id: unknown): TurnStreamStubLike;
|
|
42
18
|
}
|
|
19
|
+
/** The HMAC secret shared between this worker and its `TurnStreamDO` binding.
|
|
20
|
+
* Every adapter call mints a channel-bound capability token from it; the DO
|
|
21
|
+
* refuses requests without one (issue #746). Products pass the same value
|
|
22
|
+
* the DO resolves — `env.TURN_STREAM_AUTH_SECRET`. */
|
|
23
|
+
export interface TurnStreamAuth {
|
|
24
|
+
secret: string;
|
|
25
|
+
}
|
|
43
26
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* instance; `listRunning` reconnect discovery rides a per-scope index
|
|
49
|
-
* instance. Drops in wherever `createD1TurnEventStore(env.DB)` would.
|
|
50
|
-
*
|
|
51
|
-
* KEPT and load-bearing for AUTONOMOUS work. A detached run driven through
|
|
52
|
-
* `dispatchPrompt({ detach: true })` or `streamPrompt` executes on the sandbox
|
|
53
|
-
* run/stream lane, which publishes nothing to the session event bus on the
|
|
54
|
-
* measured path (0 of 71 / 0 of 527 / 0 of 408 across three session-id
|
|
55
|
-
* strategies). Sandbox 0.37 `driveTurn` uses the session message lane and is
|
|
56
|
-
* gateway-visible by SDK contract. A browser tailing a stream/dispatch run
|
|
57
|
-
* needs these durable rows plus `runDetachedTurn` (`/chat-routes`). Nothing
|
|
58
|
-
* here is deprecated.
|
|
27
|
+
* Optional Durable Object backend for {@link TurnEventStore}.
|
|
28
|
+
* Each turn has its own named instance; a per-scope index tracks running turns.
|
|
29
|
+
* Products choose this adapter or the D1 backend independently of their lock
|
|
30
|
+
* and workspace-signal transport.
|
|
59
31
|
*/
|
|
60
|
-
export declare function createDurableObjectTurnEventStore(namespace: TurnStreamNamespaceLike): TurnEventStore;
|
|
32
|
+
export declare function createDurableObjectTurnEventStore(namespace: TurnStreamNamespaceLike, auth: TurnStreamAuth): TurnEventStore;
|
|
61
33
|
/** Define input parameters required to acquire a durable turn lock in a workspace thread context */
|
|
62
34
|
export interface AcquireDurableTurnLockInput {
|
|
63
35
|
workspaceId: string;
|
|
@@ -69,9 +41,9 @@ export interface AcquireDurableTurnLockInput {
|
|
|
69
41
|
lockId?: string;
|
|
70
42
|
}
|
|
71
43
|
/** Acquire a durable turn lock in the specified namespace with given input parameters */
|
|
72
|
-
export declare function acquireDurableTurnLock(namespace: TurnStreamNamespaceLike, input: AcquireDurableTurnLockInput): Promise<TurnLockAcquireResult>;
|
|
44
|
+
export declare function acquireDurableTurnLock(namespace: TurnStreamNamespaceLike, input: AcquireDurableTurnLockInput, auth: TurnStreamAuth): Promise<TurnLockAcquireResult>;
|
|
73
45
|
/** Release a durable turn lock and indicate if the release was successful or deferred */
|
|
74
|
-
export declare function releaseDurableTurnLock(namespace: TurnStreamNamespaceLike, input: TurnLockReleaseInput): Promise<{
|
|
46
|
+
export declare function releaseDurableTurnLock(namespace: TurnStreamNamespaceLike, input: TurnLockReleaseInput, auth: TurnStreamAuth): Promise<{
|
|
75
47
|
released: boolean;
|
|
76
48
|
deferred?: boolean;
|
|
77
49
|
}>;
|
|
@@ -88,10 +60,11 @@ export interface ReleaseInterruptedDurableTurnLockInput {
|
|
|
88
60
|
/** Fenced out-of-band release — the DO refuses a successor lock (started
|
|
89
61
|
* after `interruptedAt`) and a turnId mismatch. Returns whether any scope
|
|
90
62
|
* released. */
|
|
91
|
-
export declare function releaseInterruptedDurableTurnLock(namespace: TurnStreamNamespaceLike, input: ReleaseInterruptedDurableTurnLockInput): Promise<boolean>;
|
|
63
|
+
export declare function releaseInterruptedDurableTurnLock(namespace: TurnStreamNamespaceLike, input: ReleaseInterruptedDurableTurnLockInput, auth: TurnStreamAuth): Promise<boolean>;
|
|
92
64
|
/** Define options to reconcile stale durable turn locks with context, namespace, workspace, and active lock details */
|
|
93
65
|
export interface ReconcileStaleDurableTurnLockOptions extends Pick<ReconcileStaleTurnLockOptions, 'probeSandbox' | 'probeSession' | 'graceMs' | 'terminalGraceMs' | 'context' | 'log' | 'now'> {
|
|
94
66
|
namespace: TurnStreamNamespaceLike;
|
|
67
|
+
auth: TurnStreamAuth;
|
|
95
68
|
workspaceId: string;
|
|
96
69
|
threadId: string;
|
|
97
70
|
/** The lock the acquire attempt was refused on. */
|
|
@@ -133,6 +106,9 @@ export type TurnLockSeamResult = {
|
|
|
133
106
|
/** Define options for creating a durable turn lock with customizable scope and identification methods */
|
|
134
107
|
export interface CreateDurableTurnLockOptions<TContext> {
|
|
135
108
|
namespace: TurnStreamNamespaceLike;
|
|
109
|
+
/** Capability tokens for the DO; pass the worker's
|
|
110
|
+
* `env.TURN_STREAM_AUTH_SECRET`. The DO validates every request. */
|
|
111
|
+
auth: TurnStreamAuth;
|
|
136
112
|
/** Which lane serializes this turn: `'workspace'` (shared sandbox — one
|
|
137
113
|
* turn per workspace) or `'thread'` (router lane — one turn per thread). */
|
|
138
114
|
scopeOf(args: TurnLockSeamArgs<TContext>): TurnLockScope;
|
|
@@ -167,56 +143,15 @@ export declare function createDurableTurnLock<TContext>(options: CreateDurableTu
|
|
|
167
143
|
acquire(args: TurnLockSeamArgs<TContext>): Promise<TurnLockSeamResult>;
|
|
168
144
|
release(handle: unknown): Promise<void>;
|
|
169
145
|
};
|
|
170
|
-
/**
|
|
171
|
-
* DEPRECATED for sandbox-backed interactive turns (drive on the session-message
|
|
172
|
-
* lane + `SessionGatewayClient` instead) — fan a turn event out to the
|
|
173
|
-
* per-thread channel. `executionId` groups events
|
|
174
|
-
* into a per-turn segment with a monotonic seq, so a reconnecting client
|
|
175
|
-
* replays only the active turn and resumes from a cursor. Callers MUST await
|
|
176
|
-
* (the DO assigns seq on arrival — emission order matters); failures are
|
|
177
|
-
* swallowed (fanout is best-effort and never breaks chat delivery).
|
|
178
|
-
*
|
|
179
|
-
* @deprecated For a SANDBOX-backed interactive turn this re-broadcasts events
|
|
180
|
-
* the sandbox platform already fans out, at the cost of a worker hop. Drive
|
|
181
|
-
* the turn on the session-MESSAGE lane instead —
|
|
182
|
-
* `box.createSession({ sessionId, backend })` then
|
|
183
|
-
* `box.session(id).sendMessage({ parts: [{ type: 'text', text }] })` — and let
|
|
184
|
-
* the tab attach with `box.mintScopedToken({ scope: 'session', sessionId,
|
|
185
|
-
* runtimeSessionId })` + `SessionGatewayClient`
|
|
186
|
-
* (`@tangle-network/sandbox/session-gateway`). Measured on production
|
|
187
|
-
* (4 arms, SDK 0.12.0): turns driven with `box.streamPrompt()` delivered
|
|
188
|
-
* 0 of 71 / 0 of 527 / 0 of 408 turn events to a gateway client, because
|
|
189
|
-
* `POST /agents/run/stream` publishes nothing to the session event bus;
|
|
190
|
-
* the message lane delivered 297 of 297.
|
|
191
|
-
*
|
|
192
|
-
* Two things this deprecation does NOT cover, both still supported:
|
|
193
|
-
* stream/dispatch DETACHED runs (keep `runDetachedTurn` over the durable
|
|
194
|
-
* turn-event rows) and the per-workspace signals
|
|
195
|
-
* ({@link broadcastWorkspaceActivity} / {@link broadcastThreadCreated}).
|
|
196
|
-
* A SANDBOX-FREE copilot that wants a second viewer should use `/stream`'s
|
|
197
|
-
* `replayTurnEvents` (`GET /chat/stream/:turnId`), which follows a running
|
|
198
|
-
* turn from a cursor without a second broadcast fabric.
|
|
199
|
-
*
|
|
200
|
-
* Kept for back-compat; removal is a major-version change.
|
|
201
|
-
*/
|
|
202
|
-
export declare function broadcastTurnStreamEvent(namespace: TurnStreamNamespaceLike, input: {
|
|
203
|
-
workspaceId: string;
|
|
204
|
-
threadId: string;
|
|
205
|
-
executionId: string;
|
|
206
|
-
event: {
|
|
207
|
-
type: string;
|
|
208
|
-
data?: Record<string, unknown>;
|
|
209
|
-
};
|
|
210
|
-
}): Promise<void>;
|
|
211
146
|
/** Coarse per-workspace marker that a thread's turn started / ended — drives
|
|
212
147
|
* a sidebar "agent responding" indicator subscribed once per workspace. */
|
|
213
|
-
export declare function broadcastWorkspaceActivity(namespace: TurnStreamNamespaceLike, workspaceId: string, threadId: string, phase: 'start' | 'end'): Promise<void>;
|
|
148
|
+
export declare function broadcastWorkspaceActivity(namespace: TurnStreamNamespaceLike, workspaceId: string, threadId: string, phase: 'start' | 'end', auth: TurnStreamAuth): Promise<void>;
|
|
214
149
|
/** Per-workspace marker that a new thread was created, so an already-open
|
|
215
150
|
* history list prepends it without a reload. */
|
|
216
151
|
export declare function broadcastThreadCreated(namespace: TurnStreamNamespaceLike, workspaceId: string, thread: {
|
|
217
152
|
threadId: string;
|
|
218
153
|
title: string;
|
|
219
|
-
}): Promise<void>;
|
|
154
|
+
}, auth: TurnStreamAuth): Promise<void>;
|
|
220
155
|
/** Represent success or failure of a TURN stream upgrade authorization with optional response data */
|
|
221
156
|
export type TurnStreamUpgradeAuthorization = {
|
|
222
157
|
ok: true;
|
|
@@ -227,31 +162,32 @@ export type TurnStreamUpgradeAuthorization = {
|
|
|
227
162
|
/** Define options for creating a TURN stream upgrade handler including namespace, path, and authorization logic */
|
|
228
163
|
export interface CreateTurnStreamUpgradeHandlerOptions {
|
|
229
164
|
namespace: TurnStreamNamespaceLike;
|
|
165
|
+
/** HMAC secret shared with the DO binding (`env.TURN_STREAM_AUTH_SECRET`).
|
|
166
|
+
* After the product `authorize` passes, the handler mints a channel-bound
|
|
167
|
+
* capability token and the DO verifies it — the browser never holds it. */
|
|
168
|
+
authSecret: string;
|
|
230
169
|
/** The worker route serving the stream. Default `/api/session-stream`. */
|
|
231
170
|
path?: string;
|
|
232
171
|
/** Viewer access check (session cookie → workspace membership). */
|
|
233
172
|
authorize(request: Request, target: {
|
|
234
173
|
workspaceId: string;
|
|
235
|
-
threadId: string | null;
|
|
236
174
|
}): Promise<TurnStreamUpgradeAuthorization>;
|
|
237
175
|
}
|
|
238
176
|
/**
|
|
239
|
-
* The worker-entry WebSocket forwarder
|
|
240
|
-
*
|
|
241
|
-
*
|
|
177
|
+
* The worker-entry WebSocket forwarder — WORKSPACE channel only (the
|
|
178
|
+
* per-thread variant went with the deprecated rebroadcast lane; a thread's
|
|
179
|
+
* live turn replay is the sandbox session gateway's job). Call BEFORE the
|
|
180
|
+
* app router (a router loader cannot return a 101); returns `null` for
|
|
181
|
+
* requests that are not a WebSocket upgrade on the configured path.
|
|
242
182
|
*
|
|
243
|
-
* GET {path}?workspaceId=...
|
|
244
|
-
* GET {path}?workspaceId=...&threadId=… → thread channel (turn resume)
|
|
183
|
+
* GET {path}?workspaceId=... → workspace channel (sidebar signals)
|
|
245
184
|
*
|
|
246
|
-
* After the 101, the client sends `{type:'sync'
|
|
247
|
-
*
|
|
185
|
+
* After the 101, the client sends `{type:'sync'}` and receives the
|
|
186
|
+
* current-activity + recent-threads snapshot, then live signals.
|
|
248
187
|
*
|
|
249
|
-
*
|
|
250
|
-
*
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
* attach to the session gateway directly instead of to this socket. See
|
|
254
|
-
* {@link broadcastTurnStreamEvent} for the measurement and the replacement
|
|
255
|
-
* wiring.
|
|
188
|
+
* Security: the product's `authorize` decides whether THIS caller may see the
|
|
189
|
+
* workspace's signals; the channel-bound token this handler then mints is
|
|
190
|
+
* what the DO itself verifies — two independent gates, and the browser never
|
|
191
|
+
* learns the token (it rides the forwarded upgrade request only).
|
|
256
192
|
*/
|
|
257
193
|
export declare function createTurnStreamUpgradeHandler(options: CreateTurnStreamUpgradeHandlerOptions): (request: Request) => Promise<Response | null>;
|
|
@@ -1,193 +1,56 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
* turn replay
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* (gtm-agent `SessionStreamDO` + `session-broadcast.ts`): the per-turn
|
|
7
|
-
* segment store that backs reconnect replay over a live socket, the
|
|
8
|
-
* single-flight chat-turn lock record and its release fences, and the wire
|
|
9
|
-
* contract (channel keys, endpoint paths, request/response bodies) shared by
|
|
10
|
-
* the DO transport shell (`./do`) and the worker-side adapters
|
|
11
|
-
* (`./adapters`). Everything here is plain data + functions — no
|
|
12
|
-
* `cloudflare:workers`, no storage, no sockets — so the semantics are
|
|
13
|
-
* unit-testable in Node and the DO stays a thin shell.
|
|
14
|
-
*
|
|
15
|
-
* ── The two-lane rule (measured, not assumed) ────────────────────────────
|
|
16
|
-
*
|
|
17
|
-
* A 4-arm A/B on production (sandbox.tangle.tools, SDK 0.12.0, one box, one
|
|
18
|
-
* gateway client per arm) established which sandbox lane a browser can see:
|
|
19
|
-
*
|
|
20
|
-
* | turn driver | raw turn events | seen at gateway |
|
|
21
|
-
* | ------------------------------------ | --------------- | --------------- |
|
|
22
|
-
* | `box.streamPrompt()` (run/stream) | 71 / 527 / 408 | 0 / 0 / 0 |
|
|
23
|
-
* | `box.session(id).sendMessage()` | 297 | 297 |
|
|
24
|
-
* | `box.driveTurn()` (Sandbox 0.37+) | — | SDK contract |
|
|
25
|
-
*
|
|
26
|
-
* `POST /agents/run/stream` publishes nothing to the sidecar session event
|
|
27
|
-
* bus, so a `SessionGatewayClient` attached to that session receives zero
|
|
28
|
-
* turn events — three different session-id strategies all got 0, the id was
|
|
29
|
-
* not the variable. `POST /agents/sessions/{id}/messages` publishes to the
|
|
30
|
-
* bus and the gateway delivered every frame, byte-matching the sidecar tail.
|
|
31
|
-
* Sandbox 0.37 admits `driveTurn` through the session message lane, so the
|
|
32
|
-
* gateway can observe it. That is an SDK contract, not a new production count.
|
|
33
|
-
*
|
|
34
|
-
* Consequences for this module, and they cut both ways:
|
|
35
|
-
*
|
|
36
|
-
* 1. INTERACTIVE sandbox turns should be driven on the message lane and
|
|
37
|
-
* tailed by the browser through `box.mintScopedToken({ scope: 'session' })`
|
|
38
|
-
* + `SessionGatewayClient`. Re-broadcasting those same events through the
|
|
39
|
-
* per-turn SEGMENT buffer below duplicates the SDK and adds a worker hop.
|
|
40
|
-
* That half is `@deprecated` (see the tags on {@link createSegmentStore},
|
|
41
|
-
* {@link appendSegmentEvent}, {@link replayActiveSegment} and
|
|
42
|
-
* `broadcastTurnStreamEvent` in `./adapters`).
|
|
43
|
-
* 2. Detached turns driven through `dispatchPrompt({ detach: true })` or
|
|
44
|
-
* `streamPrompt` remain on the run/stream lane and need a buffer when a
|
|
45
|
-
* browser must tail them. Sandbox 0.37 `driveTurn` is different: it uses
|
|
46
|
-
* the session message lane and the gateway can observe it. The buffer
|
|
47
|
-
* remains the path for stream/dispatch runs and has no SDK replacement.
|
|
48
|
-
* 3. The LOCK and the per-workspace SIGNALS have no gateway equivalent at
|
|
49
|
-
* all (the gateway is per-session and read-only). They stay canonical.
|
|
50
|
-
*
|
|
51
|
-
* Server-side resume of a run/stream turn is also already solved by the SDK
|
|
52
|
-
* and needs nothing here: `box.streamPrompt('', { executionId, lastEventId })`
|
|
53
|
-
* replays strictly after the cursor without re-dispatching — measured across
|
|
54
|
-
* a SIGKILL mid-run and a fresh process resuming from the cursor alone:
|
|
55
|
-
* 0 lost, 0 duplicated, 0 out-of-order, ids 1..517 contiguous.
|
|
2
|
+
* Channel tokens, lock records, workspace signals, and durable event keys.
|
|
3
|
+
* Interactive turn replay belongs to the sandbox session gateway.
|
|
4
|
+
* An optional turn-event backend stores durable rows and a running-turn index.
|
|
5
|
+
* This core uses WebCrypto and plain data without a Cloudflare runtime import.
|
|
56
6
|
*/
|
|
57
|
-
/** One event on a turn-stream channel.
|
|
58
|
-
*
|
|
7
|
+
/** One event on a turn-stream channel. Workspace-signal events
|
|
8
|
+
* (`thread.created`, `thread.activity`, product events) carry no `seq` —
|
|
9
|
+
* ordering is delivery order on the DO's single-threaded event loop. */
|
|
59
10
|
export interface TurnStreamEvent {
|
|
60
11
|
type: string;
|
|
61
12
|
data?: unknown;
|
|
62
13
|
timestamp: number;
|
|
63
|
-
seq?:
|
|
14
|
+
seq?: never;
|
|
64
15
|
}
|
|
65
|
-
/**
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
*
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
16
|
+
/** Default capability lifetime. Tokens are minted per worker request and
|
|
17
|
+
* verified immediately; a WS token gates only the upgrade handshake — an
|
|
18
|
+
* accepted socket lives until it closes. */
|
|
19
|
+
export declare const TURN_STREAM_TOKEN_TTL_MS = 60000;
|
|
20
|
+
/** Request header the adapters attach (and the DO accepts). The worker also
|
|
21
|
+
* attaches it when forwarding an authorized browser WebSocket handshake. */
|
|
22
|
+
export declare const TURN_STREAM_TOKEN_HEADER = "x-turn-stream-token";
|
|
23
|
+
/** `v1.<base64url-channel>.<exp-ms-36>.<base64url-mac>` — the expiry is inside the signed payload so
|
|
24
|
+
* it cannot be extended by editing the token. */
|
|
25
|
+
export declare function mintTurnStreamToken(channelName: string, secret: string, now?: () => number, ttlMs?: number): Promise<string>;
|
|
26
|
+
/** Verify a token for `channelName`: constant-time MAC compare with the
|
|
27
|
+
* exact channel name embedded in the signed payload, plus freshness. A
|
|
28
|
+
* token minted for any other channel — or a tampered expiry — is false. */
|
|
29
|
+
export declare function verifyTurnStreamToken(channelName: string, token: string, secret: string, now?: () => number): Promise<boolean>;
|
|
74
30
|
/** Define the scope level for acquiring a turn lock within thread or workspace contexts */
|
|
75
31
|
export type TurnLockScope = 'thread' | 'workspace';
|
|
76
|
-
/**
|
|
77
|
-
*
|
|
78
|
-
* KEPT: thread-scope LOCKS are keyed on it (see {@link turnLockChannelKey}).
|
|
79
|
-
* Only its second use — addressing a live-viewer socket for interactive
|
|
80
|
-
* sandbox-turn rebroadcast — is superseded by the session gateway. */
|
|
32
|
+
/** Channel for a thread-scoped lock. */
|
|
81
33
|
export declare function threadChannelKey(workspaceId: string, threadId: string): string;
|
|
82
|
-
/**
|
|
83
|
-
*
|
|
84
|
-
* KEPT and canonical: the per-workspace signal channel (`thread.created`,
|
|
85
|
-
* `thread.activity`) plus workspace-scope locks. The session gateway is
|
|
86
|
-
* per-SESSION and read-only, so it cannot carry either. */
|
|
34
|
+
/** Channel for workspace signals and the workspace-scoped lock. */
|
|
87
35
|
export declare function workspaceChannelKey(workspaceId: string): string;
|
|
88
36
|
/** The channel a lock lives on: workspace-scope locks serialize every thread
|
|
89
37
|
* in the workspace (one shared sandbox), thread-scope locks serialize one
|
|
90
38
|
* thread (router lane). Same keying as the reference consumer, so a product
|
|
91
39
|
* swapping its fork for this package contends on identical instances. */
|
|
92
40
|
export declare function turnLockChannelKey(workspaceId: string, threadId: string, scope: TurnLockScope): string;
|
|
93
|
-
/**
|
|
94
|
-
*
|
|
95
|
-
* KEPT and canonical: durable turn-event rows for stream/dispatch detached
|
|
96
|
-
* runs live on this instance. Those run/stream paths do not reach the
|
|
97
|
-
* session gateway, so this is how a browser tails one. */
|
|
41
|
+
/** Channel for the optional Durable Object turn-event backend. */
|
|
98
42
|
export declare function turnStorageChannelKey(turnId: string): string;
|
|
99
|
-
/**
|
|
100
|
-
*
|
|
101
|
-
* KEPT and canonical: backs `TurnEventStore.listRunning`, which is how a
|
|
102
|
-
* reloaded client rediscovers an in-flight DETACHED turn. */
|
|
43
|
+
/** Running-turn index for the optional Durable Object turn-event backend. */
|
|
103
44
|
export declare function scopeIndexChannelKey(scopeId: string): string;
|
|
104
|
-
/**
|
|
105
|
-
*
|
|
106
|
-
* @deprecated Part of the interactive turn-rebroadcast buffer — see the
|
|
107
|
-
* two-lane rule in this file's header. Removal is a major-version change. */
|
|
108
|
-
export interface TurnSegment {
|
|
109
|
-
events: TurnStreamEvent[];
|
|
110
|
-
maxSeq: number;
|
|
111
|
-
terminal: boolean;
|
|
112
|
-
}
|
|
113
|
-
/** DEPRECATED (interactive turn-rebroadcast buffer) — define a store managing segments and tracking the active execution identifier.
|
|
114
|
-
*
|
|
115
|
-
* @deprecated Part of the interactive turn-rebroadcast buffer — see the
|
|
116
|
-
* two-lane rule in this file's header. Removal is a major-version change. */
|
|
117
|
-
export interface SegmentStore {
|
|
118
|
-
segments: Map<string, TurnSegment>;
|
|
119
|
-
activeExecutionId: string | null;
|
|
120
|
-
}
|
|
121
|
-
/** DEPRECATED (interactive turn-rebroadcast buffer) — per-turn replay window. Generous enough for normal turns; a turn that
|
|
122
|
-
* exceeds it loses its earliest deltas from replay (a late resumer
|
|
123
|
-
* self-heals via the final `result` event + loader revalidation).
|
|
124
|
-
*
|
|
125
|
-
* @deprecated Sizes the interactive turn-rebroadcast buffer only. The
|
|
126
|
-
* stream/dispatch detached lanes' durable rows (`turnEvent:` storage) are
|
|
127
|
-
* uncapped and are not affected. */
|
|
128
|
-
export declare const MAX_SEGMENT_EVENTS = 2000;
|
|
129
|
-
/** Recent `thread.created` markers kept for late-connecting sidebars.
|
|
130
|
-
*
|
|
131
|
-
* KEPT: a workspace-level signal, not a turn rebroadcast. */
|
|
45
|
+
/** Recent thread-created markers kept for late-connecting sidebars. */
|
|
132
46
|
export declare const MAX_RECENT_CREATED = 50;
|
|
133
47
|
/** A responding marker older than this is treated as stale, so a dropped
|
|
134
48
|
* `end` broadcast can't leave a permanently-stuck "responding" dot. */
|
|
135
49
|
export declare const ACTIVITY_TTL_MS: number;
|
|
136
|
-
/**
|
|
137
|
-
*
|
|
138
|
-
* @deprecated Backs the interactive sandbox-turn rebroadcast, which the
|
|
139
|
-
* sandbox SDK already does better (measured: run/stream → 0 frames at the
|
|
140
|
-
* gateway, message lane → 297/297; see the two-lane rule in this file's
|
|
141
|
-
* header). Sandbox turns: drive on `box.session(id).sendMessage()` and let
|
|
142
|
-
* the browser attach with `box.mintScopedToken({ scope: 'session' })` +
|
|
143
|
-
* `SessionGatewayClient`. Sandbox-FREE turns: `/stream`'s
|
|
144
|
-
* `replayTurnEvents` (`GET /chat/stream/:turnId`) already follows a running
|
|
145
|
-
* turn from a cursor. Stream/dispatch detached turns keep the durable
|
|
146
|
-
* turn-event rows —
|
|
147
|
-
* they are a different, non-deprecated lane. Removal is a major-version
|
|
148
|
-
* change; nothing is deleted here. */
|
|
149
|
-
export declare function createSegmentStore(): SegmentStore;
|
|
150
|
-
/**
|
|
151
|
-
* DEPRECATED (interactive turn-rebroadcast buffer) — append a per-turn event to
|
|
152
|
-
* its execution's segment, assigning a monotonic
|
|
153
|
-
* `seq`. A `session.run.started` (or the first-seen event for an execution)
|
|
154
|
-
* opens a fresh segment, makes it active, and drops prior turns' buffers so a
|
|
155
|
-
* resumer only ever replays the current turn. A terminal run event marks the
|
|
156
|
-
* segment terminal. Returns the seq-stamped event to broadcast.
|
|
157
|
-
*
|
|
158
|
-
* @deprecated The interactive rebroadcast half — {@link createSegmentStore}
|
|
159
|
-
* names the replacement per lane; this file's header holds the measurement.
|
|
160
|
-
*/
|
|
161
|
-
export declare function appendSegmentEvent(store: SegmentStore, executionId: string, incoming: TurnStreamEvent, maxEvents?: number): TurnStreamEvent;
|
|
162
|
-
/**
|
|
163
|
-
* DEPRECATED (interactive turn-rebroadcast buffer; the SDK replays losslessly on
|
|
164
|
-
* both lanes) — events of the active, non-terminal turn with `seq > afterSeq`,
|
|
165
|
-
* i.e. what a
|
|
166
|
-
* (re)connecting client replays before going live. A terminal (finished) turn
|
|
167
|
-
* replays nothing: the client falls back to the loader's persisted row.
|
|
168
|
-
*
|
|
169
|
-
* @deprecated The interactive rebroadcast half — {@link createSegmentStore}
|
|
170
|
-
* names the replacement per lane. The SDK's own reconnect replay is
|
|
171
|
-
* `SessionGatewayClient` + `lastEventId` (browser) or
|
|
172
|
-
* `box.streamPrompt('', { executionId, lastEventId })` (worker); both were
|
|
173
|
-
* measured lossless.
|
|
174
|
-
*/
|
|
175
|
-
export declare function replayActiveSegment(store: SegmentStore, afterSeq: number): TurnStreamEvent[];
|
|
176
|
-
/**
|
|
177
|
-
* Remove responding entries (threadId → startedAt) older than `ttlMs`, so a
|
|
178
|
-
* dropped `end` broadcast can't leave a permanently-stuck dot. Mutates
|
|
179
|
-
* `active` and returns the removed thread ids.
|
|
180
|
-
*/
|
|
50
|
+
/** Remove responding markers older than ttlMs; return their thread IDs. */
|
|
181
51
|
export declare function pruneStaleThreads(active: Map<string, number>, now: number, ttlMs: number): string[];
|
|
182
|
-
/**
|
|
183
|
-
*
|
|
184
|
-
* never the TTL but `reconcileStaleTurnLock` (in `/chat-routes`), which
|
|
185
|
-
* probes the execution's actual state.
|
|
186
|
-
*
|
|
187
|
-
* Everything from here down is the LOCK, and it is fully KEPT. The sandbox
|
|
188
|
-
* SDK ships no single-flight primitive — the session gateway is a read-only
|
|
189
|
-
* fanout — so moving a product to the message lane changes nothing about
|
|
190
|
-
* who is allowed to start a turn. */
|
|
52
|
+
/** Fallback lifetime for an unreleased lock. Use stale-lock reconciliation to
|
|
53
|
+
* recover earlier when execution state proves that its holder stopped. */
|
|
191
54
|
export declare const TURN_LOCK_TTL_MS: number;
|
|
192
55
|
/** The stored single-flight lock. Field-compatible with the reference
|
|
193
56
|
* consumer's `ChatTurnLock` so adoption is a swap, not a migration. */
|
|
@@ -247,11 +110,7 @@ export interface TurnLockInterruptedReleaseInput {
|
|
|
247
110
|
export declare function activeTurnLock(stored: DurableTurnLock | undefined, now: number): DurableTurnLock | null;
|
|
248
111
|
/** Create a durable turn lock object with timing and scope based on input parameters */
|
|
249
112
|
export declare function createTurnLock(input: TurnLockAcquireInput, now: number, ttlMs?: number): DurableTurnLock;
|
|
250
|
-
/** A cooperative release
|
|
251
|
-
* execution and the lockId minted at acquire — so a retry of a PREVIOUS turn
|
|
252
|
-
* can never release the current one. `lockId` is optional only for the DO's
|
|
253
|
-
* internal terminal-event auto-release, which knows the execution but not
|
|
254
|
-
* the caller-held lockId. */
|
|
113
|
+
/** A cooperative release matches the execution and, when supplied, lock ID. */
|
|
255
114
|
export declare function turnLockMatchesRelease(active: DurableTurnLock, input: {
|
|
256
115
|
executionId: string;
|
|
257
116
|
lockId?: string;
|
package/dist/turn-stream/do.d.ts
CHANGED
|
@@ -1,47 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Durable Object transport for thread/workspace locks, workspace signals,
|
|
3
|
+
* detached turn-event rows, and running-turn discovery.
|
|
4
|
+
* Cloudflare's named object identity binds every request's capability token.
|
|
5
|
+
* Worker and DO code share TURN_STREAM_AUTH_SECRET; absent configuration fails closed.
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* `@deprecated` for sandbox-backed interactive turns — the sandbox session
|
|
10
|
-
* gateway already does it, browser-direct, when the turn is driven on the
|
|
11
|
-
* message lane (`./core`'s header has the production measurement).
|
|
12
|
-
* - **workspace channel** (`${workspaceId}`) — coarse sidebar signals
|
|
13
|
-
* (`thread.activity` responding set, durable across eviction;
|
|
14
|
-
* `thread.created` recent list) and the workspace-scope lock. KEPT: the
|
|
15
|
-
* gateway is per-session and read-only, so it carries neither.
|
|
16
|
-
* - **turn storage** (`turn:${turnId}`) — the durable `TurnEventStore` rows +
|
|
17
|
-
* status for one buffered turn (replay survives DO eviction — this is what
|
|
18
|
-
* graduates the vertical's `turnStore` from no-op). KEPT and load-bearing:
|
|
19
|
-
* a stream/dispatch DETACHED run does not reach the gateway on the
|
|
20
|
-
* measured path, so this is how a browser tails that autonomous work.
|
|
21
|
-
* - **scope index** (`scope:${scopeId}`) — the running-turn index backing
|
|
22
|
-
* `TurnEventStore.listRunning` reconnect discovery. KEPT.
|
|
23
|
-
*
|
|
24
|
-
* The class is a PLAIN class over a structural {@link TurnStreamDOState} —
|
|
25
|
-
* no `cloudflare:workers` import, so this package stays substrate-free and
|
|
26
|
-
* the DO is unit-testable in Node. Cloudflare's `DurableObjectState`
|
|
27
|
-
* satisfies the interface; a product binds it in wrangler by re-exporting:
|
|
28
|
-
*
|
|
29
|
-
* // worker entry
|
|
30
|
-
* export { TurnStreamDO } from '@tangle-network/agent-app/turn-stream'
|
|
31
|
-
*
|
|
32
|
-
* Fan-out enumerates `state.getWebSockets()` (never an in-memory socket map)
|
|
33
|
-
* and reads per-socket metadata from the serialized attachment, so it is
|
|
34
|
-
* correct across WebSocket hibernation.
|
|
35
|
-
*
|
|
36
|
-
* Product extension (how the reference consumer keeps its Vault machinery
|
|
37
|
-
* while deleting its fork): subclass and override
|
|
38
|
-
* {@link TurnStreamDO.handleProductRequest} (extra POST endpoints),
|
|
39
|
-
* {@link TurnStreamDO.shouldDeferLockRelease} /
|
|
40
|
-
* {@link TurnStreamDO.completeDeferredLockRelease} (park a lock release
|
|
41
|
-
* behind a product-owned post-turn task), and
|
|
42
|
-
* {@link TurnStreamDO.productSyncEvents} (extra state replayed to a
|
|
43
|
-
* late-connecting socket). Product storage keys must avoid
|
|
44
|
-
* {@link TURN_STREAM_STORAGE_KEYS}.
|
|
7
|
+
* Sockets use hibernation attachments; products may add authenticated endpoints,
|
|
8
|
+
* defer lock release during persistence, and contribute workspace sync events.
|
|
9
|
+
* Product storage keys must avoid TURN_STREAM_STORAGE_KEYS.
|
|
45
10
|
*/
|
|
46
11
|
import { type DurableTurnLock, type TurnStreamEvent } from './core';
|
|
47
12
|
/** The socket surface the DO touches. Cloudflare's hibernatable `WebSocket`
|
|
@@ -69,34 +34,62 @@ export interface TurnStreamDOState {
|
|
|
69
34
|
storage: TurnStreamStorage;
|
|
70
35
|
acceptWebSocket(ws: TurnStreamSocket): void;
|
|
71
36
|
getWebSockets(): TurnStreamSocket[];
|
|
37
|
+
/** The instance's named identity — Cloudflare's `DurableObjectState.id`
|
|
38
|
+
* satisfies this structurally (`state.id.name` for `idFromName` bindings).
|
|
39
|
+
* Capability tokens are bound to this name, so it must be present for the
|
|
40
|
+
* DO to serve any request. */
|
|
41
|
+
id?: {
|
|
42
|
+
name?: string | null;
|
|
43
|
+
};
|
|
72
44
|
}
|
|
73
45
|
/** Define options to override default TTL and event limits for TURN stream DO operations */
|
|
74
46
|
export interface TurnStreamDOOptions {
|
|
75
47
|
/** Override {@link TURN_LOCK_TTL_MS}. */
|
|
76
48
|
lockTtlMs?: number;
|
|
77
|
-
/** Override {@link MAX_SEGMENT_EVENTS}. */
|
|
78
|
-
maxSegmentEvents?: number;
|
|
79
49
|
/** Override {@link ACTIVITY_TTL_MS}. */
|
|
80
50
|
activityTtlMs?: number;
|
|
81
51
|
/** How long an unrenewed running turn remains discoverable. */
|
|
82
52
|
runningTurnLeaseMs?: number;
|
|
53
|
+
/**
|
|
54
|
+
* HMAC secret for the channel-bound capability tokens every request must
|
|
55
|
+
* carry (issue #746). When omitted, the DO reads `TURN_STREAM_AUTH_SECRET`
|
|
56
|
+
* from its `env`. Fail-closed: absent or shorter than 32 chars, every
|
|
57
|
+
* request answers 500 with the fix in the message — there is deliberately
|
|
58
|
+
* no unauthenticated mode.
|
|
59
|
+
*/
|
|
60
|
+
authSecret?: string;
|
|
83
61
|
}
|
|
84
|
-
/**
|
|
62
|
+
/** Durable turn-event storage, workspace signals, and the single-flight turn
|
|
63
|
+
* lock, on one channel-bound Durable Object. Every request — including
|
|
64
|
+
* subclass product routes — passes the capability-token gate in
|
|
65
|
+
* {@link TurnStreamDO.fetch} (issue #746). */
|
|
85
66
|
export declare class TurnStreamDO {
|
|
86
67
|
protected readonly state: TurnStreamDOState;
|
|
87
68
|
protected readonly env: unknown;
|
|
88
69
|
protected readonly options: TurnStreamDOOptions;
|
|
89
|
-
private segments;
|
|
90
70
|
private recentCreated;
|
|
91
71
|
private activeThreads;
|
|
92
72
|
constructor(state: TurnStreamDOState, env?: unknown, options?: TurnStreamDOOptions);
|
|
73
|
+
/** The token-verification secret: explicit option first, then the
|
|
74
|
+
* `TURN_STREAM_AUTH_SECRET` env binding. Protected so a product subclass
|
|
75
|
+
* with its own secret store overrides ONE method instead of copying the
|
|
76
|
+
* resolution. */
|
|
77
|
+
protected resolveAuthSecret(): string | undefined;
|
|
78
|
+
/**
|
|
79
|
+
* The single authentication gate for EVERYTHING this DO serves — base
|
|
80
|
+
* endpoints, the WebSocket upgrade, and subclass product routes (they are
|
|
81
|
+
* dispatched from {@link fetch} after this check). A request must present a
|
|
82
|
+
* capability token minted for THIS instance's channel name: cross-channel
|
|
83
|
+
* replay is impossible, an unauthenticated forward gets 401, and a missing
|
|
84
|
+
* secret fails closed with a 500 that names the fix (issue #746).
|
|
85
|
+
*/
|
|
86
|
+
private authorizeRequest;
|
|
93
87
|
fetch(request: Request): Promise<Response>;
|
|
94
88
|
/** Called for any request no base endpoint claimed (before the 404), so a
|
|
95
89
|
* subclass adds product endpoints without touching base routing. Return
|
|
96
90
|
* `null` to decline. */
|
|
97
91
|
protected handleProductRequest(_request: Request, _url: URL): Promise<Response | null>;
|
|
98
|
-
/** Consulted before any lock release (cooperative
|
|
99
|
-
* terminal-event auto-release). Return `true` while a product-owned
|
|
92
|
+
/** Consulted before any lock release (cooperative or interrupted). Return `true` while a product-owned
|
|
100
93
|
* post-turn task for `executionId` must keep the scope serialized (e.g.
|
|
101
94
|
* file persistence still reading the box) — the release is then parked as
|
|
102
95
|
* `releasePending` on the lock and completed via
|