@tangle-network/agent-app 0.43.68 → 0.43.70

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.
@@ -14,6 +14,46 @@ import { d as TurnEventStore } from '../turn-buffer-DGnAPKwa.js';
14
14
  * (`./adapters`). Everything here is plain data + functions — no
15
15
  * `cloudflare:workers`, no storage, no sockets — so the semantics are
16
16
  * unit-testable in Node and the DO stays a thin shell.
17
+ *
18
+ * ── The two-lane rule (measured, not assumed) ────────────────────────────
19
+ *
20
+ * A 4-arm A/B on production (sandbox.tangle.tools, SDK 0.12.0, one box, one
21
+ * gateway client per arm) established which sandbox lane a browser can see:
22
+ *
23
+ * | turn driver | raw turn events | seen at gateway |
24
+ * | ------------------------------------ | --------------- | --------------- |
25
+ * | `box.streamPrompt()` (run/stream) | 71 / 527 / 408 | 0 / 0 / 0 |
26
+ * | `box.session(id).sendMessage()` | 297 | 297 |
27
+ *
28
+ * `POST /agents/run/stream` publishes nothing to the sidecar session event
29
+ * bus, so a `SessionGatewayClient` attached to that session receives zero
30
+ * turn events — three different session-id strategies all got 0, the id was
31
+ * not the variable. `POST /agents/sessions/{id}/messages` publishes to the
32
+ * bus and the gateway delivered every frame, byte-matching the sidecar tail.
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/autonomous turns are INVISIBLE to the gateway:
44
+ * `dispatchPrompt({ detach: true })` and `driveTurn` both go through
45
+ * `streamPrompt` internally, i.e. the run/stream lane, which does not fan
46
+ * out. A browser that must tail an unattended run still needs a buffer —
47
+ * `runDetachedTurn` (`/chat-routes`) over the durable turn-event rows
48
+ * below. That half is NOT deprecated and has no SDK replacement today.
49
+ * 3. The LOCK and the per-workspace SIGNALS have no gateway equivalent at
50
+ * all (the gateway is per-session and read-only). They stay canonical.
51
+ *
52
+ * Server-side resume of a run/stream turn is also already solved by the SDK
53
+ * and needs nothing here: `box.streamPrompt('', { executionId, lastEventId })`
54
+ * replays strictly after the cursor without re-dispatching — measured across
55
+ * a SIGKILL mid-run and a fresh process resuming from the cursor alone:
56
+ * 0 lost, 0 duplicated, 0 out-of-order, ids 1..517 contiguous.
17
57
  */
18
58
  /** One event on a turn-stream channel. `seq` is monotonic within a turn
19
59
  * segment and assigned by {@link appendSegmentEvent} on arrival at the DO. */
@@ -24,57 +64,113 @@ interface TurnStreamEvent {
24
64
  seq?: number;
25
65
  }
26
66
  /** Terminal run markers: they close a turn segment and auto-release the
27
- * channel's chat-turn lock for the segment's execution. */
67
+ * channel's chat-turn lock for the segment's execution.
68
+ *
69
+ * KEPT (not deprecated with the segment buffer): the lock auto-release
70
+ * reads it. A product that stops broadcasting turn events to the thread
71
+ * channel loses only that auto-release — the cooperative release on settle
72
+ * (`createDurableTurnLock().release`) and `reconcileStaleDurableTurnLock`
73
+ * both still fire, which is what actually frees a wedged lane. */
28
74
  declare function isTerminalRunEvent(type: string): boolean;
29
75
  /** Define the scope level for acquiring a turn lock within thread or workspace contexts */
30
76
  type TurnLockScope = 'thread' | 'workspace';
31
- /** Generate a unique string key combining workspace and thread identifiers */
77
+ /** Generate a unique string key combining workspace and thread identifiers.
78
+ *
79
+ * KEPT: thread-scope LOCKS are keyed on it (see {@link turnLockChannelKey}).
80
+ * Only its second use — addressing a live-viewer socket for interactive
81
+ * sandbox-turn rebroadcast — is superseded by the session gateway. */
32
82
  declare function threadChannelKey(workspaceId: string, threadId: string): string;
