@tangle-network/agent-app 4.0.48 → 4.0.50
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/chat-routes/index.js +6 -6
- package/dist/{chunk-YLRH77J3.js → chunk-EHUSCRLY.js} +2 -2
- package/dist/{chunk-P6NVRUW6.js → chunk-OV4X4P6U.js} +2 -2
- package/dist/{chunk-Y7FTBDFZ.js → chunk-PFH3EVZN.js} +4 -4
- package/dist/{chunk-AFSDGQIV.js → chunk-TWFYDZVA.js} +2 -2
- package/dist/{chunk-FIVFWLX7.js → chunk-YR4OHHQL.js} +12 -8
- package/dist/chunk-YR4OHHQL.js.map +1 -0
- package/dist/{chunk-FIH4MI6S.js → chunk-YY3D7LYV.js} +7 -2
- package/dist/chunk-YY3D7LYV.js.map +1 -0
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.js +5 -5
- package/dist/runtime/index.js +2 -2
- package/dist/runtime/router-turn.d.ts +4 -0
- package/dist/runtime/router-turn.js +1 -1
- package/dist/sandbox/index.js +2 -2
- package/dist/stream/index.js +2 -2
- package/dist/turn-stream/index.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-FIH4MI6S.js.map +0 -1
- package/dist/chunk-FIVFWLX7.js.map +0 -1
- /package/dist/{chunk-YLRH77J3.js.map → chunk-EHUSCRLY.js.map} +0 -0
- /package/dist/{chunk-P6NVRUW6.js.map → chunk-OV4X4P6U.js.map} +0 -0
- /package/dist/{chunk-Y7FTBDFZ.js.map → chunk-PFH3EVZN.js.map} +0 -0
- /package/dist/{chunk-AFSDGQIV.js.map → chunk-TWFYDZVA.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stream/turn-buffer.ts"],"sourcesContent":["/**\n * Resumable chat turns — the router-path answer to \"streams resume on\n * disconnect\" (issue #27). A turn's loop events are teed into a store as they\n * stream; the turn keeps running under `ctx.waitUntil` when the client drops;\n * a reconnecting client replays the buffered tail by sequence number and\n * keeps following until the turn completes.\n *\n * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON\n * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON\n *\n * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation\n * ships here because that's what Cloudflare products have (KV is unsuitable:\n * eventually consistent cross-isolate). Per-token deltas would mean hundreds\n * of rows per turn, so consecutive text/reasoning deltas are coalesced within\n * a flush window before they are persisted — replay yields slightly chunkier\n * deltas with identical concatenation.\n */\n\nexport type TurnStatus = 'running' | 'complete' | 'error'\n\n/** A running row is a renewable lease, not permanent truth. If the process\n * driving a turn dies before writing a terminal status, reconnect discovery\n * must eventually stop returning that abandoned row. */\nexport const DEFAULT_RUNNING_TURN_LEASE_MS = 5 * 60_000\n\n/** Keep a healthy turn's lease comfortably ahead of expiry without turning\n * per-token streaming into status-write traffic. */\nexport const DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS = 30_000\n\n/** Represent a buffered turn event with a sequence number and serialized event data */\nexport interface BufferedTurnEvent {\n seq: number\n /** The serialized event line (JSON string, no trailing newline). */\n event: string\n}\n\n/** Manage and query turn events and their lifecycle statuses within a scoped event store */\nexport interface TurnEventStore {\n /**\n * Append rows while the turn is live. Implementations must ignore rows that\n * arrive after `setStatus` publishes `complete` or `error`; the terminal\n * status is the replay fence for a detached live projection.\n */\n append(turnId: string, events: BufferedTurnEvent[]): Promise<void>\n read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>\n /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets\n * {@link TurnEventStore.listRunning} rediscover this turn after a client reload\n * loses the turnId; stores that don't track scope ignore it. */\n setStatus(turnId: string, status: TurnStatus, scopeId?: string, options?: TurnStatusWriteOptions): Promise<void>\n getStatus(turnId: string): Promise<TurnStatus | null>\n /** Unexpired running turnIds for a scope, newest first — so a reloaded client\n * (clientRunId lost) can find and resume the in-flight turn without reviving\n * a row abandoned by a dead process. Optional: a store records it only if\n * `setStatus` was given a `scopeId`. */\n listRunning?(scopeId: string): Promise<string[]>\n /** Remove one turn's buffered events and keep its status, so a genuine\n * re-stream after a crash starts at seq 0 without interleaving orphaned\n * rows. `runDetachedTurn` requires it to recover a `running` turn. */\n resetEvents?(turnId: string): Promise<void>\n /** Explicitly remove one turn's events and status. Optional so existing\n * custom stores remain source-compatible; the built-in D1 and memory stores\n * provide it. */\n deleteTurn?(turnId: string): Promise<void>\n /** Remove terminal turns whose status was updated before `before` (Unix\n * milliseconds or a Date). Running turns are never eligible. */\n pruneTerminalTurns?(before: number | Date): Promise<number>\n /** Running turns last renewed before `before` (Unix ms), oldest first, at most\n * `limit`: the candidates {@link settleOrphanedTurns} settles. */\n listStaleRunning?(before: number, limit: number): Promise<StaleRunningTurn[]>\n /** The last `count` events of a turn, newest first; a bounded read of the tail. */\n readTail?(turnId: string, count: number): Promise<BufferedTurnEvent[]>\n}\n\n/** A running turn nothing has renewed since `updatedAt`. */\nexport interface StaleRunningTurn {\n turnId: string\n scopeId: string | null\n /** Unix ms of the last status write. */\n updatedAt: number\n /** Set on a plan follow-up claim (`createD1PlanFollowUpGate`), which keeps its own staleness and does not renew. */\n leaseToken?: string | null\n}\n\n/**\n * Settling a stream nothing produces any more. A sweep that ends an orphaned\n * stream must not move it in time, since reports place a stream by its update\n * time, and must not end one whose producer came back meanwhile.\n */\nexport interface TurnStatusWriteOptions {\n /** Keep the row's update time; a new row still takes the current time. */\n preserveUpdatedAt?: boolean\n /** Write only when the row is still `running` and was last updated before this time (Unix ms). */\n onlyIfRunningBefore?: number\n}\n\n/** Configure running-turn lease evaluation. The clock is injectable so store\n * contract tests do not sleep. Keep the default in production unless a\n * deployment also tunes the buffer's renewal interval. */\nexport interface TurnEventStoreOptions {\n runningTurnLeaseMs?: number\n now?: () => number\n}\n\n// ── coalescing ────────────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>\n\nfunction deltaTypeOf(ev: unknown): 'text' | 'reasoning' | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? (e.event as AnyRecord | undefined) : e) as AnyRecord | undefined\n if (!inner || typeof inner !== 'object') return null\n if ((inner.type === 'text' || inner.type === 'reasoning') && typeof inner.text === 'string') {\n return inner.type\n }\n return null\n}\n\nfunction innerOf(ev: unknown): AnyRecord | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? e.event : e) as AnyRecord | undefined\n return inner && typeof inner === 'object' ? inner : null\n}\n\n/**\n * The key of a live-state event whose latest value supersedes earlier ones:\n * the model-processing heartbeat, and a harness's raw update of a text or\n * reasoning part (it carries the part's whole state, keyed by part id). Null\n * for every other event.\n */\nfunction liveStateKeyOf(ev: unknown): string | null {\n const inner = innerOf(ev)\n if (!inner) return null\n if (inner.type === 'model-processing') return 'model-processing'\n if (inner.type !== 'raw') return null\n const raw = (inner.data as AnyRecord | undefined)?.event as AnyRecord | undefined\n const part = raw?.part as AnyRecord | undefined\n if ((raw?.type === 'text' || raw?.type === 'reasoning') && typeof part?.id === 'string') return `raw:${part.id}`\n return null\n}\n\n/** Whether an event only projects live progress, so it may wait for the flush window and be coalesced. */\nexport function isLiveProgressEvent(ev: unknown): boolean {\n return deltaTypeOf(ev) !== null || liveStateKeyOf(ev) !== null\n}\n\n/**\n * Merge text and reasoning deltas of the same type into one event, across the\n * live-state events a harness interleaves with them, and keep only the latest\n * of each live-state event. A reasoning model streams three events per token\n * (its raw part update, a model-processing heartbeat and the delta); merging\n * only adjacent deltas wrote all three as rows (1.63 M rows in a\n * day, 59,659 in one turn). Any other event is a boundary nothing merges\n * across. Concatenation-preserving: replaying the coalesced stream produces\n * the same accumulated text, and the latest state of every part.\n */\nexport function coalesceDeltas(events: unknown[]): unknown[] {\n const out: unknown[] = []\n let run: { type: 'text' | 'reasoning'; index: number } | null = null\n let stateSlots = new Map<string, number>()\n for (const ev of events) {\n const type = deltaTypeOf(ev)\n if (type) {\n if (run && run.type === type) {\n const merged = JSON.parse(JSON.stringify(out[run.index])) as AnyRecord\n innerOf(merged)!.text = String(innerOf(out[run.index])!.text) + String(innerOf(ev)!.text)\n out[run.index] = merged\n } else {\n out.push(ev)\n run = { type, index: out.length - 1 }\n }\n continue\n }\n const key = liveStateKeyOf(ev)\n if (key) {\n const slot = stateSlots.get(key)\n if (slot === undefined) {\n out.push(ev)\n stateSlots.set(key, out.length - 1)\n } else {\n out[slot] = ev\n }\n continue\n }\n out.push(ev)\n run = null\n stateSlots = new Map()\n }\n return out\n}\n\nfunction asPartUpdate(ev: unknown): { partId: unknown; delta: unknown } | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object' || e.type !== 'message.part.updated') return null\n const data = e.data as AnyRecord | undefined\n if (!data || typeof data !== 'object') return null\n const part = data.part as AnyRecord | undefined\n const partId = part?.id ?? data.partId ?? part?.partId ?? null\n return { partId, delta: data.delta }\n}\n\n/**\n * Coalesce consecutive `message.part.updated` deltas for the SAME part into one\n * event. agent-runtime products stream `ChatStreamEvent` NDJSON\n * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the\n * buffer with the default tool-loop coalescer, every per-token delta persists as\n * its own row because that coalescer never recognizes the shape. Pass this as\n * {@link PumpBufferedTurnOptions.coalesce} instead.\n *\n * Concatenation-preserving for BOTH consumer styles: the merged event keeps the\n * LATEST event's `data.part` (already the cumulative accumulation) and sets\n * `data.delta` to the concatenation of the merged deltas, so a client that\n * appends `delta` and one that reads the cumulative `part` both reconstruct the\n * identical final text.\n */\nexport function coalesceChatStreamEvents(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const cur = asPartUpdate(ev)\n const prevEv = out[out.length - 1]\n const prev = prevEv ? asPartUpdate(prevEv) : null\n if (cur && prev && cur.partId != null && cur.partId === prev.partId) {\n // Base the merged row on the latest event (its `part` is the most complete\n // accumulation); carry forward the summed delta.\n const merged = JSON.parse(JSON.stringify(ev)) as AnyRecord\n ;(merged.data as AnyRecord).delta = String(prev.delta ?? '') + String(cur.delta ?? '')\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\n// ── buffering core (the tap) ────────────────────────────────────────────────\n\n/** Define options for buffering and flushing turn events with optional live client delivery and event coalescing */\nexport interface BufferedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Deliver one serialized line to the live client. Throwing here (client\n * disconnected) does NOT stop buffering — events keep persisting. */\n write?: (line: string) => Promise<void> | void\n /** Flush buffered events to the store at most this often. Default 400ms. */\n flushIntervalMs?: number\n /** Flush window once a durable owner has taken the turn ({@link BufferedTurnTap.detach}). Live-progress events\n * wait for it; any other event flushes at once, after them. Default 2000ms. */\n detachedFlushIntervalMs?: number\n /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning\n * deltas). agent-runtime products streaming `ChatStreamEvent` pass\n * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a\n * row. Must be concatenation-preserving. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Optional scope (thread/session id) recorded with the turn status, so\n * {@link TurnEventStore.listRunning} can find this turn after a reload. */\n scopeId?: string\n /** How often to renew the running-turn lease while a producer is alive.\n * The timer is backed up by event-driven renewal when a runtime freezes\n * unreferenced timers during remote I/O. Default\n * {@link DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS}. */\n runningTurnRenewIntervalMs?: number\n}\n\n/** A push-driven buffer for a turn whose producer the caller does NOT own. */\nexport interface BufferedTurnTap {\n /** Buffer one event: persist (coalesced, on the flush window) + best-effort\n * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime\n * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call.\n * `execution.started` commits its ordered prefix before this tap's live write. */\n onEvent(raw: unknown): Promise<void>\n /** Settle the turn: final flush + set status. Call after the producer resolves\n * ('complete') or rejects ('error'). 'error' flushes what was produced first. */\n done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>\n /**\n * Give terminal-status ownership to an external durable runner. Stops this\n * tap's running-lease renewal and flushes its current projection, but keeps\n * `onEvent` available as an append-only live-observation path. After the\n * handoff, an event that is not live progress (a marker, interaction, tool\n * event, error or terminal event) flushes before `onEvent` returns, so a\n * durable owner cannot publish terminal status ahead of it; live progress\n * (deltas, heartbeats, raw part updates) is coalesced over\n * `detachedFlushIntervalMs`. Call it again when observation ends to flush any\n * final event.\n *\n * A caller MUST have registered that durable owner before detaching: this\n * method intentionally writes no replacement status.\n */\n detach(): Promise<void>\n}\n\n/**\n * The buffering core. Sequence-numbers every event, delivers it to `write`\n * (best-effort — a disconnected client never stops buffering), and flushes to\n * the store in coalesced batches. Drives both transports:\n *\n * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.\n * • this tap (`onEvent`/`done`) — when the producer owns iteration and only\n * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`\n * + the finished body). Durability stays here in the shell; the engine needs\n * no `TurnEventStore` seam.\n */\n/** Serialized characters of pending events that force a flush before the window ends. */\nconst MAX_PENDING_CHARS = 64 * 1024\n\nexport function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap {\n const flushIntervalMs = opts.flushIntervalMs ?? 400\n const detachedFlushIntervalMs = opts.detachedFlushIntervalMs ?? 2000\n let pendingChars = 0\n const coalesce = opts.coalesce ?? coalesceDeltas\n const startedAt = Date.now()\n let seq = 0\n let clientGone = false\n let firstTextCommitted = false\n let pending: unknown[] = []\n let lastFlush = Date.now()\n let started = false\n let settled = false\n let detached = false\n let renewalTimer: ReturnType<typeof setTimeout> | undefined\n let renewal: Promise<void> = Promise.resolve()\n let lastRenewedAt = 0\n const runningTurnRenewIntervalMs = Math.max(\n 1,\n opts.runningTurnRenewIntervalMs ?? DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,\n )\n\n function clearRenewalTimer(): void {\n if (renewalTimer !== undefined) clearTimeout(renewalTimer)\n renewalTimer = undefined\n }\n\n function scheduleRenewal(): void {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n const elapsedMs = Math.max(0, Date.now() - lastRenewedAt)\n const delayMs = Math.max(1, runningTurnRenewIntervalMs - elapsedMs)\n renewalTimer = setTimeout(() => {\n renewalTimer = undefined\n void renewLease()\n }, delayMs)\n // A deliberately abandoned tap in a Node test must not keep the process\n // alive until the production renewal interval elapses.\n if (typeof renewalTimer === 'object' && 'unref' in renewalTimer) {\n renewalTimer.unref()\n }\n }\n\n async function renewLease(): Promise<void> {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n lastRenewedAt = Date.now()\n renewal = renewal\n .then(() => opts.store.setStatus(opts.turnId, 'running', opts.scopeId))\n .catch(() => {})\n await renewal\n scheduleRenewal()\n }\n\n async function flush(): Promise<void> {\n if (pending.length === 0) return\n const batch = coalesce(pending)\n pending = []\n pendingChars = 0\n const rows = batch.map((ev) => ({ seq: ++seq, event: JSON.stringify(ev) }))\n await opts.store.append(opts.turnId, rows)\n lastFlush = Date.now()\n }\n\n async function ensureStarted(): Promise<void> {\n if (started) return\n started = true\n // An external durable owner may have detached before the first observed\n // event. It owns status from that point, so this tap must never resurrect\n // its running lease.\n if (detached) return\n await opts.store.setStatus(opts.turnId, 'running', opts.scopeId)\n lastRenewedAt = Date.now()\n scheduleRenewal()\n }\n\n return {\n async onEvent(raw) {\n await ensureStarted()\n // Cloudflare may freeze an unreferenced timer while a producer is\n // awaiting remote I/O. A real event (including the route heartbeat)\n // therefore also renews any lease whose interval has elapsed.\n if (\n !detached &&\n opts.scopeId &&\n Date.now() - lastRenewedAt >= runningTurnRenewIntervalMs\n ) {\n await renewLease()\n }\n // Stamp ms-since-turn-start so any stored turn is replayable AND traceable\n // (see ../trace) from the same buffered rows.\n const ev = raw && typeof raw === 'object' ? { ...(raw as Record<string, unknown>), _t: Date.now() - startedAt } : raw\n const line = JSON.stringify(ev)\n pending.push(ev)\n pendingChars += line?.length ?? 0\n // Commit native identity or the first visible text and its ordered prefix.\n const firstText = !firstTextCommitted && deltaTypeOf(ev) === 'text' &&\n (innerOf(ev)!.text as string).trim().length > 0\n if (innerOf(ev)?.type === 'execution.started' || firstText) {\n await flush()\n if (firstText) firstTextCommitted = true\n }\n if (!clientGone && opts.write) {\n try {\n // Live delivery carries a provisional ordering hint, not the persisted\n // seq (coalescing changes seq assignment); clients resume with the\n // seqs from replay, or 0 for \"everything\".\n await opts.write(line)\n } catch {\n clientGone = true\n }\n }\n // Once detached, a turn marker, interaction, tool event, error or terminal event persists at once (with the\n // progress before it), and live progress waits for the window, so a reasoning model's per-token events do\n // not each become a row. An external owner's terminal status can fence at most the last window of progress.\n const due = detached\n ? !isLiveProgressEvent(ev) || Date.now() - lastFlush >= detachedFlushIntervalMs\n : Date.now() - lastFlush >= flushIntervalMs\n if (due || pendingChars >= MAX_PENDING_CHARS) await flush()\n },\n async done(status = 'complete') {\n await ensureStarted()\n if (detached) {\n await flush()\n return\n }\n settled = true\n clearRenewalTimer()\n await renewal\n if (status === 'error') {\n await flush().catch(() => {})\n await opts.store.setStatus(opts.turnId, 'error', opts.scopeId).catch(() => {})\n return\n }\n await flush()\n await opts.store.setStatus(opts.turnId, 'complete', opts.scopeId)\n },\n async detach() {\n detached = true\n clearRenewalTimer()\n // A renewal already queued before detach may be writing `running`. Wait\n // for it before returning so the durable owner can safely publish a\n // terminal status after the awaited handoff.\n await renewal\n await flush()\n },\n }\n}\n\n// ── pump (producer side) ──────────────────────────────────────────────────\n\n/** Define options to pump data from an asynchronous iterable source with buffered turn control */\nexport interface PumpBufferedTurnOptions extends BufferedTurnOptions {\n source: AsyncIterable<unknown>\n}\n\n/**\n * Drive a turn to completion regardless of the live client, when you OWN the\n * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.\n * Returns a promise that resolves when the turn finishes — hand it to\n * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on\n * client-write failure; a source error marks the turn 'error' (after flushing\n * what was produced) and rethrows.\n */\nexport async function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void> {\n const tap = createBufferedTurnTap(opts)\n try {\n for await (const raw of opts.source) await tap.onEvent(raw)\n await tap.done('complete')\n } catch (err) {\n await tap.done('error')\n throw err\n }\n}\n\n// ── replay (consumer side) ────────────────────────────────────────────────\n\n/** Define options for replaying turn events with control over sequence, polling, and timeout */\nexport interface ReplayTurnEventsOptions {\n store: TurnEventStore\n turnId: string\n /** Replay strictly after this sequence number (0 = from the beginning). */\n fromSeq?: number\n /** Poll cadence while the turn is still running. Default 500ms. */\n pollMs?: number\n /** Give up following a 'running' turn after this long. Default 120s. */\n timeoutMs?: number\n}\n\n/**\n * Yield buffered events after `fromSeq`, then keep polling while the turn is\n * still 'running' until it completes, errors, or times out. Terminates with a\n * final `{seq: -1, event: '{\"type\":\"turn_status\",...}'}` marker so clients\n * know why the replay ended.\n */\nexport async function* replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent> {\n const pollMs = opts.pollMs ?? 500\n const timeoutMs = opts.timeoutMs ?? 120_000\n let cursor = opts.fromSeq ?? 0\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n const batch = await opts.store.read(opts.turnId, cursor)\n for (const row of batch) {\n cursor = Math.max(cursor, row.seq)\n yield row\n }\n const status = await opts.store.getStatus(opts.turnId)\n if (status !== 'running') {\n // Writers flush before publishing terminal status; include rows committed after the first read.\n yield* await opts.store.read(opts.turnId, cursor)\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: status ?? 'unknown' }) }\n return\n }\n if (Date.now() >= deadline) {\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: 'timeout' }) }\n return\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Serialize a replayed row for the wire, stamping the buffer ordinal ONTO the\n * line so a reconnecting client can continue from `?fromSeq=<lastSeq>`.\n *\n * The seq lives on the {@link BufferedTurnEvent} row wrapper, not inside the\n * serialized event — `flush()` builds `{seq: ++seq, event: JSON.stringify(ev)}`.\n * A route that enqueues `row.event` alone therefore emits lines with no seq at\n * all, and every client cursor silently pins to 0: each reconnect refetches the\n * whole turn and re-applies every delta onto already-rendered state. This\n * restores the contract `web-react/chat-stream` already documents (\"replayed\n * lines carry an extra `seq` — transparently ignored\").\n *\n * The `{seq: -1}` `turn_status` sentinel is passed through unstamped: it is a\n * terminator, not a cursor position, and stamping it would move a client's\n * cursor to -1.\n *\n * Fail-soft by construction — a line that is not a JSON object passes through\n * verbatim. A stamping bug must degrade to today's behaviour, never break a\n * replay.\n */\nexport function stampReplaySeq(row: BufferedTurnEvent): string {\n if (row.seq <= 0) return row.event\n const line = row.event\n // Cheap splice instead of parse+stringify: these rows are already canonical\n // JSON objects from `JSON.stringify`, and replay is a hot per-event path.\n if (line.charCodeAt(0) !== 0x7b /* { */) return line\n const rest = line.slice(1)\n return rest.trimStart().startsWith('}')\n ? `{\"seq\":${row.seq}${rest}`\n : `{\"seq\":${row.seq},${rest}`\n}\n\n// ── D1 store ──────────────────────────────────────────────────────────────\n\n/** A bound D1 statement used by the turn store. */\nexport interface D1BoundForTurns {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n first<T = Record<string, unknown>>(): Promise<T | null>\n}\n\n/** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */\nexport interface D1LikeForTurns {\n prepare(sql: string): {\n bind(...values: unknown[]): D1BoundForTurns\n }\n /** D1's only atomic primitive. Retention refuses a driver without it rather\n * than deleting events and status in separate, reorderable requests. */\n batch?(statements: D1BoundForTurns[]): Promise<unknown[]>\n}\n\nfunction normalizeTurnCutoff(before: number | Date): { milliseconds: number; iso: string } {\n const milliseconds = before instanceof Date ? before.getTime() : before\n if (!Number.isFinite(milliseconds)) {\n throw new RangeError('turn retention cutoff must be a finite Unix-millisecond timestamp or a valid Date')\n }\n const date = new Date(milliseconds)\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError('turn retention cutoff is outside the supported Date range')\n }\n return { milliseconds, iso: date.toISOString() }\n}\n\nasync function runAtomicTurnBatch(\n db: D1LikeForTurns,\n statements: D1BoundForTurns[],\n): Promise<unknown[]> {\n if (typeof db.batch !== 'function') {\n throw new Error('turn retention requires D1 batch() for atomic deletion')\n }\n return db.batch(statements)\n}\n\nfunction changesFromD1Result(result: unknown): number {\n if (!result || typeof result !== 'object') return 0\n const meta = (result as { meta?: unknown }).meta\n if (meta && typeof meta === 'object') {\n const changes = (meta as { changes?: unknown }).changes\n if (typeof changes === 'number' && Number.isFinite(changes)) return changes\n }\n const changes = (result as { changes?: unknown }).changes\n return typeof changes === 'number' && Number.isFinite(changes) ? changes : 0\n}\n\n/** Schema for the D1 store — append to the product's migrations. */\nexport 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);\nCREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);\n`\n\n/** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —\n * run once to add the column (the CREATE above already includes it for new\n * deployments). SQLite ignores a duplicate-add error if already applied. */\nexport const TURN_STATUS_SCOPE_MIGRATION_SQL = `ALTER TABLE turn_status ADD COLUMN scopeId TEXT;`\n\n/** Run once before using `createD1PlanFollowUpGate`: it adds the lease column\n * the gate fences its claims on. Stores that never take follow-up claims do\n * not need it, so the base turn tables leave it out. */\nexport const TURN_STATUS_LEASE_MIGRATION_SQL = 'ALTER TABLE turn_status ADD COLUMN leaseToken TEXT;'\n\n/** For deployments that already have the turn tables, add the index used by\n * terminal-turn retention without rerunning the table migration. */\nexport const TURN_STATUS_RETENTION_MIGRATION_SQL = 'CREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);'\n\n/** Resolve a TurnEventStore that appends and reads turn events using a D1-like database interface */\n/** A store that lists running turns by scope, as the turn lock's default reclaim needs. */\nexport type ListingTurnEventStore = TurnEventStore & Required<Pick<TurnEventStore, 'listRunning'>>\n\n/** 100 D1 variables per statement, three per row. */\nconst D1_APPEND_CHUNK = 33\n\nexport function createD1TurnEventStore(\n db: D1LikeForTurns,\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, events) {\n if (!events.length) return\n // One multi-row insert per flush window keeps write volume bounded, but\n // D1 caps a statement at 100 bound variables, so a burst of more than 33\n // events (a subagent finishing, a long tool result) failed the whole\n // flush with `D1_ERROR: too many SQL variables` and killed the turn.\n // Rows are appended in order across chunks; a partial failure leaves a\n // prefix, which the ordered `seq` column already tolerates on replay.\n for (let start = 0; start < events.length; start += D1_APPEND_CHUNK) {\n const chunk = events.slice(start, start + D1_APPEND_CHUNK)\n const placeholders = chunk.map(() => '(?, ?, ?)').join(', ')\n const values = chunk.flatMap((e) => [turnId, e.seq, e.event])\n await db\n .prepare(\n `WITH pending(turnId, seq, event) AS (VALUES ${placeholders})\n INSERT OR IGNORE INTO turn_events (turnId, seq, event)\n SELECT pending.turnId, pending.seq, pending.event\n FROM pending\n WHERE NOT EXISTS (\n SELECT 1 FROM turn_status\n WHERE turn_status.turnId = pending.turnId\n AND turn_status.status IN ('complete', 'error')\n )`,\n )\n .bind(...values)\n .run()\n }\n },\n async read(turnId, fromSeq) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? AND seq > ? ORDER BY seq ASC')\n .bind(turnId, fromSeq)\n .all<{ seq: number; event: string }>()\n return results\n },\n async setStatus(turnId, status, scopeId, options = {}) {\n const at = new Date(now()).toISOString()\n if (options.onlyIfRunningBefore !== undefined) {\n // A guarded write never creates a row: it settles one that exists, is running and is stale.\n await db\n .prepare(\n `UPDATE turn_status SET status = ?, scopeId = COALESCE(?, scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = ?'} WHERE turnId = ? AND status = 'running' AND updatedAt < ?`,\n )\n .bind(...[status, scopeId ?? null, ...(options.preserveUpdatedAt ? [] : [at]), turnId, new Date(options.onlyIfRunningBefore).toISOString()])\n .run()\n return\n }\n // COALESCE preserves a scopeId set on the initial 'running' write when a\n // later 'complete'/'error' write passes none.\n await db\n .prepare(\n `INSERT INTO turn_status (turnId, status, scopeId, updatedAt) VALUES (?, ?, ?, ?) ON CONFLICT(turnId) DO UPDATE SET status = excluded.status, scopeId = COALESCE(excluded.scopeId, turn_status.scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = excluded.updatedAt'}`,\n )\n .bind(turnId, status, scopeId ?? null, at)\n .run()\n },\n async getStatus(turnId) {\n const row = await db.prepare('SELECT status FROM turn_status WHERE turnId = ?').bind(turnId).first<{ status: TurnStatus }>()\n return row?.status ?? null\n },\n async listRunning(scopeId) {\n const { results } = await db\n .prepare(\n \"SELECT turnId FROM turn_status WHERE scopeId = ? AND status = 'running' AND updatedAt >= ? ORDER BY updatedAt DESC, rowid DESC\",\n )\n .bind(scopeId, new Date(now() - runningTurnLeaseMs).toISOString())\n .all<{ turnId: string }>()\n return results.map((r) => r.turnId)\n },\n async resetEvents(turnId) {\n await db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId).run()\n },\n async deleteTurn(turnId) {\n await runAtomicTurnBatch(db, [\n db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId),\n db.prepare('DELETE FROM turn_status WHERE turnId = ?').bind(turnId),\n ])\n },\n async listStaleRunning(before, limit) {\n const { results } = await db\n // `*` so a deployment that applied TURN_STATUS_LEASE_MIGRATION_SQL also returns its follow-up claims' leaseToken.\n .prepare(\"SELECT * FROM turn_status WHERE status = 'running' AND updatedAt < ? ORDER BY updatedAt ASC LIMIT ?\")\n .bind(new Date(before).toISOString(), Math.max(1, Math.floor(limit)))\n .all<{ turnId: string; scopeId: string | null; updatedAt: string; leaseToken?: string | null }>()\n return results.map((row) => ({\n turnId: row.turnId,\n scopeId: row.scopeId ?? null,\n updatedAt: Date.parse(row.updatedAt),\n ...(row.leaseToken ? { leaseToken: row.leaseToken } : {}),\n }))\n },\n async readTail(turnId, count) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? ORDER BY seq DESC LIMIT ?')\n .bind(turnId, Math.max(1, Math.floor(count)))\n .all<{ seq: number; event: string }>()\n return results\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before)\n const terminalBefore = \"status IN ('complete', 'error') AND updatedAt < ?\"\n const results = await runAtomicTurnBatch(db, [\n db\n .prepare(\n `DELETE FROM turn_events WHERE turnId IN (SELECT turnId FROM turn_status WHERE ${terminalBefore})`,\n )\n .bind(cutoff.iso),\n db.prepare(`DELETE FROM turn_status WHERE ${terminalBefore}`).bind(cutoff.iso),\n ])\n return changesFromD1Result(results[1])\n },\n }\n}\n\n/** In-memory store for tests and keyless local dev. */\nexport function createMemoryTurnEventStore(\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const events = new Map<string, BufferedTurnEvent[]>()\n const status = new Map<string, TurnStatus>()\n const scopes = new Map<string, string>()\n const order: string[] = []\n const updatedAt = new Map<string, number>()\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, rows) {\n if (status.get(turnId) === 'complete' || status.get(turnId) === 'error') return\n const list = events.get(turnId) ?? []\n list.push(...rows)\n events.set(turnId, list)\n },\n async read(turnId, fromSeq) {\n return (events.get(turnId) ?? []).filter((e) => e.seq > fromSeq)\n },\n async setStatus(turnId, s, scopeId, options = {}) {\n if (options.onlyIfRunningBefore !== undefined) {\n const stale = status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < options.onlyIfRunningBefore\n if (!stale) return\n }\n const existed = status.has(turnId)\n status.set(turnId, s)\n if (scopeId) scopes.set(turnId, scopeId)\n if (!order.includes(turnId)) order.push(turnId)\n if (!(options.preserveUpdatedAt && existed)) updatedAt.set(turnId, now())\n },\n async getStatus(turnId) {\n return status.get(turnId) ?? null\n },\n async listRunning(scopeId) {\n const cutoff = now() - runningTurnLeaseMs\n return order\n .filter(\n (turnId) =>\n status.get(turnId) === 'running' &&\n scopes.get(turnId) === scopeId &&\n (updatedAt.get(turnId) ?? Number.NEGATIVE_INFINITY) >= cutoff,\n )\n .sort((left, right) => {\n const updatedDelta = (updatedAt.get(right) ?? 0) - (updatedAt.get(left) ?? 0)\n return updatedDelta || order.indexOf(right) - order.indexOf(left)\n })\n },\n async resetEvents(turnId) {\n events.delete(turnId)\n },\n async deleteTurn(turnId) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n const index = order.indexOf(turnId)\n if (index >= 0) order.splice(index, 1)\n },\n async listStaleRunning(before, limit) {\n return order\n .filter((turnId) => status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < before)\n .sort((left, right) => (updatedAt.get(left) ?? 0) - (updatedAt.get(right) ?? 0))\n .slice(0, Math.max(1, Math.floor(limit)))\n .map((turnId) => ({ turnId, scopeId: scopes.get(turnId) ?? null, updatedAt: updatedAt.get(turnId)! }))\n },\n async readTail(turnId, count) {\n return (events.get(turnId) ?? []).slice(-Math.max(1, Math.floor(count))).reverse()\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before).milliseconds\n const removable = order.filter((turnId) => {\n const s = status.get(turnId)\n return (s === 'complete' || s === 'error') && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < cutoff\n })\n for (const turnId of removable) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n }\n if (removable.length) {\n const removed = new Set(removable)\n for (let i = order.length - 1; i >= 0; i--) {\n if (removed.has(order[i]!)) order.splice(i, 1)\n }\n }\n return removable.length\n },\n }\n}\n"],"mappings":";AAuBO,IAAM,gCAAgC,IAAI;AAI1C,IAAM,yCAAyC;AAgFtD,SAAS,YAAY,IAA0C;AAC7D,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,QAAS,EAAE,SAAS,UAAW,EAAE,QAAkC;AACzE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,OAAK,MAAM,SAAS,UAAU,MAAM,SAAS,gBAAgB,OAAO,MAAM,SAAS,UAAU;AAC3F,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,IAA+B;AAC9C,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,QAAS,EAAE,SAAS,UAAU,EAAE,QAAQ;AAC9C,SAAO,SAAS,OAAO,UAAU,WAAW,QAAQ;AACtD;AAQA,SAAS,eAAe,IAA4B;AAClD,QAAM,QAAQ,QAAQ,EAAE;AACxB,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,MAAM,SAAS,mBAAoB,QAAO;AAC9C,MAAI,MAAM,SAAS,MAAO,QAAO;AACjC,QAAM,MAAO,MAAM,MAAgC;AACnD,QAAM,OAAO,KAAK;AAClB,OAAK,KAAK,SAAS,UAAU,KAAK,SAAS,gBAAgB,OAAO,MAAM,OAAO,SAAU,QAAO,OAAO,KAAK,EAAE;AAC9G,SAAO;AACT;AAGO,SAAS,oBAAoB,IAAsB;AACxD,SAAO,YAAY,EAAE,MAAM,QAAQ,eAAe,EAAE,MAAM;AAC5D;AAYO,SAAS,eAAe,QAA8B;AAC3D,QAAM,MAAiB,CAAC;AACxB,MAAI,MAA4D;AAChE,MAAI,aAAa,oBAAI,IAA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AE,EAC9E,MAAM,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC,EACvC,IAAI,CAAC,YAAY,EAAE,QAAQ,SAAS,OAAO,IAAI,MAAM,KAAK,MAAM,WAAW,UAAU,IAAI,MAAM,EAAG,EAAE;AAAA,IACzG;AAAA,IACA,MAAM,SAAS,QAAQ,OAAO;AAC5B,cAAQ,OAAO,IAAI,MAAM,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC,CAAC,EAAE,QAAQ;AAAA,IACnF;AAAA,IACA,MAAM,mBAAmB,QAAQ;AAC/B,YAAM,SAAS,oBAAoB,MAAM,EAAE;AAC3C,YAAM,YAAY,MAAM,OAAO,CAAC,WAAW;AACzC,cAAM,IAAI,OAAO,IAAI,MAAM;AAC3B,gBAAQ,MAAM,cAAc,MAAM,aAAa,UAAU,IAAI,MAAM,KAAK,OAAO,qBAAqB;AAAA,MACtG,CAAC;AACD,iBAAW,UAAU,WAAW;AAC9B,eAAO,OAAO,MAAM;AACpB,eAAO,OAAO,MAAM;AACpB,eAAO,OAAO,MAAM;AACpB,kBAAU,OAAO,MAAM;AAAA,MACzB;AACA,UAAI,UAAU,QAAQ;AACpB,cAAM,UAAU,IAAI,IAAI,SAAS;AACjC,iBAAS,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;AAC1C,cAAI,QAAQ,IAAI,MAAM,CAAC,CAAE,EAAG,OAAM,OAAO,GAAG,CAAC;AAAA,QAC/C;AAAA,MACF;AACA,aAAO,UAAU;AAAA,IACnB;AAAA,EACF;AACF;","names":["changes","options"]}
|
|
@@ -17,7 +17,7 @@ import "../chunk-QUV5M7SZ.js";
|
|
|
17
17
|
import {
|
|
18
18
|
assistantRowIdForTurn
|
|
19
19
|
} from "../chunk-QM5TPZQY.js";
|
|
20
|
-
import "../chunk-
|
|
20
|
+
import "../chunk-OV4X4P6U.js";
|
|
21
21
|
import "../chunk-YG66IHDU.js";
|
|
22
22
|
import "../chunk-SADNHPAY.js";
|
|
23
23
|
import "../chunk-ZVEEWGDK.js";
|
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
} from "../chunk-AOSQ5JCO.js";
|
|
36
36
|
import {
|
|
37
37
|
createD1TurnEventStore
|
|
38
|
-
} from "../chunk-
|
|
38
|
+
} from "../chunk-YY3D7LYV.js";
|
|
39
39
|
import "../chunk-6YLVFV3F.js";
|
|
40
40
|
import "../chunk-L3QR274L.js";
|
|
41
41
|
import "../chunk-XELWWXJJ.js";
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createChatTurnRoutes,
|
|
3
3
|
streamChatRouteAsSandboxEvents
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-PFH3EVZN.js";
|
|
5
5
|
import "../chunk-SBHFMDR7.js";
|
|
6
6
|
import "../chunk-H6BRJU5M.js";
|
|
7
7
|
import "../chunk-4DBHC63F.js";
|
|
8
8
|
import "../chunk-RN4WPTBH.js";
|
|
9
9
|
import "../chunk-MM6RLOXF.js";
|
|
10
10
|
import "../chunk-M4QITAQV.js";
|
|
11
|
-
import "../chunk-
|
|
11
|
+
import "../chunk-EHUSCRLY.js";
|
|
12
12
|
import "../chunk-F4TUZYMX.js";
|
|
13
13
|
import "../chunk-MH74DY2I.js";
|
|
14
14
|
import "../chunk-ORC66WNJ.js";
|
|
15
15
|
import "../chunk-QUV5M7SZ.js";
|
|
16
16
|
import "../chunk-QM5TPZQY.js";
|
|
17
|
-
import "../chunk-
|
|
17
|
+
import "../chunk-OV4X4P6U.js";
|
|
18
18
|
import "../chunk-YG66IHDU.js";
|
|
19
19
|
import "../chunk-SADNHPAY.js";
|
|
20
20
|
import "../chunk-ZVEEWGDK.js";
|
|
@@ -23,7 +23,7 @@ import "../chunk-TB6KNPFI.js";
|
|
|
23
23
|
import "../chunk-2IGXFHUO.js";
|
|
24
24
|
import "../chunk-ALIWB2P3.js";
|
|
25
25
|
import "../chunk-AOSQ5JCO.js";
|
|
26
|
-
import "../chunk-
|
|
26
|
+
import "../chunk-YY3D7LYV.js";
|
|
27
27
|
import "../chunk-6YLVFV3F.js";
|
|
28
28
|
import "../chunk-L3QR274L.js";
|
|
29
29
|
import "../chunk-XELWWXJJ.js";
|
|
@@ -36,7 +36,7 @@ import "../chunk-S5SRJJQG.js";
|
|
|
36
36
|
import "../chunk-S25BCP2R.js";
|
|
37
37
|
import "../chunk-UGWQLQDS.js";
|
|
38
38
|
import "../chunk-CUV2EOFB.js";
|
|
39
|
-
import "../chunk-
|
|
39
|
+
import "../chunk-YR4OHHQL.js";
|
|
40
40
|
import "../chunk-D6UJEOZQ.js";
|
|
41
41
|
import "../chunk-VUI4IUIM.js";
|
|
42
42
|
import "../chunk-KDFW6NO5.js";
|
package/dist/runtime/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
ProtectedModelSettlementError,
|
|
3
3
|
createRouterProtectedModelPort,
|
|
4
4
|
runProtectedRouterTurn
|
|
5
|
-
} from "../chunk-
|
|
5
|
+
} from "../chunk-TWFYDZVA.js";
|
|
6
6
|
import {
|
|
7
7
|
DURABLE_HOP_BUDGET_MS,
|
|
8
8
|
asksForLanguage,
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
turnKnowledgeInstructions,
|
|
28
28
|
workspaceKnowledgeForTurn,
|
|
29
29
|
workspaceTurnCheckpoints
|
|
30
|
-
} from "../chunk-
|
|
30
|
+
} from "../chunk-YR4OHHQL.js";
|
|
31
31
|
import {
|
|
32
32
|
DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
|
|
33
33
|
DEFAULT_TANGLE_ROUTER_BASE_URL,
|
|
@@ -294,6 +294,10 @@ export interface RouterTurnOptions {
|
|
|
294
294
|
/** At most this many tool calls run. The next one is refused before it runs and the turn ends
|
|
295
295
|
* with `turn_tool_limit`. */
|
|
296
296
|
maxToolCalls?: number;
|
|
297
|
+
/** How many of one model call's tool calls run at once (the tool loop's `maxConcurrentToolCalls`; agent-runtime
|
|
298
|
+
* 10.0.8 or later). Default 1, one at a time. Results still reach the model and `onEvent` in call order. Raise it
|
|
299
|
+
* only for tools that do not depend on each other finishing first. */
|
|
300
|
+
maxConcurrentToolCalls?: number;
|
|
297
301
|
/** Replace a domain-specific tool result; return undefined to use the shared serialization and limit. */
|
|
298
302
|
renderToolResult?: (toolName: string, outcome: RouterTurnToolOutcome) => string | undefined;
|
|
299
303
|
/**
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
turnKnowledgeInstructions,
|
|
15
15
|
workspaceKnowledgeForTurn,
|
|
16
16
|
workspaceTurnCheckpoints
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-YR4OHHQL.js";
|
|
18
18
|
import "../chunk-D6UJEOZQ.js";
|
|
19
19
|
import "../chunk-VUI4IUIM.js";
|
|
20
20
|
import "../chunk-KDFW6NO5.js";
|
package/dist/sandbox/index.js
CHANGED
|
@@ -114,7 +114,7 @@ import {
|
|
|
114
114
|
warmKey,
|
|
115
115
|
warmReceiptId,
|
|
116
116
|
warmWeekdayOf
|
|
117
|
-
} from "../chunk-
|
|
117
|
+
} from "../chunk-EHUSCRLY.js";
|
|
118
118
|
import {
|
|
119
119
|
createWarmCache
|
|
120
120
|
} from "../chunk-F4TUZYMX.js";
|
|
@@ -163,7 +163,7 @@ import {
|
|
|
163
163
|
} from "../chunk-2IGXFHUO.js";
|
|
164
164
|
import "../chunk-ALIWB2P3.js";
|
|
165
165
|
import "../chunk-AOSQ5JCO.js";
|
|
166
|
-
import "../chunk-
|
|
166
|
+
import "../chunk-YY3D7LYV.js";
|
|
167
167
|
import "../chunk-6YLVFV3F.js";
|
|
168
168
|
import "../chunk-L3QR274L.js";
|
|
169
169
|
import "../chunk-XELWWXJJ.js";
|
package/dist/stream/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
observeTurnEvent,
|
|
6
6
|
parseTurnObservation,
|
|
7
7
|
settleOrphanedTurns
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-OV4X4P6U.js";
|
|
9
9
|
import {
|
|
10
10
|
buildUserTextParts,
|
|
11
11
|
messageHasTurnId,
|
|
@@ -51,7 +51,7 @@ import {
|
|
|
51
51
|
pumpBufferedTurn,
|
|
52
52
|
replayTurnEvents,
|
|
53
53
|
stampReplaySeq
|
|
54
|
-
} from "../chunk-
|
|
54
|
+
} from "../chunk-YY3D7LYV.js";
|
|
55
55
|
import "../chunk-T3C2BX7N.js";
|
|
56
56
|
export {
|
|
57
57
|
DEFAULT_RUNNING_TURN_LEASE_MS,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.50",
|
|
4
4
|
"packageManager": "pnpm@11.28.8",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -805,7 +805,7 @@
|
|
|
805
805
|
"@tangle-network/agent-interface": "^5.10.28",
|
|
806
806
|
"@tangle-network/agent-knowledge": "^23.0.3",
|
|
807
807
|
"@tangle-network/agent-profile-materialize": "^1.1.64",
|
|
808
|
-
"@tangle-network/agent-runtime": "^10.0.
|
|
808
|
+
"@tangle-network/agent-runtime": "^10.0.8",
|
|
809
809
|
"@tangle-network/brand": "^1.31.12",
|
|
810
810
|
"@tangle-network/browser-agent-driver": "^0.37.0",
|
|
811
811
|
"@tangle-network/hub-sdk": "^1.0.21",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-buffer.ts"],"sourcesContent":["/**\n * Resumable chat turns — the router-path answer to \"streams resume on\n * disconnect\" (issue #27). A turn's loop events are teed into a store as they\n * stream; the turn keeps running under `ctx.waitUntil` when the client drops;\n * a reconnecting client replays the buffered tail by sequence number and\n * keeps following until the turn completes.\n *\n * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON\n * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON\n *\n * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation\n * ships here because that's what Cloudflare products have (KV is unsuitable:\n * eventually consistent cross-isolate). Per-token deltas would mean hundreds\n * of rows per turn, so consecutive text/reasoning deltas are coalesced within\n * a flush window before they are persisted — replay yields slightly chunkier\n * deltas with identical concatenation.\n */\n\nexport type TurnStatus = 'running' | 'complete' | 'error'\n\n/** A running row is a renewable lease, not permanent truth. If the process\n * driving a turn dies before writing a terminal status, reconnect discovery\n * must eventually stop returning that abandoned row. */\nexport const DEFAULT_RUNNING_TURN_LEASE_MS = 5 * 60_000\n\n/** Keep a healthy turn's lease comfortably ahead of expiry without turning\n * per-token streaming into status-write traffic. */\nexport const DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS = 30_000\n\n/** Represent a buffered turn event with a sequence number and serialized event data */\nexport interface BufferedTurnEvent {\n seq: number\n /** The serialized event line (JSON string, no trailing newline). */\n event: string\n}\n\n/** Manage and query turn events and their lifecycle statuses within a scoped event store */\nexport interface TurnEventStore {\n /**\n * Append rows while the turn is live. Implementations must ignore rows that\n * arrive after `setStatus` publishes `complete` or `error`; the terminal\n * status is the replay fence for a detached live projection.\n */\n append(turnId: string, events: BufferedTurnEvent[]): Promise<void>\n read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>\n /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets\n * {@link TurnEventStore.listRunning} rediscover this turn after a client reload\n * loses the turnId; stores that don't track scope ignore it. */\n setStatus(turnId: string, status: TurnStatus, scopeId?: string, options?: TurnStatusWriteOptions): Promise<void>\n getStatus(turnId: string): Promise<TurnStatus | null>\n /** Unexpired running turnIds for a scope, newest first — so a reloaded client\n * (clientRunId lost) can find and resume the in-flight turn without reviving\n * a row abandoned by a dead process. Optional: a store records it only if\n * `setStatus` was given a `scopeId`. */\n listRunning?(scopeId: string): Promise<string[]>\n /** Remove one turn's buffered events and keep its status, so a genuine\n * re-stream after a crash starts at seq 0 without interleaving orphaned\n * rows. `runDetachedTurn` requires it to recover a `running` turn. */\n resetEvents?(turnId: string): Promise<void>\n /** Explicitly remove one turn's events and status. Optional so existing\n * custom stores remain source-compatible; the built-in D1 and memory stores\n * provide it. */\n deleteTurn?(turnId: string): Promise<void>\n /** Remove terminal turns whose status was updated before `before` (Unix\n * milliseconds or a Date). Running turns are never eligible. */\n pruneTerminalTurns?(before: number | Date): Promise<number>\n /** Running turns last renewed before `before` (Unix ms), oldest first, at most\n * `limit`: the candidates {@link settleOrphanedTurns} settles. */\n listStaleRunning?(before: number, limit: number): Promise<StaleRunningTurn[]>\n /** The last `count` events of a turn, newest first; a bounded read of the tail. */\n readTail?(turnId: string, count: number): Promise<BufferedTurnEvent[]>\n}\n\n/** A running turn nothing has renewed since `updatedAt`. */\nexport interface StaleRunningTurn {\n turnId: string\n scopeId: string | null\n /** Unix ms of the last status write. */\n updatedAt: number\n /** Set on a plan follow-up claim (`createD1PlanFollowUpGate`), which keeps its own staleness and does not renew. */\n leaseToken?: string | null\n}\n\n/**\n * Settling a stream nothing produces any more. A sweep that ends an orphaned\n * stream must not move it in time, since reports place a stream by its update\n * time, and must not end one whose producer came back meanwhile.\n */\nexport interface TurnStatusWriteOptions {\n /** Keep the row's update time; a new row still takes the current time. */\n preserveUpdatedAt?: boolean\n /** Write only when the row is still `running` and was last updated before this time (Unix ms). */\n onlyIfRunningBefore?: number\n}\n\n/** Configure running-turn lease evaluation. The clock is injectable so store\n * contract tests do not sleep. Keep the default in production unless a\n * deployment also tunes the buffer's renewal interval. */\nexport interface TurnEventStoreOptions {\n runningTurnLeaseMs?: number\n now?: () => number\n}\n\n// ── coalescing ────────────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>\n\nfunction deltaTypeOf(ev: unknown): 'text' | 'reasoning' | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? (e.event as AnyRecord | undefined) : e) as AnyRecord | undefined\n if (!inner || typeof inner !== 'object') return null\n if ((inner.type === 'text' || inner.type === 'reasoning') && typeof inner.text === 'string') {\n return inner.type\n }\n return null\n}\n\nfunction innerOf(ev: unknown): AnyRecord | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? e.event : e) as AnyRecord | undefined\n return inner && typeof inner === 'object' ? inner : null\n}\n\n/**\n * The key of a live-state event whose latest value supersedes earlier ones:\n * the model-processing heartbeat, and a harness's raw update of a text or\n * reasoning part (it carries the part's whole state, keyed by part id). Null\n * for every other event.\n */\nfunction liveStateKeyOf(ev: unknown): string | null {\n const inner = innerOf(ev)\n if (!inner) return null\n if (inner.type === 'model-processing') return 'model-processing'\n if (inner.type !== 'raw') return null\n const raw = (inner.data as AnyRecord | undefined)?.event as AnyRecord | undefined\n const part = raw?.part as AnyRecord | undefined\n if ((raw?.type === 'text' || raw?.type === 'reasoning') && typeof part?.id === 'string') return `raw:${part.id}`\n return null\n}\n\n/** Whether an event only projects live progress, so it may wait for the flush window and be coalesced. */\nexport function isLiveProgressEvent(ev: unknown): boolean {\n return deltaTypeOf(ev) !== null || liveStateKeyOf(ev) !== null\n}\n\n/**\n * Merge text and reasoning deltas of the same type into one event, across the\n * live-state events a harness interleaves with them, and keep only the latest\n * of each live-state event. A reasoning model streams three events per token\n * (its raw part update, a model-processing heartbeat and the delta); merging\n * only adjacent deltas wrote all three as rows (1.63 M rows in a\n * day, 59,659 in one turn). Any other event is a boundary nothing merges\n * across. Concatenation-preserving: replaying the coalesced stream produces\n * the same accumulated text, and the latest state of every part.\n */\nexport function coalesceDeltas(events: unknown[]): unknown[] {\n const out: unknown[] = []\n let run: { type: 'text' | 'reasoning'; index: number } | null = null\n let stateSlots = new Map<string, number>()\n for (const ev of events) {\n const type = deltaTypeOf(ev)\n if (type) {\n if (run && run.type === type) {\n const merged = JSON.parse(JSON.stringify(out[run.index])) as AnyRecord\n innerOf(merged)!.text = String(innerOf(out[run.index])!.text) + String(innerOf(ev)!.text)\n out[run.index] = merged\n } else {\n out.push(ev)\n run = { type, index: out.length - 1 }\n }\n continue\n }\n const key = liveStateKeyOf(ev)\n if (key) {\n const slot = stateSlots.get(key)\n if (slot === undefined) {\n out.push(ev)\n stateSlots.set(key, out.length - 1)\n } else {\n out[slot] = ev\n }\n continue\n }\n out.push(ev)\n run = null\n stateSlots = new Map()\n }\n return out\n}\n\nfunction asPartUpdate(ev: unknown): { partId: unknown; delta: unknown } | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object' || e.type !== 'message.part.updated') return null\n const data = e.data as AnyRecord | undefined\n if (!data || typeof data !== 'object') return null\n const part = data.part as AnyRecord | undefined\n const partId = part?.id ?? data.partId ?? part?.partId ?? null\n return { partId, delta: data.delta }\n}\n\n/**\n * Coalesce consecutive `message.part.updated` deltas for the SAME part into one\n * event. agent-runtime products stream `ChatStreamEvent` NDJSON\n * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the\n * buffer with the default tool-loop coalescer, every per-token delta persists as\n * its own row because that coalescer never recognizes the shape. Pass this as\n * {@link PumpBufferedTurnOptions.coalesce} instead.\n *\n * Concatenation-preserving for BOTH consumer styles: the merged event keeps the\n * LATEST event's `data.part` (already the cumulative accumulation) and sets\n * `data.delta` to the concatenation of the merged deltas, so a client that\n * appends `delta` and one that reads the cumulative `part` both reconstruct the\n * identical final text.\n */\nexport function coalesceChatStreamEvents(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const cur = asPartUpdate(ev)\n const prevEv = out[out.length - 1]\n const prev = prevEv ? asPartUpdate(prevEv) : null\n if (cur && prev && cur.partId != null && cur.partId === prev.partId) {\n // Base the merged row on the latest event (its `part` is the most complete\n // accumulation); carry forward the summed delta.\n const merged = JSON.parse(JSON.stringify(ev)) as AnyRecord\n ;(merged.data as AnyRecord).delta = String(prev.delta ?? '') + String(cur.delta ?? '')\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\n// ── buffering core (the tap) ────────────────────────────────────────────────\n\n/** Define options for buffering and flushing turn events with optional live client delivery and event coalescing */\nexport interface BufferedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Deliver one serialized line to the live client. Throwing here (client\n * disconnected) does NOT stop buffering — events keep persisting. */\n write?: (line: string) => Promise<void> | void\n /** Flush buffered events to the store at most this often. Default 400ms. */\n flushIntervalMs?: number\n /** Flush window once a durable owner has taken the turn ({@link BufferedTurnTap.detach}). Live-progress events\n * wait for it; any other event flushes at once, after them. Default 2000ms. */\n detachedFlushIntervalMs?: number\n /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning\n * deltas). agent-runtime products streaming `ChatStreamEvent` pass\n * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a\n * row. Must be concatenation-preserving. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Optional scope (thread/session id) recorded with the turn status, so\n * {@link TurnEventStore.listRunning} can find this turn after a reload. */\n scopeId?: string\n /** How often to renew the running-turn lease while a producer is alive.\n * The timer is backed up by event-driven renewal when a runtime freezes\n * unreferenced timers during remote I/O. Default\n * {@link DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS}. */\n runningTurnRenewIntervalMs?: number\n}\n\n/** A push-driven buffer for a turn whose producer the caller does NOT own. */\nexport interface BufferedTurnTap {\n /** Buffer one event: persist (coalesced, on the flush window) + best-effort\n * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime\n * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call.\n * `execution.started` commits its ordered prefix before this tap's live write. */\n onEvent(raw: unknown): Promise<void>\n /** Settle the turn: final flush + set status. Call after the producer resolves\n * ('complete') or rejects ('error'). 'error' flushes what was produced first. */\n done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>\n /**\n * Give terminal-status ownership to an external durable runner. Stops this\n * tap's running-lease renewal and flushes its current projection, but keeps\n * `onEvent` available as an append-only live-observation path. After the\n * handoff, an event that is not live progress (a marker, interaction, tool\n * event, error or terminal event) flushes before `onEvent` returns, so a\n * durable owner cannot publish terminal status ahead of it; live progress\n * (deltas, heartbeats, raw part updates) is coalesced over\n * `detachedFlushIntervalMs`. Call it again when observation ends to flush any\n * final event.\n *\n * A caller MUST have registered that durable owner before detaching: this\n * method intentionally writes no replacement status.\n */\n detach(): Promise<void>\n}\n\n/**\n * The buffering core. Sequence-numbers every event, delivers it to `write`\n * (best-effort — a disconnected client never stops buffering), and flushes to\n * the store in coalesced batches. Drives both transports:\n *\n * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.\n * • this tap (`onEvent`/`done`) — when the producer owns iteration and only\n * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`\n * + the finished body). Durability stays here in the shell; the engine needs\n * no `TurnEventStore` seam.\n */\n/** Serialized characters of pending events that force a flush before the window ends. */\nconst MAX_PENDING_CHARS = 64 * 1024\n\nexport function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap {\n const flushIntervalMs = opts.flushIntervalMs ?? 400\n const detachedFlushIntervalMs = opts.detachedFlushIntervalMs ?? 2000\n let pendingChars = 0\n const coalesce = opts.coalesce ?? coalesceDeltas\n const startedAt = Date.now()\n let seq = 0\n let clientGone = false\n let pending: unknown[] = []\n let lastFlush = Date.now()\n let started = false\n let settled = false\n let detached = false\n let renewalTimer: ReturnType<typeof setTimeout> | undefined\n let renewal: Promise<void> = Promise.resolve()\n let lastRenewedAt = 0\n const runningTurnRenewIntervalMs = Math.max(\n 1,\n opts.runningTurnRenewIntervalMs ?? DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,\n )\n\n function clearRenewalTimer(): void {\n if (renewalTimer !== undefined) clearTimeout(renewalTimer)\n renewalTimer = undefined\n }\n\n function scheduleRenewal(): void {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n const elapsedMs = Math.max(0, Date.now() - lastRenewedAt)\n const delayMs = Math.max(1, runningTurnRenewIntervalMs - elapsedMs)\n renewalTimer = setTimeout(() => {\n renewalTimer = undefined\n void renewLease()\n }, delayMs)\n // A deliberately abandoned tap in a Node test must not keep the process\n // alive until the production renewal interval elapses.\n if (typeof renewalTimer === 'object' && 'unref' in renewalTimer) {\n renewalTimer.unref()\n }\n }\n\n async function renewLease(): Promise<void> {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n lastRenewedAt = Date.now()\n renewal = renewal\n .then(() => opts.store.setStatus(opts.turnId, 'running', opts.scopeId))\n .catch(() => {})\n await renewal\n scheduleRenewal()\n }\n\n async function flush(): Promise<void> {\n if (pending.length === 0) return\n const batch = coalesce(pending)\n pending = []\n pendingChars = 0\n const rows = batch.map((ev) => ({ seq: ++seq, event: JSON.stringify(ev) }))\n await opts.store.append(opts.turnId, rows)\n lastFlush = Date.now()\n }\n\n async function ensureStarted(): Promise<void> {\n if (started) return\n started = true\n // An external durable owner may have detached before the first observed\n // event. It owns status from that point, so this tap must never resurrect\n // its running lease.\n if (detached) return\n await opts.store.setStatus(opts.turnId, 'running', opts.scopeId)\n lastRenewedAt = Date.now()\n scheduleRenewal()\n }\n\n return {\n async onEvent(raw) {\n await ensureStarted()\n // Cloudflare may freeze an unreferenced timer while a producer is\n // awaiting remote I/O. A real event (including the route heartbeat)\n // therefore also renews any lease whose interval has elapsed.\n if (\n !detached &&\n opts.scopeId &&\n Date.now() - lastRenewedAt >= runningTurnRenewIntervalMs\n ) {\n await renewLease()\n }\n // Stamp ms-since-turn-start so any stored turn is replayable AND traceable\n // (see ../trace) from the same buffered rows.\n const ev = raw && typeof raw === 'object' ? { ...(raw as Record<string, unknown>), _t: Date.now() - startedAt } : raw\n const line = JSON.stringify(ev)\n pending.push(ev)\n pendingChars += line?.length ?? 0\n // Commit the native identity and its ordered prefix before our live write.\n if (innerOf(ev)?.type === 'execution.started') await flush()\n if (!clientGone && opts.write) {\n try {\n // Live delivery carries a provisional ordering hint, not the persisted\n // seq (coalescing changes seq assignment); clients resume with the\n // seqs from replay, or 0 for \"everything\".\n await opts.write(line)\n } catch {\n clientGone = true\n }\n }\n // Once detached, a turn marker, interaction, tool event, error or terminal event persists at once (with the\n // progress before it), and live progress waits for the window, so a reasoning model's per-token events do\n // not each become a row. An external owner's terminal status can fence at most the last window of progress.\n const due = detached\n ? !isLiveProgressEvent(ev) || Date.now() - lastFlush >= detachedFlushIntervalMs\n : Date.now() - lastFlush >= flushIntervalMs\n if (due || pendingChars >= MAX_PENDING_CHARS) await flush()\n },\n async done(status = 'complete') {\n await ensureStarted()\n if (detached) {\n await flush()\n return\n }\n settled = true\n clearRenewalTimer()\n await renewal\n if (status === 'error') {\n await flush().catch(() => {})\n await opts.store.setStatus(opts.turnId, 'error', opts.scopeId).catch(() => {})\n return\n }\n await flush()\n await opts.store.setStatus(opts.turnId, 'complete', opts.scopeId)\n },\n async detach() {\n detached = true\n clearRenewalTimer()\n // A renewal already queued before detach may be writing `running`. Wait\n // for it before returning so the durable owner can safely publish a\n // terminal status after the awaited handoff.\n await renewal\n await flush()\n },\n }\n}\n\n// ── pump (producer side) ──────────────────────────────────────────────────\n\n/** Define options to pump data from an asynchronous iterable source with buffered turn control */\nexport interface PumpBufferedTurnOptions extends BufferedTurnOptions {\n source: AsyncIterable<unknown>\n}\n\n/**\n * Drive a turn to completion regardless of the live client, when you OWN the\n * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.\n * Returns a promise that resolves when the turn finishes — hand it to\n * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on\n * client-write failure; a source error marks the turn 'error' (after flushing\n * what was produced) and rethrows.\n */\nexport async function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void> {\n const tap = createBufferedTurnTap(opts)\n try {\n for await (const raw of opts.source) await tap.onEvent(raw)\n await tap.done('complete')\n } catch (err) {\n await tap.done('error')\n throw err\n }\n}\n\n// ── replay (consumer side) ────────────────────────────────────────────────\n\n/** Define options for replaying turn events with control over sequence, polling, and timeout */\nexport interface ReplayTurnEventsOptions {\n store: TurnEventStore\n turnId: string\n /** Replay strictly after this sequence number (0 = from the beginning). */\n fromSeq?: number\n /** Poll cadence while the turn is still running. Default 500ms. */\n pollMs?: number\n /** Give up following a 'running' turn after this long. Default 120s. */\n timeoutMs?: number\n}\n\n/**\n * Yield buffered events after `fromSeq`, then keep polling while the turn is\n * still 'running' until it completes, errors, or times out. Terminates with a\n * final `{seq: -1, event: '{\"type\":\"turn_status\",...}'}` marker so clients\n * know why the replay ended.\n */\nexport async function* replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent> {\n const pollMs = opts.pollMs ?? 500\n const timeoutMs = opts.timeoutMs ?? 120_000\n let cursor = opts.fromSeq ?? 0\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n const batch = await opts.store.read(opts.turnId, cursor)\n for (const row of batch) {\n cursor = Math.max(cursor, row.seq)\n yield row\n }\n const status = await opts.store.getStatus(opts.turnId)\n if (status !== 'running') {\n // Writers flush before publishing terminal status; include rows committed after the first read.\n yield* await opts.store.read(opts.turnId, cursor)\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: status ?? 'unknown' }) }\n return\n }\n if (Date.now() >= deadline) {\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: 'timeout' }) }\n return\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Serialize a replayed row for the wire, stamping the buffer ordinal ONTO the\n * line so a reconnecting client can continue from `?fromSeq=<lastSeq>`.\n *\n * The seq lives on the {@link BufferedTurnEvent} row wrapper, not inside the\n * serialized event — `flush()` builds `{seq: ++seq, event: JSON.stringify(ev)}`.\n * A route that enqueues `row.event` alone therefore emits lines with no seq at\n * all, and every client cursor silently pins to 0: each reconnect refetches the\n * whole turn and re-applies every delta onto already-rendered state. This\n * restores the contract `web-react/chat-stream` already documents (\"replayed\n * lines carry an extra `seq` — transparently ignored\").\n *\n * The `{seq: -1}` `turn_status` sentinel is passed through unstamped: it is a\n * terminator, not a cursor position, and stamping it would move a client's\n * cursor to -1.\n *\n * Fail-soft by construction — a line that is not a JSON object passes through\n * verbatim. A stamping bug must degrade to today's behaviour, never break a\n * replay.\n */\nexport function stampReplaySeq(row: BufferedTurnEvent): string {\n if (row.seq <= 0) return row.event\n const line = row.event\n // Cheap splice instead of parse+stringify: these rows are already canonical\n // JSON objects from `JSON.stringify`, and replay is a hot per-event path.\n if (line.charCodeAt(0) !== 0x7b /* { */) return line\n const rest = line.slice(1)\n return rest.trimStart().startsWith('}')\n ? `{\"seq\":${row.seq}${rest}`\n : `{\"seq\":${row.seq},${rest}`\n}\n\n// ── D1 store ──────────────────────────────────────────────────────────────\n\n/** A bound D1 statement used by the turn store. */\nexport interface D1BoundForTurns {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n first<T = Record<string, unknown>>(): Promise<T | null>\n}\n\n/** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */\nexport interface D1LikeForTurns {\n prepare(sql: string): {\n bind(...values: unknown[]): D1BoundForTurns\n }\n /** D1's only atomic primitive. Retention refuses a driver without it rather\n * than deleting events and status in separate, reorderable requests. */\n batch?(statements: D1BoundForTurns[]): Promise<unknown[]>\n}\n\nfunction normalizeTurnCutoff(before: number | Date): { milliseconds: number; iso: string } {\n const milliseconds = before instanceof Date ? before.getTime() : before\n if (!Number.isFinite(milliseconds)) {\n throw new RangeError('turn retention cutoff must be a finite Unix-millisecond timestamp or a valid Date')\n }\n const date = new Date(milliseconds)\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError('turn retention cutoff is outside the supported Date range')\n }\n return { milliseconds, iso: date.toISOString() }\n}\n\nasync function runAtomicTurnBatch(\n db: D1LikeForTurns,\n statements: D1BoundForTurns[],\n): Promise<unknown[]> {\n if (typeof db.batch !== 'function') {\n throw new Error('turn retention requires D1 batch() for atomic deletion')\n }\n return db.batch(statements)\n}\n\nfunction changesFromD1Result(result: unknown): number {\n if (!result || typeof result !== 'object') return 0\n const meta = (result as { meta?: unknown }).meta\n if (meta && typeof meta === 'object') {\n const changes = (meta as { changes?: unknown }).changes\n if (typeof changes === 'number' && Number.isFinite(changes)) return changes\n }\n const changes = (result as { changes?: unknown }).changes\n return typeof changes === 'number' && Number.isFinite(changes) ? changes : 0\n}\n\n/** Schema for the D1 store — append to the product's migrations. */\nexport 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);\nCREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);\n`\n\n/** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —\n * run once to add the column (the CREATE above already includes it for new\n * deployments). SQLite ignores a duplicate-add error if already applied. */\nexport const TURN_STATUS_SCOPE_MIGRATION_SQL = `ALTER TABLE turn_status ADD COLUMN scopeId TEXT;`\n\n/** Run once before using `createD1PlanFollowUpGate`: it adds the lease column\n * the gate fences its claims on. Stores that never take follow-up claims do\n * not need it, so the base turn tables leave it out. */\nexport const TURN_STATUS_LEASE_MIGRATION_SQL = 'ALTER TABLE turn_status ADD COLUMN leaseToken TEXT;'\n\n/** For deployments that already have the turn tables, add the index used by\n * terminal-turn retention without rerunning the table migration. */\nexport const TURN_STATUS_RETENTION_MIGRATION_SQL = 'CREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);'\n\n/** Resolve a TurnEventStore that appends and reads turn events using a D1-like database interface */\n/** A store that lists running turns by scope, as the turn lock's default reclaim needs. */\nexport type ListingTurnEventStore = TurnEventStore & Required<Pick<TurnEventStore, 'listRunning'>>\n\n/** 100 D1 variables per statement, three per row. */\nconst D1_APPEND_CHUNK = 33\n\nexport function createD1TurnEventStore(\n db: D1LikeForTurns,\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, events) {\n if (!events.length) return\n // One multi-row insert per flush window keeps write volume bounded, but\n // D1 caps a statement at 100 bound variables, so a burst of more than 33\n // events (a subagent finishing, a long tool result) failed the whole\n // flush with `D1_ERROR: too many SQL variables` and killed the turn.\n // Rows are appended in order across chunks; a partial failure leaves a\n // prefix, which the ordered `seq` column already tolerates on replay.\n for (let start = 0; start < events.length; start += D1_APPEND_CHUNK) {\n const chunk = events.slice(start, start + D1_APPEND_CHUNK)\n const placeholders = chunk.map(() => '(?, ?, ?)').join(', ')\n const values = chunk.flatMap((e) => [turnId, e.seq, e.event])\n await db\n .prepare(\n `WITH pending(turnId, seq, event) AS (VALUES ${placeholders})\n INSERT OR IGNORE INTO turn_events (turnId, seq, event)\n SELECT pending.turnId, pending.seq, pending.event\n FROM pending\n WHERE NOT EXISTS (\n SELECT 1 FROM turn_status\n WHERE turn_status.turnId = pending.turnId\n AND turn_status.status IN ('complete', 'error')\n )`,\n )\n .bind(...values)\n .run()\n }\n },\n async read(turnId, fromSeq) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? AND seq > ? ORDER BY seq ASC')\n .bind(turnId, fromSeq)\n .all<{ seq: number; event: string }>()\n return results\n },\n async setStatus(turnId, status, scopeId, options = {}) {\n const at = new Date(now()).toISOString()\n if (options.onlyIfRunningBefore !== undefined) {\n // A guarded write never creates a row: it settles one that exists, is running and is stale.\n await db\n .prepare(\n `UPDATE turn_status SET status = ?, scopeId = COALESCE(?, scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = ?'} WHERE turnId = ? AND status = 'running' AND updatedAt < ?`,\n )\n .bind(...[status, scopeId ?? null, ...(options.preserveUpdatedAt ? [] : [at]), turnId, new Date(options.onlyIfRunningBefore).toISOString()])\n .run()\n return\n }\n // COALESCE preserves a scopeId set on the initial 'running' write when a\n // later 'complete'/'error' write passes none.\n await db\n .prepare(\n `INSERT INTO turn_status (turnId, status, scopeId, updatedAt) VALUES (?, ?, ?, ?) ON CONFLICT(turnId) DO UPDATE SET status = excluded.status, scopeId = COALESCE(excluded.scopeId, turn_status.scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = excluded.updatedAt'}`,\n )\n .bind(turnId, status, scopeId ?? null, at)\n .run()\n },\n async getStatus(turnId) {\n const row = await db.prepare('SELECT status FROM turn_status WHERE turnId = ?').bind(turnId).first<{ status: TurnStatus }>()\n return row?.status ?? null\n },\n async listRunning(scopeId) {\n const { results } = await db\n .prepare(\n \"SELECT turnId FROM turn_status WHERE scopeId = ? AND status = 'running' AND updatedAt >= ? ORDER BY updatedAt DESC, rowid DESC\",\n )\n .bind(scopeId, new Date(now() - runningTurnLeaseMs).toISOString())\n .all<{ turnId: string }>()\n return results.map((r) => r.turnId)\n },\n async resetEvents(turnId) {\n await db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId).run()\n },\n async deleteTurn(turnId) {\n await runAtomicTurnBatch(db, [\n db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId),\n db.prepare('DELETE FROM turn_status WHERE turnId = ?').bind(turnId),\n ])\n },\n async listStaleRunning(before, limit) {\n const { results } = await db\n // `*` so a deployment that applied TURN_STATUS_LEASE_MIGRATION_SQL also returns its follow-up claims' leaseToken.\n .prepare(\"SELECT * FROM turn_status WHERE status = 'running' AND updatedAt < ? ORDER BY updatedAt ASC LIMIT ?\")\n .bind(new Date(before).toISOString(), Math.max(1, Math.floor(limit)))\n .all<{ turnId: string; scopeId: string | null; updatedAt: string; leaseToken?: string | null }>()\n return results.map((row) => ({\n turnId: row.turnId,\n scopeId: row.scopeId ?? null,\n updatedAt: Date.parse(row.updatedAt),\n ...(row.leaseToken ? { leaseToken: row.leaseToken } : {}),\n }))\n },\n async readTail(turnId, count) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? ORDER BY seq DESC LIMIT ?')\n .bind(turnId, Math.max(1, Math.floor(count)))\n .all<{ seq: number; event: string }>()\n return results\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before)\n const terminalBefore = \"status IN ('complete', 'error') AND updatedAt < ?\"\n const results = await runAtomicTurnBatch(db, [\n db\n .prepare(\n `DELETE FROM turn_events WHERE turnId IN (SELECT turnId FROM turn_status WHERE ${terminalBefore})`,\n )\n .bind(cutoff.iso),\n db.prepare(`DELETE FROM turn_status WHERE ${terminalBefore}`).bind(cutoff.iso),\n ])\n return changesFromD1Result(results[1])\n },\n }\n}\n\n/** In-memory store for tests and keyless local dev. */\nexport function createMemoryTurnEventStore(\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const events = new Map<string, BufferedTurnEvent[]>()\n const status = new Map<string, TurnStatus>()\n const scopes = new Map<string, string>()\n const order: string[] = []\n const updatedAt = new Map<string, number>()\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, rows) {\n if (status.get(turnId) === 'complete' || status.get(turnId) === 'error') return\n const list = events.get(turnId) ?? []\n list.push(...rows)\n events.set(turnId, list)\n },\n async read(turnId, fromSeq) {\n return (events.get(turnId) ?? []).filter((e) => e.seq > fromSeq)\n },\n async setStatus(turnId, s, scopeId, options = {}) {\n if (options.onlyIfRunningBefore !== undefined) {\n const stale = status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < options.onlyIfRunningBefore\n if (!stale) return\n }\n const existed = status.has(turnId)\n status.set(turnId, s)\n if (scopeId) scopes.set(turnId, scopeId)\n if (!order.includes(turnId)) order.push(turnId)\n if (!(options.preserveUpdatedAt && existed)) updatedAt.set(turnId, now())\n },\n async getStatus(turnId) {\n return status.get(turnId) ?? null\n },\n async listRunning(scopeId) {\n const cutoff = now() - runningTurnLeaseMs\n return order\n .filter(\n (turnId) =>\n status.get(turnId) === 'running' &&\n scopes.get(turnId) === scopeId &&\n (updatedAt.get(turnId) ?? Number.NEGATIVE_INFINITY) >= cutoff,\n )\n .sort((left, right) => {\n const updatedDelta = (updatedAt.get(right) ?? 0) - (updatedAt.get(left) ?? 0)\n return updatedDelta || order.indexOf(right) - order.indexOf(left)\n })\n },\n async resetEvents(turnId) {\n events.delete(turnId)\n },\n async deleteTurn(turnId) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n const index = order.indexOf(turnId)\n if (index >= 0) order.splice(index, 1)\n },\n async listStaleRunning(before, limit) {\n return order\n .filter((turnId) => status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < before)\n .sort((left, right) => (updatedAt.get(left) ?? 0) - (updatedAt.get(right) ?? 0))\n .slice(0, Math.max(1, Math.floor(limit)))\n .map((turnId) => ({ turnId, scopeId: scopes.get(turnId) ?? null, updatedAt: updatedAt.get(turnId)! }))\n },\n async readTail(turnId, count) {\n return (events.get(turnId) ?? []).slice(-Math.max(1, Math.floor(count))).reverse()\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before).milliseconds\n const removable = order.filter((turnId) => {\n const s = status.get(turnId)\n return (s === 'complete' || s === 'error') && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < cutoff\n })\n for (const turnId of removable) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n }\n if (removable.length) {\n const removed = new Set(removable)\n for (let i = order.length - 1; i >= 0; i--) {\n if (removed.has(order[i]!)) order.splice(i, 1)\n }\n }\n return removable.length\n },\n }\n}\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