@tangle-network/agent-app 0.43.46 → 0.43.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/assistant/index.d.ts +3 -2
  2. package/dist/assistant/index.js +3 -2
  3. package/dist/assistant/index.js.map +1 -1
  4. package/dist/chat-routes/index.d.ts +407 -160
  5. package/dist/chat-routes/index.js +512 -102
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-store/index.d.ts +3 -2
  8. package/dist/chat-store/index.js +19 -1
  9. package/dist/chat-store/index.js.map +1 -1
  10. package/dist/chunk-23LUHHHN.js +282 -0
  11. package/dist/chunk-23LUHHHN.js.map +1 -0
  12. package/dist/{chunk-4AUQIAYU.js → chunk-5MG74GVQ.js} +2 -281
  13. package/dist/chunk-5MG74GVQ.js.map +1 -0
  14. package/dist/chunk-BQV42AFK.js +99 -0
  15. package/dist/chunk-BQV42AFK.js.map +1 -0
  16. package/dist/{chunk-6E2XJSCT.js → chunk-JGYOYY5D.js} +65 -2
  17. package/dist/chunk-JGYOYY5D.js.map +1 -0
  18. package/dist/{chunk-7VMUOD3G.js → chunk-PHIXZC6Y.js} +1 -1
  19. package/dist/chunk-PHIXZC6Y.js.map +1 -0
  20. package/dist/{file-index-Bn6sitKb.d.ts → file-index-b26ee-_R.d.ts} +1 -1
  21. package/dist/index.d.ts +4 -2
  22. package/dist/index.js +38 -22
  23. package/dist/{parts-1_3y2JmR.d.ts → parts-IB-Kbb7z.d.ts} +146 -2
  24. package/dist/sandbox/index.d.ts +1 -1
  25. package/dist/stale-turn-lock-C8Na1cFZ.d.ts +149 -0
  26. package/dist/stream/index.d.ts +5 -192
  27. package/dist/stream/index.js +14 -12
  28. package/dist/stream-normalizer-DWvtmY6F.d.ts +48 -0
  29. package/dist/teams/index.js +9 -9
  30. package/dist/teams/invitations-api.js +7 -7
  31. package/dist/turn-buffer-C9mEgoop.d.ts +146 -0
  32. package/dist/turn-stream/index.d.ts +551 -0
  33. package/dist/turn-stream/index.js +837 -0
  34. package/dist/turn-stream/index.js.map +1 -0
  35. package/dist/web-react/index.d.ts +4 -3
  36. package/dist/web-react/index.js +24 -2
  37. package/package.json +6 -1
  38. package/dist/chunk-4AUQIAYU.js.map +0 -1
  39. package/dist/chunk-6E2XJSCT.js.map +0 -1
  40. package/dist/chunk-7VMUOD3G.js.map +0 -1
@@ -1,51 +1,9 @@
1
- import { b as ChatInteractionStatus } from '../contract-KfqJh_au.js';
1
+ import { J as JsonRecord } from '../stream-normalizer-DWvtmY6F.js';
2
+ export { M as MISSING_TOOL_TERMINAL_ERROR, a as MISSING_TOOL_TERMINAL_REASON, S as StreamEvent, b as asRecord, c as asString, d as attachmentPartKey, e as collapseRedundantTextParts, f as encodeEvent, g as finalizeAssistantParts, h as finalizePendingInteractionParts, i as getPartKey, m as mergePersistedPart, n as normalizePersistedPart, j as normalizeTime, k as normalizeToolEvent, r as resolveToolId, l as resolveToolName, t as terminalizeDanglingAssistantToolUpdates, o as terminalizeDanglingToolPart, p as terminalizeDanglingToolParts } from '../stream-normalizer-DWvtmY6F.js';
3
+ export { B as BufferedTurnEvent, a as BufferedTurnOptions, b as BufferedTurnTap, D as D1LikeForTurns, P as PumpBufferedTurnOptions, R as ReplayTurnEventsOptions, T as TURN_EVENTS_MIGRATION_SQL, c as TURN_STATUS_SCOPE_MIGRATION_SQL, d as TurnEventStore, e as TurnStatus, f as coalesceChatStreamEvents, g as coalesceDeltas, h as createBufferedTurnTap, i as createD1TurnEventStore, j as createMemoryTurnEventStore, p as pumpBufferedTurn, r as replayTurnEvents } from '../turn-buffer-C9mEgoop.js';
4
+ import '../contract-KfqJh_au.js';
2
5
  import '@tangle-network/agent-interface';