33
- /** Generate a unique channel key based on the given workspace identifier */
83
+ /** Generate a unique channel key based on the given workspace identifier.
84
+ *
85
+ * KEPT and canonical: the per-workspace signal channel (`thread.created`,
86
+ * `thread.activity`) plus workspace-scope locks. The session gateway is
87
+ * per-SESSION and read-only, so it cannot carry either. */
34
88
  declare function workspaceChannelKey(workspaceId: string): string;
35
89
  /** The channel a lock lives on: workspace-scope locks serialize every thread
36
90
  * in the workspace (one shared sandbox), thread-scope locks serialize one
37
91
  * thread (router lane). Same keying as the reference consumer, so a product
38
92
  * swapping its fork for this package contends on identical instances. */
39
93
  declare function turnLockChannelKey(workspaceId: string, threadId: string, scope: TurnLockScope): string;
40
- /** Generate a storage channel key string for a given turn identifier */
94
+ /** Generate a storage channel key string for a given turn identifier.
95
+ *
96
+ * KEPT and canonical: the DETACHED lane's durable turn-event rows live on
97
+ * this instance. A detached run never reaches the session gateway, so this
98
+ * is the only way a browser tails one. */
41
99
  declare function turnStorageChannelKey(turnId: string): string;
42
- /** Generate a unique channel key string based on the provided scope identifier */
100
+ /** Generate a unique channel key string based on the provided scope identifier.
101
+ *
102
+ * KEPT and canonical: backs `TurnEventStore.listRunning`, which is how a
103
+ * reloaded client rediscovers an in-flight DETACHED turn. */
43
104
  declare function scopeIndexChannelKey(scopeId: string): string;
44
- /** Represent a segment of a turn containing events, sequence limit, and terminal status */
105
+ /** DEPRECATED (interactive turn-rebroadcast buffer) — represent a segment of a turn containing events, sequence limit, and terminal status.
106
+ *
107
+ * @deprecated Part of the interactive turn-rebroadcast buffer — see the
108
+ * two-lane rule in this file's header. Removal is a major-version change. */
45
109
  interface TurnSegment {
46
110
  events: TurnStreamEvent[];
47
111
  maxSeq: number;
48
112
  terminal: boolean;
49
113
  }
50
- /** Define a store managing segments and tracking the active execution identifier */
114
+ /** DEPRECATED (interactive turn-rebroadcast buffer) — define a store managing segments and tracking the active execution identifier.
115
+ *
116
+ * @deprecated Part of the interactive turn-rebroadcast buffer — see the
117
+ * two-lane rule in this file's header. Removal is a major-version change. */
51
118
  interface SegmentStore {
52
119
  segments: Map<string, TurnSegment>;
53
120
  activeExecutionId: string | null;
54
121
  }
55
- /** Per-turn replay window. Generous enough for normal turns; a turn that
122
+ /** DEPRECATED (interactive turn-rebroadcast buffer) — per-turn replay window. Generous enough for normal turns; a turn that
56
123
  * exceeds it loses its earliest deltas from replay (a late resumer
57
- * self-heals via the final `result` event + loader revalidation). */
124
+ * self-heals via the final `result` event + loader revalidation).
125
+ *
126
+ * @deprecated Sizes the interactive turn-rebroadcast buffer only. The
127
+ * DETACHED lane's durable rows (`turnEvent:` storage) are uncapped and are
128
+ * not affected. */
58
129
  declare const MAX_SEGMENT_EVENTS = 2000;
59
- /** Recent `thread.created` markers kept for late-connecting sidebars. */
130
+ /** Recent `thread.created` markers kept for late-connecting sidebars.
131
+ *
132
+ * KEPT: a workspace-level signal, not a turn rebroadcast. */
60
133
  declare const MAX_RECENT_CREATED = 50;
61
134
  /** A responding marker older than this is treated as stale, so a dropped
62
135
  * `end` broadcast can't leave a permanently-stuck "responding" dot. */
63
136
  declare const ACTIVITY_TTL_MS: number;
64
- /** Create a SegmentStore with initialized segments and no active execution ID */
137
+ /** DEPRECATED (interactive sandbox-turn rebroadcast; the SDK's session gateway replaces it) — create a SegmentStore with initialized segments and no active execution ID.
138
+ *
139
+ * @deprecated Backs the interactive sandbox-turn rebroadcast, which the
140
+ * sandbox SDK already does better (measured: run/stream → 0 frames at the
141
+ * gateway, message lane → 297/297; see the two-lane rule in this file's
142
+ * header). Sandbox turns: drive on `box.session(id).sendMessage()` and let
143
+ * the browser attach with `box.mintScopedToken({ scope: 'session' })` +
144
+ * `SessionGatewayClient`. Sandbox-FREE turns: `/stream`'s
145
+ * `replayTurnEvents` (`GET /chat/stream/:turnId`) already follows a running
146
+ * turn from a cursor. Detached turns keep the durable turn-event rows —
147
+ * they are a different, non-deprecated lane. Removal is a major-version
148
+ * change; nothing is deleted here. */
65
149
  declare function createSegmentStore(): SegmentStore;
66
150
  /**
67
- * Append a per-turn event to its execution's segment, assigning a monotonic
151
+ * DEPRECATED (interactive turn-rebroadcast buffer) — append a per-turn event to
152
+ * its execution's segment, assigning a monotonic
68
153
  * `seq`. A `session.run.started` (or the first-seen event for an execution)
69
154
  * opens a fresh segment, makes it active, and drops prior turns' buffers so a
70
155
  * resumer only ever replays the current turn. A terminal run event marks the
71
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.
72
160
  */
73
161
  declare function appendSegmentEvent(store: SegmentStore, executionId: string, incoming: TurnStreamEvent, maxEvents?: number): TurnStreamEvent;
74
162
  /**
75
- * Events of the active, non-terminal turn with `seq > afterSeq` — what a
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
76
166
  * (re)connecting client replays before going live. A terminal (finished) turn
77
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.
78
174
  */
79
175
  declare function replayActiveSegment(store: SegmentStore, afterSeq: number): TurnStreamEvent[];
80
176
  /**
@@ -86,7 +182,12 @@ declare function pruneStaleThreads(active: Map<string, number>, now: number, ttl
86
182
  /** Default lifetime of an unreleased lock. Long enough that a legitimately
87
183
  * slow sandbox turn never loses its guard mid-run; the way OUT of a wedge is
88
184
  * never the TTL but `reconcileStaleTurnLock` (in `/chat-routes`), which
89
- * probes the execution's actual state. */
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. */
90
191
  declare const TURN_LOCK_TTL_MS: number;
91
192
  /** The stored single-flight lock. Field-compatible with the reference
92
193
  * consumer's `ChatTurnLock` so adoption is a swap, not a migration. */
@@ -199,17 +300,23 @@ declare function turnEventStorageKey(seq: number): string;
199
300
  * core (`./core`). One class serves every channel family; the instance NAME
200
301
  * decides which endpoints a given instance ever sees:
201
302
  *
202
- * - **thread channel** (`${workspaceId}:${threadId}`) — the live chat turn:
203
- * WebSocket fanout, per-turn segments with `sync`/`afterSeq` reconnect
204
- * replay, and the thread-scope lock.
303
+ * - **thread channel** (`${workspaceId}:${threadId}`) — the thread-scope lock
304
+ * (KEPT), plus the live turn rebroadcast: WebSocket fanout and per-turn
305
+ * segments with `sync`/`afterSeq` reconnect replay. That rebroadcast is
306
+ * `@deprecated` for sandbox-backed interactive turns — the sandbox session
307
+ * gateway already does it, browser-direct, when the turn is driven on the
308
+ * message lane (`./core`'s header has the production measurement).
205
309
  * - **workspace channel** (`${workspaceId}`) — coarse sidebar signals
206
310
  * (`thread.activity` responding set, durable across eviction;
207
- * `thread.created` recent list) and the workspace-scope lock.
311
+ * `thread.created` recent list) and the workspace-scope lock. KEPT: the
312
+ * gateway is per-session and read-only, so it carries neither.
208
313
  * - **turn storage** (`turn:${turnId}`) — the durable `TurnEventStore` rows +