3
6
 
4
- type JsonRecord = Record<string, unknown>;
5
- interface StreamEvent {
6
- type: string;
7
- data?: JsonRecord;
8
- }
9
- declare function asRecord(value: unknown): JsonRecord | undefined;
10
- declare function asString(value: unknown): string | undefined;
11
- declare function resolveToolId(part: JsonRecord): string;
12
- declare function resolveToolName(part: JsonRecord): string;
13
- declare function normalizeTime(value: unknown): JsonRecord | undefined;
14
- declare function normalizeToolEvent(event: StreamEvent): StreamEvent;
15
- declare function normalizePersistedPart(rawPart: JsonRecord): JsonRecord | null;
16
- /** Stream/transcript part key for a promoted (path-bearing) attachment,
17
- * keyed on its storage path — re-emitting the same path folds into the same
18
- * segment instead of duplicating it. */
19
- declare function attachmentPartKey(path: string): string;
20
- declare function getPartKey(part: JsonRecord): string;
21
- declare function mergePersistedPart(existing: JsonRecord | undefined, incoming: JsonRecord, delta?: string): JsonRecord;
22
- declare const MISSING_TOOL_TERMINAL_ERROR = "Tool did not report a terminal result before the assistant turn completed.";
23
- declare const MISSING_TOOL_TERMINAL_REASON = "missing-tool-terminal";
24
- /** Closes a tool part left `running` when a stream ended abnormally: settles
25
- * it as a terminal `error` and stamps `state.metadata.terminalized` so the
26
- * synthetic settlement is distinguishable from a real tool failure. Parts
27
- * that already settled (and non-tool parts) pass through untouched. */
28
- declare function terminalizeDanglingToolPart(part: JsonRecord): JsonRecord;
29
- declare function terminalizeDanglingToolParts(parts: JsonRecord[]): JsonRecord[];
30
- /** Settles still-pending interaction parts at persist time. The broker
31
- * guarantees a resolved question either answered (run unblocked, no cancel
32
- * event) or cancelled/timed out (cancel event already updated the part), so
33
- * the success path finalizes remaining pendings as `answered` and the
34
- * failure/terminalize paths as `expired`. */
35
- declare function finalizePendingInteractionParts(parts: JsonRecord[], outcome: Extract<ChatInteractionStatus, 'answered' | 'expired'>): JsonRecord[];
36
- /** Collapses text-part artifacts of unstable upstream segment identity: the
37
- * same text arriving under two keys (id-less delta stream, then an
38
- * id-bearing snapshot) folds into two segments, and interleaved empty
39
- * segments survive as blank parts. Consecutive identical text parts merge
40
- * into one; empty text parts drop when any non-empty text part exists. */
41
- declare function collapseRedundantTextParts(parts: JsonRecord[]): JsonRecord[];
42
- declare function finalizeAssistantParts(partOrder: string[], partMap: Map<string, JsonRecord>, finalText: string): JsonRecord[];
43
- /** Finalizes, then folds each synthetic tool settlement back into `partMap`
44
- * and returns just those updates — the shape a streaming loop needs to emit
45
- * closing `message.part.updated` frames for tools the stream never settled. */
46
- declare function terminalizeDanglingAssistantToolUpdates(partOrder: string[], partMap: Map<string, JsonRecord>, finalText: string): JsonRecord[];
47
- declare function encodeEvent(encoder: TextEncoder, event: StreamEvent): Uint8Array;
48
-
49
7
  interface PersistedChatMessageForTurn {
50
8
  id: string;
51
9
  role: 'user' | 'assistant' | 'system' | 'tool';
@@ -67,149 +25,4 @@ declare function resolveChatTurn(input: {
67
25
  turnId?: string;
68
26
  }): ResolvedChatTurn;
69
27
 
70
- /**
71
- * Resumable chat turns — the router-path answer to "streams resume on
72
- * disconnect" (issue #27). A turn's loop events are teed into a store as they
73
- * stream; the turn keeps running under `ctx.waitUntil` when the client drops;
74
- * a reconnecting client replays the buffered tail by sequence number and
75
- * keeps following until the turn completes.
76
- *
77
- * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON
78
- * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON
79
- *
80
- * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation
81
- * ships here because that's what Cloudflare products have (KV is unsuitable:
82
- * eventually consistent cross-isolate). Per-token deltas would mean hundreds
83
- * of rows per turn, so consecutive text/reasoning deltas are coalesced within
84
- * a flush window before they are persisted — replay yields slightly chunkier
85
- * deltas with identical concatenation.
86
- */
87
- type TurnStatus = 'running' | 'complete' | 'error';
88
- interface BufferedTurnEvent {
89
- seq: number;
90
- /** The serialized event line (JSON string, no trailing newline). */
91
- event: string;
92
- }
93
- interface TurnEventStore {
94
- append(turnId: string, events: BufferedTurnEvent[]): Promise<void>;
95
- read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>;
96
- /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets
97
- * {@link TurnEventStore.listRunning} rediscover this turn after a client reload
98
- * loses the turnId; stores that don't track scope ignore it. */
99
- setStatus(turnId: string, status: TurnStatus, scopeId?: string): Promise<void>;
100
- getStatus(turnId: string): Promise<TurnStatus | null>;
101
- /** Running turnIds for a scope, newest first — so a reloaded client (clientRunId
102
- * lost) can find and resume the in-flight turn. Optional: a store records it
103
- * only if `setStatus` was given a `scopeId`. */
104
- listRunning?(scopeId: string): Promise<string[]>;
105
- }
106
- /** Merge consecutive text/reasoning deltas of the same type into one event.
107
- * Concatenation-preserving: replaying the coalesced stream produces the same
108
- * accumulated text as the original. */
109
- declare function coalesceDeltas(events: unknown[]): unknown[];
110
- /**
111
- * Coalesce consecutive `message.part.updated` deltas for the SAME part into one
112
- * event. agent-runtime products stream `ChatStreamEvent` NDJSON
113
- * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the
114
- * buffer with the default tool-loop coalescer, every per-token delta persists as
115
- * its own row because that coalescer never recognizes the shape. Pass this as
116
- * {@link PumpBufferedTurnOptions.coalesce} instead.
117
- *
118
- * Concatenation-preserving for BOTH consumer styles: the merged event keeps the
119
- * LATEST event's `data.part` (already the cumulative accumulation) and sets
120
- * `data.delta` to the concatenation of the merged deltas, so a client that
121
- * appends `delta` and one that reads the cumulative `part` both reconstruct the
122
- * identical final text.
123
- */
124
- declare function coalesceChatStreamEvents(events: unknown[]): unknown[];
125
- interface BufferedTurnOptions {
126
- store: TurnEventStore;
127
- turnId: string;
128
- /** Deliver one serialized line to the live client. Throwing here (client
129
- * disconnected) does NOT stop buffering — events keep persisting. */
130
- write?: (line: string) => Promise<void> | void;
131
- /** Flush buffered events to the store at most this often. Default 400ms. */
132
- flushIntervalMs?: number;
133
- /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning
134
- * deltas). agent-runtime products streaming `ChatStreamEvent` pass
135
- * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a
136
- * row. Must be concatenation-preserving. */
137
- coalesce?: (events: unknown[]) => unknown[];
138
- /** Optional scope (thread/session id) recorded with the turn status, so
139
- * {@link TurnEventStore.listRunning} can find this turn after a reload. */
140
- scopeId?: string;
141
- }
142
- /** A push-driven buffer for a turn whose producer the caller does NOT own. */
143
- interface BufferedTurnTap {
144
- /** Buffer one event: persist (coalesced, on the flush window) + best-effort
145
- * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime
146
- * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call. */
147
- onEvent(raw: unknown): Promise<void>;
148
- /** Settle the turn: final flush + set status. Call after the producer resolves
149
- * ('complete') or rejects ('error'). 'error' flushes what was produced first. */
150
- done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>;
151
- }
152
- /**
153
- * The buffering core. Sequence-numbers every event, delivers it to `write`
154
- * (best-effort — a disconnected client never stops buffering), and flushes to
155
- * the store in coalesced batches. Drives both transports:
156
- *
157
- * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.
158
- * • this tap (`onEvent`/`done`) — when the producer owns iteration and only
159
- * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`
160
- * + the finished body). Durability stays here in the shell; the engine needs
161
- * no `TurnEventStore` seam.
162
- */
163
- declare function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap;
164
- interface PumpBufferedTurnOptions extends BufferedTurnOptions {
165
- source: AsyncIterable<unknown>;
166
- }
167
- /**
168
- * Drive a turn to completion regardless of the live client, when you OWN the
169
- * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.
170
- * Returns a promise that resolves when the turn finishes — hand it to
171
- * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on
172
- * client-write failure; a source error marks the turn 'error' (after flushing
173
- * what was produced) and rethrows.
174
- */
175
- declare function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void>;
176
- interface ReplayTurnEventsOptions {
177
- store: TurnEventStore;
178
- turnId: string;
179
- /** Replay strictly after this sequence number (0 = from the beginning). */
180
- fromSeq?: number;
181
- /** Poll cadence while the turn is still running. Default 500ms. */
182
- pollMs?: number;
183
- /** Give up following a 'running' turn after this long. Default 120s. */
184
- timeoutMs?: number;
185
- }
186
- /**
187
- * Yield buffered events after `fromSeq`, then keep polling while the turn is
188
- * still 'running' until it completes, errors, or times out. Terminates with a
189
- * final `{seq: -1, event: '{"type":"turn_status",...}'}` marker so clients
190
- * know why the replay ended.
191
- */
192
- declare function replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent>;
193
- /** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */
194
- interface D1LikeForTurns {
195
- prepare(sql: string): {
196
- bind(...values: unknown[]): {
197
- run(): Promise<unknown>;
198
- all<T = Record<string, unknown>>(): Promise<{
199
- results: T[];
200
- }>;
201
- first<T = Record<string, unknown>>(): Promise<T | null>;
202
- };
203
- };
204
- }
205
- /** Schema for the D1 store — append to the product's migrations. */
206
- declare const TURN_EVENTS_MIGRATION_SQL = "\nCREATE TABLE IF NOT EXISTS turn_events (\n turnId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event TEXT NOT NULL,\n PRIMARY KEY (turnId, seq)\n);\nCREATE TABLE IF NOT EXISTS turn_status (\n turnId TEXT PRIMARY KEY,\n status TEXT NOT NULL,\n scopeId TEXT,\n updatedAt TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_turn_status_scope ON turn_status (scopeId, status);\n";
207
- /** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —
208
- * run once to add the column (the CREATE above already includes it for new
209
- * deployments). SQLite ignores a duplicate-add error if already applied. */
210
- declare const TURN_STATUS_SCOPE_MIGRATION_SQL = "ALTER TABLE turn_status ADD COLUMN scopeId TEXT;";
211
- declare function createD1TurnEventStore(db: D1LikeForTurns): TurnEventStore;
212
- /** In-memory store for tests and keyless local dev. */
213
- declare function createMemoryTurnEventStore(): TurnEventStore;
214
-
215
- export { type BufferedTurnEvent, type BufferedTurnOptions, type BufferedTurnTap, type D1LikeForTurns, type JsonRecord, MISSING_TOOL_TERMINAL_ERROR, MISSING_TOOL_TERMINAL_REASON, type PersistedChatMessageForTurn, type PumpBufferedTurnOptions, type ReplayTurnEventsOptions, type ResolvedChatTurn, type StreamEvent, TURN_EVENTS_MIGRATION_SQL, TURN_STATUS_SCOPE_MIGRATION_SQL, type TurnEventStore, type TurnStatus, asRecord, asString, attachmentPartKey, buildUserTextParts, coalesceChatStreamEvents, coalesceDeltas, collapseRedundantTextParts, createBufferedTurnTap, createD1TurnEventStore, createMemoryTurnEventStore, encodeEvent, finalizeAssistantParts, finalizePendingInteractionParts, getPartKey, mergePersistedPart, messageHasTurnId, normalizeClientTurnId, normalizePersistedPart, normalizeTime, normalizeToolEvent, pumpBufferedTurn, replayTurnEvents, resolveChatTurn, resolveToolId, resolveToolName, terminalizeDanglingAssistantToolUpdates, terminalizeDanglingToolPart, terminalizeDanglingToolParts };
28
+ export { JsonRecord, type PersistedChatMessageForTurn, type ResolvedChatTurn, buildUserTextParts, messageHasTurnId, normalizeClientTurnId, resolveChatTurn };
@@ -1,37 +1,39 @@
1
1
  import {
2
- MISSING_TOOL_TERMINAL_ERROR,
3
- MISSING_TOOL_TERMINAL_REASON,
4
2
  TURN_EVENTS_MIGRATION_SQL,
5
3
  TURN_STATUS_SCOPE_MIGRATION_SQL,
6
- asRecord,
7
- asString,
8
- attachmentPartKey,
9
4
  buildUserTextParts,
10
5
  coalesceChatStreamEvents,
11
6
  coalesceDeltas,
12
- collapseRedundantTextParts,
13
7
  createBufferedTurnTap,
14
8
  createD1TurnEventStore,
15
9
  createMemoryTurnEventStore,
10
+ messageHasTurnId,
11
+ normalizeClientTurnId,
12
+ pumpBufferedTurn,
13
+ replayTurnEvents,
14
+ resolveChatTurn
15
+ } from "../chunk-23LUHHHN.js";
16
+ import {
17
+ MISSING_TOOL_TERMINAL_ERROR,
18
+ MISSING_TOOL_TERMINAL_REASON,
19
+ asRecord,
20
+ asString,
21
+ attachmentPartKey,
22
+ collapseRedundantTextParts,
16
23
  encodeEvent,
17
24
  finalizeAssistantParts,
18
25
  finalizePendingInteractionParts,
19
26
  getPartKey,
20
27
  mergePersistedPart,
21
- messageHasTurnId,
22
- normalizeClientTurnId,
23
28
  normalizePersistedPart,
24
29
  normalizeTime,
25
30
  normalizeToolEvent,
26
- pumpBufferedTurn,
27
- replayTurnEvents,
28
- resolveChatTurn,
29
31
  resolveToolId,
30
32
  resolveToolName,
31
33
  terminalizeDanglingAssistantToolUpdates,
32
34
  terminalizeDanglingToolPart,
33
35
  terminalizeDanglingToolParts
34
- } from "../chunk-4AUQIAYU.js";
36
+ } from "../chunk-5MG74GVQ.js";
35
37
  import "../chunk-XAWFPMAR.js";