209
314
  * status for one buffered turn (replay survives DO eviction — this is what
210
- * graduates the vertical's `turnStore` from no-op).
315
+ * graduates the vertical's `turnStore` from no-op). KEPT and load-bearing:
316
+ * a DETACHED run never reaches the gateway, so this is the only way a
317
+ * browser tails autonomous work.
211
318
  * - **scope index** (`scope:${scopeId}`) — the running-turn index backing
212
- * `TurnEventStore.listRunning` reconnect discovery.
319
+ * `TurnEventStore.listRunning` reconnect discovery. KEPT.
213
320
  *
214
321
  * The class is a PLAIN class over a structural {@link TurnStreamDOState} —
215
322
  * no `cloudflare:workers` import, so this package stays substrate-free and
@@ -345,9 +452,21 @@ declare class TurnStreamDO {
345
452
  * Live fanout is deliberately NOT a side effect of the turn-event store: the
346
453
  * store is keyed by turnId/scopeId while viewer sockets live on the
347
454
  * `${workspaceId}:${threadId}` channel, and only the product's per-turn
348
- * context knows both. Products wire {@link broadcastTurnStreamEvent} (and the
349
- * workspace helpers) into `createChatTurnRoutes`' `onEvent` — the same
350
- * contract the reference consumer already runs.
455
+ * context knows both. Products wire the workspace signal helpers into
456
+ * `createChatTurnRoutes`' `onEvent`.
457
+ *
458
+ * Which adapters are still the right answer (see `./core`'s header for the
459
+ * production measurement behind this split):
460
+ *
461
+ * | adapter | status |
462
+ * | ------------------------------------ | --------------------------------- |
463
+ * | {@link createDurableTurnLock} | KEPT — no SDK equivalent |
464
+ * | {@link reconcileStaleDurableTurnLock}| KEPT — no SDK equivalent |
465
+ * | {@link createDurableObjectTurnEventStore} | KEPT — the DETACHED lane |
466
+ * | {@link broadcastWorkspaceActivity} | KEPT — workspace signal |
467
+ * | {@link broadcastThreadCreated} | KEPT — workspace signal |
468
+ * | {@link createTurnStreamUpgradeHandler} | KEPT for the workspace channel |
469
+ * | {@link broadcastTurnStreamEvent} | `@deprecated` for sandbox turns |
351
470
  */
352
471
 
353
472
  /** Resolve a stub interface for handling fetch requests with optional initialization parameters */
@@ -366,6 +485,15 @@ interface TurnStreamNamespaceLike {
366
485
  * live channel). Each buffered turn lives on its own `turn:<turnId>` DO
367
486
  * instance; `listRunning` reconnect discovery rides a per-scope index
368
487
  * instance. Drops in wherever `createD1TurnEventStore(env.DB)` would.
488
+ *
489
+ * KEPT and load-bearing for AUTONOMOUS work. A detached run
490
+ * (`dispatchPrompt({ detach: true })`, `driveTurn`) executes on the sandbox
491
+ * run/stream lane, which publishes nothing to the session event bus — a
492
+ * `SessionGatewayClient` attached to that session sees zero turn events
493
+ * (measured: 0 of 71 / 0 of 527 / 0 of 408 across three session-id
494
+ * strategies). So a browser that must tail a mission step, a queue job, or
495
+ * an inbound-email review has no SDK path; it needs these durable rows plus
496
+ * `runDetachedTurn` (`/chat-routes`). Nothing here is deprecated.
369
497
  */
370
498
  declare function createDurableObjectTurnEventStore(namespace: TurnStreamNamespaceLike): TurnEventStore;
371
499
  /** Define input parameters required to acquire a durable turn lock in a workspace thread context */
@@ -478,11 +606,36 @@ declare function createDurableTurnLock<TContext>(options: CreateDurableTurnLockO
478
606
  release(handle: unknown): Promise<void>;
479
607
  };
480
608
  /**
481
- * Fan a turn event out to the per-thread channel. `executionId` groups events
609
+ * DEPRECATED for sandbox-backed interactive turns (drive on the session-message
610
+ * lane + `SessionGatewayClient` instead) — fan a turn event out to the
611
+ * per-thread channel. `executionId` groups events
482
612
  * into a per-turn segment with a monotonic seq, so a reconnecting client
483
613
  * replays only the active turn and resumes from a cursor. Callers MUST await
484
614
  * (the DO assigns seq on arrival — emission order matters); failures are
485
615
  * swallowed (fanout is best-effort and never breaks chat delivery).
616
+ *
617
+ * @deprecated For a SANDBOX-backed interactive turn this re-broadcasts events
618
+ * the sandbox platform already fans out, at the cost of a worker hop. Drive
619
+ * the turn on the session-MESSAGE lane instead —
620
+ * `box.createSession({ sessionId, backend })` then
621
+ * `box.session(id).sendMessage({ parts: [{ type: 'text', text }] })` — and let
622
+ * the tab attach with `box.mintScopedToken({ scope: 'session', sessionId,
623
+ * runtimeSessionId })` + `SessionGatewayClient`
624
+ * (`@tangle-network/sandbox/session-gateway`). Measured on production
625
+ * (4 arms, SDK 0.12.0): turns driven with `box.streamPrompt()` delivered
626
+ * 0 of 71 / 0 of 527 / 0 of 408 turn events to a gateway client, because
627
+ * `POST /agents/run/stream` publishes nothing to the session event bus;
628
+ * the message lane delivered 297 of 297.
629
+ *
630
+ * Two things this deprecation does NOT cover, both still supported:
631
+ * DETACHED runs (no gateway fanout at all — keep `runDetachedTurn` over the
632
+ * durable turn-event rows) and the per-workspace signals
633
+ * ({@link broadcastWorkspaceActivity} / {@link broadcastThreadCreated}).
634
+ * A SANDBOX-FREE copilot that wants a second viewer should use `/stream`'s
635
+ * `replayTurnEvents` (`GET /chat/stream/:turnId`), which follows a running
636
+ * turn from a cursor without a second broadcast fabric.
637
+ *
638
+ * Kept for back-compat; removal is a major-version change.
486
639
  */
487
640
  declare function broadcastTurnStreamEvent(namespace: TurnStreamNamespaceLike, input: {
488
641
  workspaceId: string;
@@ -530,6 +683,14 @@ interface CreateTurnStreamUpgradeHandlerOptions {
530
683
  *
531
684
  * After the 101, the client sends `{type:'sync', afterSeq}` and receives the
532
685
  * replay-then-live stream (see {@link TurnStreamDO.webSocketMessage}).
686
+ *
687
+ * NOT deprecated — the workspace variant (no `threadId`) is the canonical
688
+ * transport for the per-workspace signals, which the session gateway cannot
689
+ * carry (it is per-session and read-only). The THREAD variant is the
690
+ * deprecated half: for a sandbox-backed interactive turn the tab should
691
+ * attach to the session gateway directly instead of to this socket. See
692
+ * {@link broadcastTurnStreamEvent} for the measurement and the replacement
693
+ * wiring.
533
694
  */
534
695
  declare function createTurnStreamUpgradeHandler(options: CreateTurnStreamUpgradeHandlerOptions): (request: Request) => Promise<Response | null>;
535
696