36
38
  import "../chunk-SIXYZ2FB.js";
37
39
  export {
@@ -0,0 +1,48 @@
1
+ import { b as ChatInteractionStatus } from './contract-KfqJh_au.js';
2
+
3
+ type JsonRecord = Record<string, unknown>;
4
+ interface StreamEvent {
5
+ type: string;
6
+ data?: JsonRecord;
7
+ }
8
+ declare function asRecord(value: unknown): JsonRecord | undefined;
9
+ declare function asString(value: unknown): string | undefined;
10
+ declare function resolveToolId(part: JsonRecord): string;
11
+ declare function resolveToolName(part: JsonRecord): string;
12
+ declare function normalizeTime(value: unknown): JsonRecord | undefined;
13
+ declare function normalizeToolEvent(event: StreamEvent): StreamEvent;
14
+ declare function normalizePersistedPart(rawPart: JsonRecord): JsonRecord | null;
15
+ /** Stream/transcript part key for a promoted (path-bearing) attachment,
16
+ * keyed on its storage path — re-emitting the same path folds into the same
17
+ * segment instead of duplicating it. */
18
+ declare function attachmentPartKey(path: string): string;
19
+ declare function getPartKey(part: JsonRecord): string;
20
+ declare function mergePersistedPart(existing: JsonRecord | undefined, incoming: JsonRecord, delta?: string): JsonRecord;
21
+ declare const MISSING_TOOL_TERMINAL_ERROR = "Tool did not report a terminal result before the assistant turn completed.";
22
+ declare const MISSING_TOOL_TERMINAL_REASON = "missing-tool-terminal";
23
+ /** Closes a tool part left `running` when a stream ended abnormally: settles
24
+ * it as a terminal `error` and stamps `state.metadata.terminalized` so the
25
+ * synthetic settlement is distinguishable from a real tool failure. Parts
26
+ * that already settled (and non-tool parts) pass through untouched. */
27
+ declare function terminalizeDanglingToolPart(part: JsonRecord): JsonRecord;
28
+ declare function terminalizeDanglingToolParts(parts: JsonRecord[]): JsonRecord[];
29
+ /** Settles still-pending interaction parts at persist time. The broker
30
+ * guarantees a resolved question either answered (run unblocked, no cancel
31
+ * event) or cancelled/timed out (cancel event already updated the part), so
32
+ * the success path finalizes remaining pendings as `answered` and the
33
+ * failure/terminalize paths as `expired`. */
34
+ declare function finalizePendingInteractionParts(parts: JsonRecord[], outcome: Extract<ChatInteractionStatus, 'answered' | 'expired'>): JsonRecord[];
35
+ /** Collapses text-part artifacts of unstable upstream segment identity: the
36
+ * same text arriving under two keys (id-less delta stream, then an
37
+ * id-bearing snapshot) folds into two segments, and interleaved empty
38
+ * segments survive as blank parts. Consecutive identical text parts merge
39
+ * into one; empty text parts drop when any non-empty text part exists. */
40
+ declare function collapseRedundantTextParts(parts: JsonRecord[]): JsonRecord[];
41
+ declare function finalizeAssistantParts(partOrder: string[], partMap: Map<string, JsonRecord>, finalText: string): JsonRecord[];
42
+ /** Finalizes, then folds each synthetic tool settlement back into `partMap`
43
+ * and returns just those updates — the shape a streaming loop needs to emit
44
+ * closing `message.part.updated` frames for tools the stream never settled. */
45
+ declare function terminalizeDanglingAssistantToolUpdates(partOrder: string[], partMap: Map<string, JsonRecord>, finalText: string): JsonRecord[];
46
+ declare function encodeEvent(encoder: TextEncoder, event: StreamEvent): Uint8Array;
47
+
48
+ export { type JsonRecord as J, MISSING_TOOL_TERMINAL_ERROR as M, type StreamEvent as S, MISSING_TOOL_TERMINAL_REASON as a, asRecord as b, asString as c, attachmentPartKey as d, collapseRedundantTextParts as e, encodeEvent as f, finalizeAssistantParts as g, finalizePendingInteractionParts as h, getPartKey as i, normalizeTime as j, normalizeToolEvent as k, resolveToolName as l, mergePersistedPart as m, normalizePersistedPart as n, terminalizeDanglingToolPart as o, terminalizeDanglingToolParts as p, resolveToolId as r, terminalizeDanglingAssistantToolUpdates as t };
@@ -1,3 +1,12 @@
1
+ import {
2
+ INVITATION_EXPIRY_DAYS,
3
+ generateInvitationToken,
4
+ getInvitationExpiresAt,
5
+ inviteUrlForToken,
6
+ normalizeInvitationEmail,
7
+ parseInvitationPermission,
8
+ renderInvitationEmail
9
+ } from "../chunk-WEBBJBDH.js";
1
10
  import {
2
11
  generateInviteToken,
3
12
  isInviteTokenShape,
@@ -18,15 +27,6 @@ import {
18
27
  workspaceRoleToCollaborationAccess,
19
28
  workspaceRoleToSandboxRole
20
29
  } from "../chunk-63CE7FEZ.js";
21
- import {
22
- INVITATION_EXPIRY_DAYS,
23
- generateInvitationToken,
24
- getInvitationExpiresAt,
25
- inviteUrlForToken,
26
- normalizeInvitationEmail,
27
- parseInvitationPermission,
28
- renderInvitationEmail
29
- } from "../chunk-WEBBJBDH.js";
30
30
  export {
31
31
  ASSIGNABLE_WORKSPACE_ROLES,
32
32
  INVITATION_EXPIRY_DAYS,
@@ -1,10 +1,3 @@
1
- import {
2
- SeatLimitError
3
- } from "../chunk-SWUVTGMR.js";
4
- import "../chunk-3SVAA3MA.js";
5
- import {
6
- hasWorkspaceRole
7
- } from "../chunk-63CE7FEZ.js";
8
1
  import {
9
2
  generateInvitationToken,
10
3
  getInvitationExpiresAt,
@@ -12,6 +5,13 @@ import {
12
5
  normalizeInvitationEmail,
13
6
  parseInvitationPermission
14
7
  } from "../chunk-WEBBJBDH.js";
8
+ import {
9
+ SeatLimitError
10
+ } from "../chunk-SWUVTGMR.js";
11
+ import "../chunk-3SVAA3MA.js";
12
+ import {
13
+ hasWorkspaceRole
14
+ } from "../chunk-63CE7FEZ.js";
15
15
 
16
16
  // src/teams/invitations-api.ts
17
17
  import { and, eq, lte, sql } from "drizzle-orm";
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Resumable chat turns — the router-path answer to "streams resume on
3
+ * disconnect" (issue #27). A turn's loop events are teed into a store as they
4
+ * stream; the turn keeps running under `ctx.waitUntil` when the client drops;
5
+ * a reconnecting client replays the buffered tail by sequence number and
6
+ * keeps following until the turn completes.
7
+ *
8
+ * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON
9
+ * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON
10
+ *
11
+ * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation
12
+ * ships here because that's what Cloudflare products have (KV is unsuitable:
13
+ * eventually consistent cross-isolate). Per-token deltas would mean hundreds
14
+ * of rows per turn, so consecutive text/reasoning deltas are coalesced within
15
+ * a flush window before they are persisted — replay yields slightly chunkier
16
+ * deltas with identical concatenation.
17
+ */
18
+ type TurnStatus = 'running' | 'complete' | 'error';
19
+ interface BufferedTurnEvent {
20
+ seq: number;
21
+ /** The serialized event line (JSON string, no trailing newline). */
22
+ event: string;
23
+ }
24
+ interface TurnEventStore {
25
+ append(turnId: string, events: BufferedTurnEvent[]): Promise<void>;
26
+ read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>;
27
+ /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets
28
+ * {@link TurnEventStore.listRunning} rediscover this turn after a client reload
29
+ * loses the turnId; stores that don't track scope ignore it. */
30
+ setStatus(turnId: string, status: TurnStatus, scopeId?: string): Promise<void>;
31
+ getStatus(turnId: string): Promise<TurnStatus | null>;
32
+ /** Running turnIds for a scope, newest first — so a reloaded client (clientRunId
33
+ * lost) can find and resume the in-flight turn. Optional: a store records it
34
+ * only if `setStatus` was given a `scopeId`. */
35
+ listRunning?(scopeId: string): Promise<string[]>;
36
+ }
37
+ /** Merge consecutive text/reasoning deltas of the same type into one event.
38
+ * Concatenation-preserving: replaying the coalesced stream produces the same
39
+ * accumulated text as the original. */
40
+ declare function coalesceDeltas(events: unknown[]): unknown[];
41
+ /**
42
+ * Coalesce consecutive `message.part.updated` deltas for the SAME part into one
43
+ * event. agent-runtime products stream `ChatStreamEvent` NDJSON
44
+ * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the
45
+ * buffer with the default tool-loop coalescer, every per-token delta persists as
46
+ * its own row because that coalescer never recognizes the shape. Pass this as
47
+ * {@link PumpBufferedTurnOptions.coalesce} instead.
48
+ *
49
+ * Concatenation-preserving for BOTH consumer styles: the merged event keeps the
50
+ * LATEST event's `data.part` (already the cumulative accumulation) and sets
51
+ * `data.delta` to the concatenation of the merged deltas, so a client that
52
+ * appends `delta` and one that reads the cumulative `part` both reconstruct the
53
+ * identical final text.
54
+ */
55
+ declare function coalesceChatStreamEvents(events: unknown[]): unknown[];
56
+ interface BufferedTurnOptions {
57
+ store: TurnEventStore;
58
+ turnId: string;
59
+ /** Deliver one serialized line to the live client. Throwing here (client
60
+ * disconnected) does NOT stop buffering — events keep persisting. */
61
+ write?: (line: string) => Promise<void> | void;
62
+ /** Flush buffered events to the store at most this often. Default 400ms. */
63
+ flushIntervalMs?: number;
64
+ /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning
65
+ * deltas). agent-runtime products streaming `ChatStreamEvent` pass
66
+ * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a
67
+ * row. Must be concatenation-preserving. */
68
+ coalesce?: (events: unknown[]) => unknown[];
69
+ /** Optional scope (thread/session id) recorded with the turn status, so
70
+ * {@link TurnEventStore.listRunning} can find this turn after a reload. */
71
+ scopeId?: string;
72
+ }
73
+ /** A push-driven buffer for a turn whose producer the caller does NOT own. */
74
+ interface BufferedTurnTap {
75
+ /** Buffer one event: persist (coalesced, on the flush window) + best-effort
76
+ * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime
77
+ * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call. */
78
+ onEvent(raw: unknown): Promise<void>;
79
+ /** Settle the turn: final flush + set status. Call after the producer resolves
80
+ * ('complete') or rejects ('error'). 'error' flushes what was produced first. */
81
+ done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>;
82
+ }
83
+ /**
84
+ * The buffering core. Sequence-numbers every event, delivers it to `write`
85
+ * (best-effort — a disconnected client never stops buffering), and flushes to
86
+ * the store in coalesced batches. Drives both transports:
87
+ *
88
+ * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.
89
+ * • this tap (`onEvent`/`done`) — when the producer owns iteration and only
90
+ * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`
91
+ * + the finished body). Durability stays here in the shell; the engine needs
92
+ * no `TurnEventStore` seam.
93
+ */
94
+ declare function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap;
95
+ interface PumpBufferedTurnOptions extends BufferedTurnOptions {
96
+ source: AsyncIterable<unknown>;
97
+ }
98
+ /**
99
+ * Drive a turn to completion regardless of the live client, when you OWN the
100
+ * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.
101
+ * Returns a promise that resolves when the turn finishes — hand it to
102
+ * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on
103
+ * client-write failure; a source error marks the turn 'error' (after flushing
104
+ * what was produced) and rethrows.
105
+ */
106
+ declare function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void>;
107
+ interface ReplayTurnEventsOptions {
108
+ store: TurnEventStore;
109
+ turnId: string;
110
+ /** Replay strictly after this sequence number (0 = from the beginning). */
111
+ fromSeq?: number;
112
+ /** Poll cadence while the turn is still running. Default 500ms. */
113
+ pollMs?: number;
114
+ /** Give up following a 'running' turn after this long. Default 120s. */
115
+ timeoutMs?: number;
116
+ }
117
+ /**
118
+ * Yield buffered events after `fromSeq`, then keep polling while the turn is
119
+ * still 'running' until it completes, errors, or times out. Terminates with a
120
+ * final `{seq: -1, event: '{"type":"turn_status",...}'}` marker so clients
121
+ * know why the replay ended.
122
+ */
123
+ declare function replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent>;
124
+ /** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */
125
+ interface D1LikeForTurns {
126
+ prepare(sql: string): {
127
+ bind(...values: unknown[]): {
128
+ run(): Promise<unknown>;
129
+ all<T = Record<string, unknown>>(): Promise<{
130
+ results: T[];
131
+ }>;
132
+ first<T = Record<string, unknown>>(): Promise<T | null>;
133
+ };
134
+ };
135
+ }
136
+ /** Schema for the D1 store — append to the product's migrations. */
137
+ declare const TURN_EVENTS_MIGRATION_SQL = "\nCREATE TABLE IF NOT EXISTS turn_events (\n turnId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event TEXT NOT NULL,\n PRIMARY KEY (turnId, seq)\n);\nCREATE TABLE IF NOT EXISTS turn_status (\n turnId TEXT PRIMARY KEY,\n status TEXT NOT NULL,\n scopeId TEXT,\n updatedAt TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_turn_status_scope ON turn_status (scopeId, status);\n";
138
+ /** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —
139
+ * run once to add the column (the CREATE above already includes it for new
140
+ * deployments). SQLite ignores a duplicate-add error if already applied. */
141
+ declare const TURN_STATUS_SCOPE_MIGRATION_SQL = "ALTER TABLE turn_status ADD COLUMN scopeId TEXT;";
142
+ declare function createD1TurnEventStore(db: D1LikeForTurns): TurnEventStore;
143
+ /** In-memory store for tests and keyless local dev. */
144
+ declare function createMemoryTurnEventStore(): TurnEventStore;
145
+
146
+ export { type BufferedTurnEvent as B, type D1LikeForTurns as D, type PumpBufferedTurnOptions as P, type ReplayTurnEventsOptions as R, TURN_EVENTS_MIGRATION_SQL as T, type BufferedTurnOptions as a, type BufferedTurnTap as b, TURN_STATUS_SCOPE_MIGRATION_SQL as c, type TurnEventStore as d, type TurnStatus as e, coalesceChatStreamEvents as f, coalesceDeltas as g, createBufferedTurnTap as h, createD1TurnEventStore as i, createMemoryTurnEventStore as j, pumpBufferedTurn as p, replayTurnEvents as r };