@langchain/langgraph-sdk
Advanced tools
| const require_channel = require("./channel.cjs"); | ||
| //#region src/stream/projections/channel-effect.ts | ||
| /** | ||
| * Acquire a side-effect subscription over one or more channels. | ||
| * | ||
| * @param registry - The stream's {@link ChannelRegistry}. | ||
| * @param channels - Channels to observe (e.g. `["lifecycle", "tools"]`). | ||
| * @param namespace - Resolved namespace (`[]` for the root). | ||
| * @param options - Callbacks plus projection (`bufferSize`/`replay`) | ||
| * options. | ||
| * @returns A `dispose()` function that detaches the listener and | ||
| * releases the ref-counted projection. Idempotent. | ||
| */ | ||
| function acquireChannelEffect(registry, channels, namespace, options) { | ||
| const { onEvent, onError, ...projectionOptions } = options; | ||
| const acquired = registry.acquire(require_channel.channelProjection(channels, namespace, { | ||
| replay: projectionOptions.replay ?? false, | ||
| bufferSize: projectionOptions.bufferSize | ||
| })); | ||
| const { store } = acquired; | ||
| const initial = store.getSnapshot(); | ||
| let lastDelivered = initial.length > 0 ? initial[initial.length - 1] : void 0; | ||
| const deliver = () => { | ||
| const snapshot = store.getSnapshot(); | ||
| let start = 0; | ||
| if (lastDelivered !== void 0) { | ||
| const index = snapshot.lastIndexOf(lastDelivered); | ||
| start = index === -1 ? 0 : index + 1; | ||
| } | ||
| for (let i = start; i < snapshot.length; i += 1) { | ||
| const event = snapshot[i]; | ||
| try { | ||
| onEvent(event); | ||
| } catch (error) { | ||
| if (onError) onError(error); | ||
| } | ||
| } | ||
| if (snapshot.length > 0) lastDelivered = snapshot[snapshot.length - 1]; | ||
| }; | ||
| const unsubscribe = store.subscribe(deliver); | ||
| let released = false; | ||
| return () => { | ||
| if (released) return; | ||
| released = true; | ||
| unsubscribe(); | ||
| acquired.release(); | ||
| }; | ||
| } | ||
| //#endregion | ||
| exports.acquireChannelEffect = acquireChannelEffect; | ||
| //# sourceMappingURL=channel-effect.cjs.map |
| {"version":3,"file":"channel-effect.cjs","names":["channelProjection"],"sources":["../../../src/stream/projections/channel-effect.ts"],"sourcesContent":["/**\n * Side-effect counterpart to {@link channelProjection}.\n *\n * Where `channelProjection` retains a bounded *buffer* of raw events\n * for rendering, this helper delivers each event to a callback exactly\n * once — the idiomatic shape for analytics, logging, and other side\n * effects that should not live in render. Framework bindings wrap it as\n * `useChannelEffect` (React/Svelte/Vue) / `injectChannelEffect`\n * (Angular).\n *\n * # Why this is built on the registry\n *\n * It acquires the very same ref-counted {@link channelProjection} entry\n * that the selector hooks use, so:\n *\n * - N consumers of the same `channels`/`namespace`/options share a\n * single server subscription (the registry dedupes by `spec.key`).\n * - The subscription survives thread swaps for free (the registry\n * rebinds every live entry on `controller.hydrate(...)`).\n *\n * Each consumer then diffs the shared store independently, so multiple\n * `useChannelEffect` callers with *different* callbacks each receive\n * their own delivery.\n *\n * # Delivery semantics\n *\n * - Only events that arrive while the effect is attached are\n * delivered. Events already buffered when the effect attaches (e.g.\n * a sibling `useChannel` populated the buffer first) are skipped —\n * analytics must not double-count history on a late mount.\n * - `channelProjection` appends exactly one event per store\n * notification, so the cursor below tracks the last delivered event\n * by identity and forwards everything after it. On a thread rebind\n * the store resets to `[]`; the old cursor is no longer found, so\n * the next batch of events for the new thread is delivered from the\n * start.\n * - `replay` is forwarded to the projection. It defaults to `false`\n * here (live-only) — the opposite of `useChannel`'s buffer default —\n * because firing analytics for replayed history is rarely what a\n * side-effect consumer wants.\n */\nimport type { Channel, Event } from \"@langchain/protocol\";\nimport type { ChannelRegistry } from \"../channel-registry.js\";\nimport { channelProjection, type ChannelProjectionOptions } from \"./channel.js\";\n\n/**\n * Options for {@link acquireChannelEffect}. Extends\n * {@link ChannelProjectionOptions} (`bufferSize`, `replay`) with the\n * per-event callback and an optional error sink.\n */\nexport interface ChannelEffectOptions extends ChannelProjectionOptions {\n /** Invoked once for every event observed while attached. */\n onEvent: (event: Event) => void;\n /**\n * Invoked when {@link onEvent} throws. When omitted, a throwing\n * `onEvent` is swallowed so one bad delivery cannot wedge the shared\n * store's notification loop or other consumers.\n */\n onError?: (error: unknown) => void;\n}\n\n/**\n * Acquire a side-effect subscription over one or more channels.\n *\n * @param registry - The stream's {@link ChannelRegistry}.\n * @param channels - Channels to observe (e.g. `[\"lifecycle\", \"tools\"]`).\n * @param namespace - Resolved namespace (`[]` for the root).\n * @param options - Callbacks plus projection (`bufferSize`/`replay`)\n * options.\n * @returns A `dispose()` function that detaches the listener and\n * releases the ref-counted projection. Idempotent.\n */\nexport function acquireChannelEffect(\n registry: ChannelRegistry,\n channels: readonly Channel[],\n namespace: readonly string[],\n options: ChannelEffectOptions\n): () => void {\n const { onEvent, onError, ...projectionOptions } = options;\n const acquired = registry.acquire<Event[]>(\n channelProjection(channels, namespace, {\n // Live-only by default for side effects; callers opt into replay\n // explicitly when they want to re-process history.\n replay: projectionOptions.replay ?? false,\n bufferSize: projectionOptions.bufferSize,\n })\n );\n const { store } = acquired;\n\n // Cursor: the last event already delivered to `onEvent`. Seeded with\n // the current tail so events buffered before this consumer attached\n // are skipped (no double-counting on a late mount).\n const initial = store.getSnapshot();\n let lastDelivered: Event | undefined =\n initial.length > 0 ? initial[initial.length - 1] : undefined;\n\n const deliver = (): void => {\n const snapshot = store.getSnapshot();\n let start = 0;\n if (lastDelivered !== undefined) {\n const index = snapshot.lastIndexOf(lastDelivered);\n // `index === -1` means the cursor fell out of the buffer (thread\n // rebind reset the store, or the bounded buffer evicted it).\n // Deliver from the start of the current snapshot.\n start = index === -1 ? 0 : index + 1;\n }\n for (let i = start; i < snapshot.length; i += 1) {\n const event = snapshot[i] as Event;\n try {\n onEvent(event);\n } catch (error) {\n if (onError) onError(error);\n }\n }\n if (snapshot.length > 0) {\n lastDelivered = snapshot[snapshot.length - 1];\n }\n };\n\n const unsubscribe = store.subscribe(deliver);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n unsubscribe();\n acquired.release();\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwEA,SAAgB,qBACd,UACA,UACA,WACA,SACY;CACZ,MAAM,EAAE,SAAS,SAAS,GAAG,sBAAsB;CACnD,MAAM,WAAW,SAAS,QACxBA,gBAAAA,kBAAkB,UAAU,WAAW;EAGrC,QAAQ,kBAAkB,UAAU;EACpC,YAAY,kBAAkB;EAC/B,CAAC,CACH;CACD,MAAM,EAAE,UAAU;CAKlB,MAAM,UAAU,MAAM,aAAa;CACnC,IAAI,gBACF,QAAQ,SAAS,IAAI,QAAQ,QAAQ,SAAS,KAAK,KAAA;CAErD,MAAM,gBAAsB;EAC1B,MAAM,WAAW,MAAM,aAAa;EACpC,IAAI,QAAQ;AACZ,MAAI,kBAAkB,KAAA,GAAW;GAC/B,MAAM,QAAQ,SAAS,YAAY,cAAc;AAIjD,WAAQ,UAAU,KAAK,IAAI,QAAQ;;AAErC,OAAK,IAAI,IAAI,OAAO,IAAI,SAAS,QAAQ,KAAK,GAAG;GAC/C,MAAM,QAAQ,SAAS;AACvB,OAAI;AACF,YAAQ,MAAM;YACP,OAAO;AACd,QAAI,QAAS,SAAQ,MAAM;;;AAG/B,MAAI,SAAS,SAAS,EACpB,iBAAgB,SAAS,SAAS,SAAS;;CAI/C,MAAM,cAAc,MAAM,UAAU,QAAQ;CAE5C,IAAI,WAAW;AACf,cAAa;AACX,MAAI,SAAU;AACd,aAAW;AACX,eAAa;AACb,WAAS,SAAS"} |
| import { ChannelRegistry } from "../channel-registry.cjs"; | ||
| import { ChannelProjectionOptions } from "./channel.cjs"; | ||
| import { Channel, Event } from "@langchain/protocol"; | ||
| //#region src/stream/projections/channel-effect.d.ts | ||
| /** | ||
| * Options for {@link acquireChannelEffect}. Extends | ||
| * {@link ChannelProjectionOptions} (`bufferSize`, `replay`) with the | ||
| * per-event callback and an optional error sink. | ||
| */ | ||
| interface ChannelEffectOptions extends ChannelProjectionOptions { | ||
| /** Invoked once for every event observed while attached. */ | ||
| onEvent: (event: Event) => void; | ||
| /** | ||
| * Invoked when {@link onEvent} throws. When omitted, a throwing | ||
| * `onEvent` is swallowed so one bad delivery cannot wedge the shared | ||
| * store's notification loop or other consumers. | ||
| */ | ||
| onError?: (error: unknown) => void; | ||
| } | ||
| /** | ||
| * Acquire a side-effect subscription over one or more channels. | ||
| * | ||
| * @param registry - The stream's {@link ChannelRegistry}. | ||
| * @param channels - Channels to observe (e.g. `["lifecycle", "tools"]`). | ||
| * @param namespace - Resolved namespace (`[]` for the root). | ||
| * @param options - Callbacks plus projection (`bufferSize`/`replay`) | ||
| * options. | ||
| * @returns A `dispose()` function that detaches the listener and | ||
| * releases the ref-counted projection. Idempotent. | ||
| */ | ||
| declare function acquireChannelEffect(registry: ChannelRegistry, channels: readonly Channel[], namespace: readonly string[], options: ChannelEffectOptions): () => void; | ||
| //#endregion | ||
| export { ChannelEffectOptions, acquireChannelEffect }; | ||
| //# sourceMappingURL=channel-effect.d.cts.map |
| {"version":3,"file":"channel-effect.d.cts","names":[],"sources":["../../../src/stream/projections/channel-effect.ts"],"mappings":";;;;;;;;;;UAkDiB,oBAAA,SAA6B,wBAAA;;EAE5C,OAAA,GAAU,KAAA,EAAO,KAAA;;;;;;EAMjB,OAAA,IAAW,KAAA;AAAA;;;;;;;;;;;;iBAcG,oBAAA,CACd,QAAA,EAAU,eAAA,EACV,QAAA,WAAmB,OAAA,IACnB,SAAA,qBACA,OAAA,EAAS,oBAAA"} |
| import { ChannelRegistry } from "../channel-registry.js"; | ||
| import { ChannelProjectionOptions } from "./channel.js"; | ||
| import { Channel, Event } from "@langchain/protocol"; | ||
| //#region src/stream/projections/channel-effect.d.ts | ||
| /** | ||
| * Options for {@link acquireChannelEffect}. Extends | ||
| * {@link ChannelProjectionOptions} (`bufferSize`, `replay`) with the | ||
| * per-event callback and an optional error sink. | ||
| */ | ||
| interface ChannelEffectOptions extends ChannelProjectionOptions { | ||
| /** Invoked once for every event observed while attached. */ | ||
| onEvent: (event: Event) => void; | ||
| /** | ||
| * Invoked when {@link onEvent} throws. When omitted, a throwing | ||
| * `onEvent` is swallowed so one bad delivery cannot wedge the shared | ||
| * store's notification loop or other consumers. | ||
| */ | ||
| onError?: (error: unknown) => void; | ||
| } | ||
| /** | ||
| * Acquire a side-effect subscription over one or more channels. | ||
| * | ||
| * @param registry - The stream's {@link ChannelRegistry}. | ||
| * @param channels - Channels to observe (e.g. `["lifecycle", "tools"]`). | ||
| * @param namespace - Resolved namespace (`[]` for the root). | ||
| * @param options - Callbacks plus projection (`bufferSize`/`replay`) | ||
| * options. | ||
| * @returns A `dispose()` function that detaches the listener and | ||
| * releases the ref-counted projection. Idempotent. | ||
| */ | ||
| declare function acquireChannelEffect(registry: ChannelRegistry, channels: readonly Channel[], namespace: readonly string[], options: ChannelEffectOptions): () => void; | ||
| //#endregion | ||
| export { ChannelEffectOptions, acquireChannelEffect }; | ||
| //# sourceMappingURL=channel-effect.d.ts.map |
| {"version":3,"file":"channel-effect.d.ts","names":[],"sources":["../../../src/stream/projections/channel-effect.ts"],"mappings":";;;;;;;;;;UAkDiB,oBAAA,SAA6B,wBAAA;;EAE5C,OAAA,GAAU,KAAA,EAAO,KAAA;;;;;;EAMjB,OAAA,IAAW,KAAA;AAAA;;;;;;;;;;;;iBAcG,oBAAA,CACd,QAAA,EAAU,eAAA,EACV,QAAA,WAAmB,OAAA,IACnB,SAAA,qBACA,OAAA,EAAS,oBAAA"} |
| import { channelProjection } from "./channel.js"; | ||
| //#region src/stream/projections/channel-effect.ts | ||
| /** | ||
| * Acquire a side-effect subscription over one or more channels. | ||
| * | ||
| * @param registry - The stream's {@link ChannelRegistry}. | ||
| * @param channels - Channels to observe (e.g. `["lifecycle", "tools"]`). | ||
| * @param namespace - Resolved namespace (`[]` for the root). | ||
| * @param options - Callbacks plus projection (`bufferSize`/`replay`) | ||
| * options. | ||
| * @returns A `dispose()` function that detaches the listener and | ||
| * releases the ref-counted projection. Idempotent. | ||
| */ | ||
| function acquireChannelEffect(registry, channels, namespace, options) { | ||
| const { onEvent, onError, ...projectionOptions } = options; | ||
| const acquired = registry.acquire(channelProjection(channels, namespace, { | ||
| replay: projectionOptions.replay ?? false, | ||
| bufferSize: projectionOptions.bufferSize | ||
| })); | ||
| const { store } = acquired; | ||
| const initial = store.getSnapshot(); | ||
| let lastDelivered = initial.length > 0 ? initial[initial.length - 1] : void 0; | ||
| const deliver = () => { | ||
| const snapshot = store.getSnapshot(); | ||
| let start = 0; | ||
| if (lastDelivered !== void 0) { | ||
| const index = snapshot.lastIndexOf(lastDelivered); | ||
| start = index === -1 ? 0 : index + 1; | ||
| } | ||
| for (let i = start; i < snapshot.length; i += 1) { | ||
| const event = snapshot[i]; | ||
| try { | ||
| onEvent(event); | ||
| } catch (error) { | ||
| if (onError) onError(error); | ||
| } | ||
| } | ||
| if (snapshot.length > 0) lastDelivered = snapshot[snapshot.length - 1]; | ||
| }; | ||
| const unsubscribe = store.subscribe(deliver); | ||
| let released = false; | ||
| return () => { | ||
| if (released) return; | ||
| released = true; | ||
| unsubscribe(); | ||
| acquired.release(); | ||
| }; | ||
| } | ||
| //#endregion | ||
| export { acquireChannelEffect }; | ||
| //# sourceMappingURL=channel-effect.js.map |
| {"version":3,"file":"channel-effect.js","names":[],"sources":["../../../src/stream/projections/channel-effect.ts"],"sourcesContent":["/**\n * Side-effect counterpart to {@link channelProjection}.\n *\n * Where `channelProjection` retains a bounded *buffer* of raw events\n * for rendering, this helper delivers each event to a callback exactly\n * once — the idiomatic shape for analytics, logging, and other side\n * effects that should not live in render. Framework bindings wrap it as\n * `useChannelEffect` (React/Svelte/Vue) / `injectChannelEffect`\n * (Angular).\n *\n * # Why this is built on the registry\n *\n * It acquires the very same ref-counted {@link channelProjection} entry\n * that the selector hooks use, so:\n *\n * - N consumers of the same `channels`/`namespace`/options share a\n * single server subscription (the registry dedupes by `spec.key`).\n * - The subscription survives thread swaps for free (the registry\n * rebinds every live entry on `controller.hydrate(...)`).\n *\n * Each consumer then diffs the shared store independently, so multiple\n * `useChannelEffect` callers with *different* callbacks each receive\n * their own delivery.\n *\n * # Delivery semantics\n *\n * - Only events that arrive while the effect is attached are\n * delivered. Events already buffered when the effect attaches (e.g.\n * a sibling `useChannel` populated the buffer first) are skipped —\n * analytics must not double-count history on a late mount.\n * - `channelProjection` appends exactly one event per store\n * notification, so the cursor below tracks the last delivered event\n * by identity and forwards everything after it. On a thread rebind\n * the store resets to `[]`; the old cursor is no longer found, so\n * the next batch of events for the new thread is delivered from the\n * start.\n * - `replay` is forwarded to the projection. It defaults to `false`\n * here (live-only) — the opposite of `useChannel`'s buffer default —\n * because firing analytics for replayed history is rarely what a\n * side-effect consumer wants.\n */\nimport type { Channel, Event } from \"@langchain/protocol\";\nimport type { ChannelRegistry } from \"../channel-registry.js\";\nimport { channelProjection, type ChannelProjectionOptions } from \"./channel.js\";\n\n/**\n * Options for {@link acquireChannelEffect}. Extends\n * {@link ChannelProjectionOptions} (`bufferSize`, `replay`) with the\n * per-event callback and an optional error sink.\n */\nexport interface ChannelEffectOptions extends ChannelProjectionOptions {\n /** Invoked once for every event observed while attached. */\n onEvent: (event: Event) => void;\n /**\n * Invoked when {@link onEvent} throws. When omitted, a throwing\n * `onEvent` is swallowed so one bad delivery cannot wedge the shared\n * store's notification loop or other consumers.\n */\n onError?: (error: unknown) => void;\n}\n\n/**\n * Acquire a side-effect subscription over one or more channels.\n *\n * @param registry - The stream's {@link ChannelRegistry}.\n * @param channels - Channels to observe (e.g. `[\"lifecycle\", \"tools\"]`).\n * @param namespace - Resolved namespace (`[]` for the root).\n * @param options - Callbacks plus projection (`bufferSize`/`replay`)\n * options.\n * @returns A `dispose()` function that detaches the listener and\n * releases the ref-counted projection. Idempotent.\n */\nexport function acquireChannelEffect(\n registry: ChannelRegistry,\n channels: readonly Channel[],\n namespace: readonly string[],\n options: ChannelEffectOptions\n): () => void {\n const { onEvent, onError, ...projectionOptions } = options;\n const acquired = registry.acquire<Event[]>(\n channelProjection(channels, namespace, {\n // Live-only by default for side effects; callers opt into replay\n // explicitly when they want to re-process history.\n replay: projectionOptions.replay ?? false,\n bufferSize: projectionOptions.bufferSize,\n })\n );\n const { store } = acquired;\n\n // Cursor: the last event already delivered to `onEvent`. Seeded with\n // the current tail so events buffered before this consumer attached\n // are skipped (no double-counting on a late mount).\n const initial = store.getSnapshot();\n let lastDelivered: Event | undefined =\n initial.length > 0 ? initial[initial.length - 1] : undefined;\n\n const deliver = (): void => {\n const snapshot = store.getSnapshot();\n let start = 0;\n if (lastDelivered !== undefined) {\n const index = snapshot.lastIndexOf(lastDelivered);\n // `index === -1` means the cursor fell out of the buffer (thread\n // rebind reset the store, or the bounded buffer evicted it).\n // Deliver from the start of the current snapshot.\n start = index === -1 ? 0 : index + 1;\n }\n for (let i = start; i < snapshot.length; i += 1) {\n const event = snapshot[i] as Event;\n try {\n onEvent(event);\n } catch (error) {\n if (onError) onError(error);\n }\n }\n if (snapshot.length > 0) {\n lastDelivered = snapshot[snapshot.length - 1];\n }\n };\n\n const unsubscribe = store.subscribe(deliver);\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n unsubscribe();\n acquired.release();\n };\n}\n"],"mappings":";;;;;;;;;;;;;AAwEA,SAAgB,qBACd,UACA,UACA,WACA,SACY;CACZ,MAAM,EAAE,SAAS,SAAS,GAAG,sBAAsB;CACnD,MAAM,WAAW,SAAS,QACxB,kBAAkB,UAAU,WAAW;EAGrC,QAAQ,kBAAkB,UAAU;EACpC,YAAY,kBAAkB;EAC/B,CAAC,CACH;CACD,MAAM,EAAE,UAAU;CAKlB,MAAM,UAAU,MAAM,aAAa;CACnC,IAAI,gBACF,QAAQ,SAAS,IAAI,QAAQ,QAAQ,SAAS,KAAK,KAAA;CAErD,MAAM,gBAAsB;EAC1B,MAAM,WAAW,MAAM,aAAa;EACpC,IAAI,QAAQ;AACZ,MAAI,kBAAkB,KAAA,GAAW;GAC/B,MAAM,QAAQ,SAAS,YAAY,cAAc;AAIjD,WAAQ,UAAU,KAAK,IAAI,QAAQ;;AAErC,OAAK,IAAI,IAAI,OAAO,IAAI,SAAS,QAAQ,KAAK,GAAG;GAC/C,MAAM,QAAQ,SAAS;AACvB,OAAI;AACF,YAAQ,MAAM;YACP,OAAO;AACd,QAAI,QAAS,SAAQ,MAAM;;;AAG/B,MAAI,SAAS,SAAS,EACpB,iBAAgB,SAAS,SAAS,SAAS;;CAI/C,MAAM,cAAc,MAAM,UAAU,QAAQ;CAE5C,IAAI,WAAW;AACf,cAAa;AACX,MAAI,SAAU;AACd,aAAW;AACX,eAAa;AACb,WAAS,SAAS"} |
+1
-1
@@ -9,4 +9,4 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); | ||
| const require_index$1 = require("./client/stream/index.cjs"); | ||
| const require_websocket = require("./client/stream/transport/websocket.cjs"); | ||
| const require_http = require("./client/stream/transport/http.cjs"); | ||
| const require_websocket = require("./client/stream/transport/websocket.cjs"); | ||
| const require_index$2 = require("./client/threads/index.cjs"); | ||
@@ -13,0 +13,0 @@ const require_index$3 = require("./client/runs/index.cjs"); |
+1
-1
@@ -8,4 +8,4 @@ import { BaseClient, getApiKey } from "./client/base.js"; | ||
| import { SubscriptionHandle, ThreadStream } from "./client/stream/index.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "./client/stream/transport/websocket.js"; | ||
| import { ProtocolSseTransportAdapter } from "./client/stream/transport/http.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "./client/stream/transport/websocket.js"; | ||
| import { ThreadsClient } from "./client/threads/index.js"; | ||
@@ -12,0 +12,0 @@ import { RunsClient } from "./client/runs/index.js"; |
@@ -11,4 +11,4 @@ require("./base.cjs"); | ||
| require("./stream/index.cjs"); | ||
| require("./stream/transport/websocket.cjs"); | ||
| require("./stream/transport/http.cjs"); | ||
| require("./stream/transport/websocket.cjs"); | ||
| const require_index$2 = require("./threads/index.cjs"); | ||
@@ -15,0 +15,0 @@ const require_index$3 = require("./runs/index.cjs"); |
@@ -11,4 +11,4 @@ import "./base.js"; | ||
| import "./stream/index.js"; | ||
| import "./stream/transport/websocket.js"; | ||
| import "./stream/transport/http.js"; | ||
| import "./stream/transport/websocket.js"; | ||
| import { ThreadsClient } from "./threads/index.js"; | ||
@@ -15,0 +15,0 @@ import { RunsClient } from "./runs/index.js"; |
@@ -15,5 +15,26 @@ //#region src/client/stream/error.ts | ||
| }; | ||
| /** | ||
| * Thrown when the v2 WebSocket transport exhausts its automatic reconnect | ||
| * budget (`maxReconnectAttempts`) after an unexpected socket close or error. | ||
| * | ||
| * The transport closes its event queue with this error so consumers of | ||
| * `events()` can treat the stream as terminally failed. Set | ||
| * `maxReconnectAttempts` to `0` on `client.threads.stream({ transport: | ||
| * "websocket" })` to disable reconnect and fail fast on the first drop | ||
| * instead. | ||
| */ | ||
| var MaxWebSocketReconnectAttemptsError = class extends Error { | ||
| /** The configured `maxReconnectAttempts` value that was exceeded. */ | ||
| maxAttempts; | ||
| constructor(maxAttempts, cause) { | ||
| super(`Exceeded maximum WebSocket reconnection attempts (${maxAttempts})`); | ||
| this.name = "MaxWebSocketReconnectAttemptsError"; | ||
| this.maxAttempts = maxAttempts; | ||
| this.cause = cause; | ||
| } | ||
| }; | ||
| //#endregion | ||
| exports.MaxWebSocketReconnectAttemptsError = MaxWebSocketReconnectAttemptsError; | ||
| exports.ProtocolError = ProtocolError; | ||
| //# sourceMappingURL=error.cjs.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"error.cjs","names":[],"sources":["../../../src/client/stream/error.ts"],"sourcesContent":["import type { ErrorResponse } from \"@langchain/protocol\";\n\n/**\n * Error wrapper for protocol-level error responses returned by the server.\n */\nexport class ProtocolError extends Error {\n readonly code: ErrorResponse[\"error\"];\n readonly response: ErrorResponse;\n\n constructor(response: ErrorResponse) {\n super(response.message);\n this.name = \"ProtocolError\";\n this.code = response.error;\n this.response = response;\n }\n}\n"],"mappings":";;;;AAKA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,UAAyB;AACnC,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK,WAAW"} | ||
| {"version":3,"file":"error.cjs","names":[],"sources":["../../../src/client/stream/error.ts"],"sourcesContent":["import type { ErrorResponse } from \"@langchain/protocol\";\n\n/**\n * Error wrapper for protocol-level error responses returned by the server.\n */\nexport class ProtocolError extends Error {\n readonly code: ErrorResponse[\"error\"];\n readonly response: ErrorResponse;\n\n constructor(response: ErrorResponse) {\n super(response.message);\n this.name = \"ProtocolError\";\n this.code = response.error;\n this.response = response;\n }\n}\n\n/**\n * Thrown when the v2 WebSocket transport exhausts its automatic reconnect\n * budget (`maxReconnectAttempts`) after an unexpected socket close or error.\n *\n * The transport closes its event queue with this error so consumers of\n * `events()` can treat the stream as terminally failed. Set\n * `maxReconnectAttempts` to `0` on `client.threads.stream({ transport:\n * \"websocket\" })` to disable reconnect and fail fast on the first drop\n * instead.\n */\nexport class MaxWebSocketReconnectAttemptsError extends Error {\n /** The configured `maxReconnectAttempts` value that was exceeded. */\n readonly maxAttempts: number;\n\n constructor(maxAttempts: number, cause: unknown) {\n super(`Exceeded maximum WebSocket reconnection attempts (${maxAttempts})`);\n this.name = \"MaxWebSocketReconnectAttemptsError\";\n this.maxAttempts = maxAttempts;\n this.cause = cause;\n }\n}\n"],"mappings":";;;;AAKA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,UAAyB;AACnC,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK,WAAW;;;;;;;;;;;;;AAcpB,IAAa,qCAAb,cAAwD,MAAM;;CAE5D;CAEA,YAAY,aAAqB,OAAgB;AAC/C,QAAM,qDAAqD,YAAY,GAAG;AAC1E,OAAK,OAAO;AACZ,OAAK,cAAc;AACnB,OAAK,QAAQ"} |
@@ -15,5 +15,25 @@ //#region src/client/stream/error.ts | ||
| }; | ||
| /** | ||
| * Thrown when the v2 WebSocket transport exhausts its automatic reconnect | ||
| * budget (`maxReconnectAttempts`) after an unexpected socket close or error. | ||
| * | ||
| * The transport closes its event queue with this error so consumers of | ||
| * `events()` can treat the stream as terminally failed. Set | ||
| * `maxReconnectAttempts` to `0` on `client.threads.stream({ transport: | ||
| * "websocket" })` to disable reconnect and fail fast on the first drop | ||
| * instead. | ||
| */ | ||
| var MaxWebSocketReconnectAttemptsError = class extends Error { | ||
| /** The configured `maxReconnectAttempts` value that was exceeded. */ | ||
| maxAttempts; | ||
| constructor(maxAttempts, cause) { | ||
| super(`Exceeded maximum WebSocket reconnection attempts (${maxAttempts})`); | ||
| this.name = "MaxWebSocketReconnectAttemptsError"; | ||
| this.maxAttempts = maxAttempts; | ||
| this.cause = cause; | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { ProtocolError }; | ||
| export { MaxWebSocketReconnectAttemptsError, ProtocolError }; | ||
| //# sourceMappingURL=error.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"error.js","names":[],"sources":["../../../src/client/stream/error.ts"],"sourcesContent":["import type { ErrorResponse } from \"@langchain/protocol\";\n\n/**\n * Error wrapper for protocol-level error responses returned by the server.\n */\nexport class ProtocolError extends Error {\n readonly code: ErrorResponse[\"error\"];\n readonly response: ErrorResponse;\n\n constructor(response: ErrorResponse) {\n super(response.message);\n this.name = \"ProtocolError\";\n this.code = response.error;\n this.response = response;\n }\n}\n"],"mappings":";;;;AAKA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,UAAyB;AACnC,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK,WAAW"} | ||
| {"version":3,"file":"error.js","names":[],"sources":["../../../src/client/stream/error.ts"],"sourcesContent":["import type { ErrorResponse } from \"@langchain/protocol\";\n\n/**\n * Error wrapper for protocol-level error responses returned by the server.\n */\nexport class ProtocolError extends Error {\n readonly code: ErrorResponse[\"error\"];\n readonly response: ErrorResponse;\n\n constructor(response: ErrorResponse) {\n super(response.message);\n this.name = \"ProtocolError\";\n this.code = response.error;\n this.response = response;\n }\n}\n\n/**\n * Thrown when the v2 WebSocket transport exhausts its automatic reconnect\n * budget (`maxReconnectAttempts`) after an unexpected socket close or error.\n *\n * The transport closes its event queue with this error so consumers of\n * `events()` can treat the stream as terminally failed. Set\n * `maxReconnectAttempts` to `0` on `client.threads.stream({ transport:\n * \"websocket\" })` to disable reconnect and fail fast on the first drop\n * instead.\n */\nexport class MaxWebSocketReconnectAttemptsError extends Error {\n /** The configured `maxReconnectAttempts` value that was exceeded. */\n readonly maxAttempts: number;\n\n constructor(maxAttempts: number, cause: unknown) {\n super(`Exceeded maximum WebSocket reconnection attempts (${maxAttempts})`);\n this.name = \"MaxWebSocketReconnectAttemptsError\";\n this.maxAttempts = maxAttempts;\n this.cause = cause;\n }\n}\n"],"mappings":";;;;AAKA,IAAa,gBAAb,cAAmC,MAAM;CACvC;CACA;CAEA,YAAY,UAAyB;AACnC,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO,SAAS;AACrB,OAAK,WAAW;;;;;;;;;;;;;AAcpB,IAAa,qCAAb,cAAwD,MAAM;;CAE5D;CAEA,YAAY,aAAqB,OAAgB;AAC/C,QAAM,qDAAqD,YAAY,GAAG;AAC1E,OAAK,OAAO;AACZ,OAAK,cAAc;AACnB,OAAK,QAAQ"} |
@@ -439,3 +439,6 @@ const require_subscription = require("./subscription.cjs"); | ||
| }; | ||
| if (this.#transportAdapter.openEventStream == null) this.#consumeEvents(); | ||
| if (this.#transportAdapter.openEventStream == null) { | ||
| this.#transportAdapter.setOnReconnected?.(() => this.#resubscribeWebSocketSubscriptions()); | ||
| this.#consumeEvents(); | ||
| } | ||
| } | ||
@@ -1379,2 +1382,22 @@ /** | ||
| } | ||
| /** | ||
| * Re-issue `subscription.subscribe` for every active WS subscription | ||
| * after the transport reconnects. The server replays buffered events on | ||
| * the new socket; client-side `event_id` dedup suppresses duplicates. | ||
| */ | ||
| async #resubscribeWebSocketSubscriptions() { | ||
| if (this.#transportAdapter.openEventStream != null || this.#closed) return; | ||
| const entries = [...this.#subscriptions.entries()]; | ||
| await Promise.all(entries.map(async ([id, subscription]) => { | ||
| if (id.startsWith("pending:")) return; | ||
| try { | ||
| const nextId = (await this.#send("subscription.subscribe", subscription.filter)).subscription_id; | ||
| if (nextId === id) return; | ||
| this.#subscriptions.delete(id); | ||
| subscription.subscriptionId = nextId; | ||
| this.#subscriptions.set(nextId, subscription); | ||
| if (this.#lifecycleSubId === id) this.#lifecycleSubId = nextId; | ||
| } catch {} | ||
| })); | ||
| } | ||
| async #consumeEvents() { | ||
@@ -1381,0 +1404,0 @@ try { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.d.cts","names":[],"sources":["../../../src/client/stream/index.ts"],"mappings":";;;;;;;;;;;;;;;;;AAqXA;;;;cAAa,kBAAA,gBAAkC,KAAA,GAAQ,KAAA,WAAgB,MAAA,aAC1D,aAAA,CAAc,MAAA,GAAS,iBAAA,CAAkB,MAAA;EAKpD,cAAA;EAAA,SACS,MAAA,EAAQ,eAAA;EAAA,iBACA,KAAA;EAAA,iBACA,OAAA;EAAA,QACT,MAAA;EAAA,QACA,MAAA;EAAA,QACA,aAAA;EAAA,iBACS,aAAA;EAAA,iBACA,SAAA;EAEjB,WAAA,CACE,cAAA,UACA,MAAA,EAAQ,eAAA,EACR,aAAA,GAAgB,EAAA,aAAe,OAAA,QAC/B,SAAA,IAAa,KAAA,EAAO,MAAA,KAAW,MAAA;EAQjC,IAAA,CAAK,KAAA,EAAO,MAAA;EA2E4B;;;;;;EAxDxC,KAAA,CAAA;EA/C8B;;;;EA2D9B,MAAA,CAAA;EA1DW;;;;EAoEX,aAAA,CAAA,GAAiB,OAAA;EAAA,IAOb,QAAA,CAAA;EAIJ,KAAA,CAAA;EAeM,WAAA,CAAA,GAAe,OAAA;EAAA,CAQpB,MAAA,CAAO,aAAA,KAAkB,aAAA,CAAc,MAAA;AAAA;;;;;;;;;;;;;;;;;cAsC7B,YAAA,qBACS,MAAA,oBAA0B,MAAA;EAAA;WAErC,QAAA;EAAA,SACA,QAAA,EAAU,oBAAA;EAAA,SACV,GAAA,EAAK,aAAA;EAAA,SACL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"; | ||
| }; | ||
| if (this.#transportAdapter.openEventStream == null) this.#consumeEvents(); | ||
| if (this.#transportAdapter.openEventStream == null) { | ||
| this.#transportAdapter.setOnReconnected?.(() => this.#resubscribeWebSocketSubscriptions()); | ||
| this.#consumeEvents(); | ||
| } | ||
| } | ||
@@ -1379,2 +1382,22 @@ /** | ||
| } | ||
| /** | ||
| * Re-issue `subscription.subscribe` for every active WS subscription | ||
| * after the transport reconnects. The server replays buffered events on | ||
| * the new socket; client-side `event_id` dedup suppresses duplicates. | ||
| */ | ||
| async #resubscribeWebSocketSubscriptions() { | ||
| if (this.#transportAdapter.openEventStream != null || this.#closed) return; | ||
| const entries = [...this.#subscriptions.entries()]; | ||
| await Promise.all(entries.map(async ([id, subscription]) => { | ||
| if (id.startsWith("pending:")) return; | ||
| try { | ||
| const nextId = (await this.#send("subscription.subscribe", subscription.filter)).subscription_id; | ||
| if (nextId === id) return; | ||
| this.#subscriptions.delete(id); | ||
| subscription.subscriptionId = nextId; | ||
| this.#subscriptions.set(nextId, subscription); | ||
| if (this.#lifecycleSubId === id) this.#lifecycleSubId = nextId; | ||
| } catch {} | ||
| })); | ||
| } | ||
| async #consumeEvents() { | ||
@@ -1381,0 +1404,0 @@ try { |
@@ -0,3 +1,3 @@ | ||
| const require_websocket = require("./websocket.cjs"); | ||
| const require_http = require("./http.cjs"); | ||
| const require_websocket = require("./websocket.cjs"); | ||
| //#region src/client/stream/transport/agent-server.ts | ||
@@ -29,2 +29,3 @@ var HttpAgentServerAdapter = class { | ||
| fetch: options.fetch, | ||
| asyncCaller: options.asyncCaller, | ||
| paths: options.paths | ||
@@ -31,0 +32,0 @@ }); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"agent-server.cjs","names":["#delegate","ProtocolWebSocketTransportAdapter","ProtocolSseTransportAdapter"],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"sourcesContent":["/**\n * Stock `AgentServerAdapter` implementation for \"point `useStream` at a\n * single HTTP endpoint that speaks the v2 protocol\" deployments.\n *\n * Internally delegates to the appropriate built-in transport:\n * - `new HttpAgentServerAdapter({ apiUrl, threadId })` → SSE\n * - `new HttpAgentServerAdapter({ apiUrl, threadId, webSocketFactory })`\n * → WebSocket\n *\n * Keeps the user-facing import surface small: callers only ever import\n * `HttpAgentServerAdapter` from `@langchain/langgraph-sdk` instead of\n * knowing the two wire-specific class names. The class is deliberately\n * thin — it forwards every method on {@link AgentServerAdapter} to the\n * delegate it picked at construction time.\n *\n * See `plan-custom-transport.md` §4.3 for motivation.\n */\nimport type {\n AgentServerAdapter,\n EventStreamHandle,\n TransportAdapter,\n} from \"../transport.js\";\nimport type {\n Command,\n CommandResponse,\n ErrorResponse,\n Message,\n SubscribeParams,\n} from \"@langchain/protocol\";\nimport { ProtocolSseTransportAdapter } from \"./http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"./websocket.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolTransportPaths,\n} from \"./types.js\";\n\nexport interface HttpAgentServerAdapterOptions {\n apiUrl: string;\n threadId: string;\n /** Auth / tenant / diagnostic headers applied to every request. */\n defaultHeaders?: Record<string, HeaderValue>;\n /** Per-request hook for last-mile header mutation. */\n onRequest?: ProtocolRequestHook;\n /** Override the default `/threads/:threadId/...` protocol paths. */\n paths?: ProtocolTransportPaths;\n /**\n * Optional `fetch` override, forwarded to the SSE transport. Useful\n * for auth proxies, Next.js route handlers, or tests with injected\n * mocks. Ignored when `webSocketFactory` is also supplied.\n */\n fetch?: typeof fetch;\n /**\n * Optional WebSocket factory. Supplying it flips the adapter into\n * WebSocket mode — SSE is bypassed entirely.\n */\n webSocketFactory?: (url: string) => WebSocket;\n}\n\nexport class HttpAgentServerAdapter implements AgentServerAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n readonly #delegate: TransportAdapter;\n\n /**\n * Thread-state reads are SSE-only. WebSocket delegates omit this so\n * {@link StreamController} falls back to `client.threads.getState()`.\n */\n getState?: AgentServerAdapter[\"getState\"];\n\n constructor(options: HttpAgentServerAdapterOptions) {\n this.threadId = options.threadId;\n this.apiUrl = options.apiUrl;\n this.#delegate =\n options.webSocketFactory != null\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n paths: options.paths,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n fetch: options.fetch,\n paths: options.paths,\n });\n\n if (options.webSocketFactory == null) {\n const sse = this.#delegate as ProtocolSseTransportAdapter;\n this.getState = sse.getState.bind(sse);\n }\n }\n\n open(): Promise<void> {\n return this.#delegate.open();\n }\n\n send(command: Command): Promise<CommandResponse | ErrorResponse | void> {\n return this.#delegate.send(command);\n }\n\n events(): AsyncIterable<Message> {\n return this.#delegate.events();\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.#delegate.openEventStream == null) {\n throw new Error(\n \"HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path).\"\n );\n }\n return this.#delegate.openEventStream(params);\n }\n\n close(): Promise<void> {\n return this.#delegate.close();\n }\n}\n"],"mappings":";;;AA2DA,IAAa,yBAAb,MAAkE;CAChE;CAEA;CAEA;;;;;CAMA;CAEA,YAAY,SAAwC;AAClD,OAAK,WAAW,QAAQ;AACxB,OAAK,SAAS,QAAQ;AACtB,QAAA,WACE,QAAQ,oBAAoB,OACxB,IAAIC,kBAAAA,kCAAkC;GACpC,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAIC,aAAAA,4BAA4B;GAC9B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,OAAO,QAAQ;GAChB,CAAC;AAER,MAAI,QAAQ,oBAAoB,MAAM;GACpC,MAAM,MAAM,MAAA;AACZ,QAAK,WAAW,IAAI,SAAS,KAAK,IAAI;;;CAI1C,OAAsB;AACpB,SAAO,MAAA,SAAe,MAAM;;CAG9B,KAAK,SAAmE;AACtE,SAAO,MAAA,SAAe,KAAK,QAAQ;;CAGrC,SAAiC;AAC/B,SAAO,MAAA,SAAe,QAAQ;;CAGhC,gBAAgB,QAA4C;AAC1D,MAAI,MAAA,SAAe,mBAAmB,KACpC,OAAM,IAAI,MACR,qFACD;AAEH,SAAO,MAAA,SAAe,gBAAgB,OAAO;;CAG/C,QAAuB;AACrB,SAAO,MAAA,SAAe,OAAO"} | ||
| {"version":3,"file":"agent-server.cjs","names":["#delegate","ProtocolWebSocketTransportAdapter","ProtocolSseTransportAdapter"],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"sourcesContent":["/**\n * Stock `AgentServerAdapter` implementation for \"point `useStream` at a\n * single HTTP endpoint that speaks the v2 protocol\" deployments.\n *\n * Internally delegates to the appropriate built-in transport:\n * - `new HttpAgentServerAdapter({ apiUrl, threadId })` → SSE\n * - `new HttpAgentServerAdapter({ apiUrl, threadId, webSocketFactory })`\n * → WebSocket\n *\n * Keeps the user-facing import surface small: callers only ever import\n * `HttpAgentServerAdapter` from `@langchain/langgraph-sdk` instead of\n * knowing the two wire-specific class names. The class is deliberately\n * thin — it forwards every method on {@link AgentServerAdapter} to the\n * delegate it picked at construction time.\n *\n * See `plan-custom-transport.md` §4.3 for motivation.\n */\nimport type {\n AgentServerAdapter,\n EventStreamHandle,\n TransportAdapter,\n} from \"../transport.js\";\nimport type {\n Command,\n CommandResponse,\n ErrorResponse,\n Message,\n SubscribeParams,\n} from \"@langchain/protocol\";\nimport type { AsyncCaller } from \"../../../utils/async_caller.js\";\nimport { ProtocolSseTransportAdapter } from \"./http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"./websocket.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolTransportPaths,\n} from \"./types.js\";\n\nexport interface HttpAgentServerAdapterOptions {\n apiUrl: string;\n threadId: string;\n /** Auth / tenant / diagnostic headers applied to every request. */\n defaultHeaders?: Record<string, HeaderValue>;\n /** Per-request hook for last-mile header mutation. */\n onRequest?: ProtocolRequestHook;\n /** Override the default `/threads/:threadId/...` protocol paths. */\n paths?: ProtocolTransportPaths;\n /**\n * Optional `fetch` override, forwarded to the SSE transport. Useful\n * for auth proxies, Next.js route handlers, or tests with injected\n * mocks. Ignored when `webSocketFactory` is also supplied.\n */\n fetch?: typeof fetch;\n /**\n * Retries and concurrency for SSE/command HTTP. When omitted, requests\n * use raw `fetch` with no automatic retries (same as constructing\n * {@link ProtocolSseTransportAdapter} without this option).\n */\n asyncCaller?: AsyncCaller;\n /**\n * Optional WebSocket factory. Supplying it flips the adapter into\n * WebSocket mode — SSE is bypassed entirely.\n */\n webSocketFactory?: (url: string) => WebSocket;\n}\n\nexport class HttpAgentServerAdapter implements AgentServerAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n readonly #delegate: TransportAdapter;\n\n /**\n * Thread-state reads are SSE-only. WebSocket delegates omit this so\n * {@link StreamController} falls back to `client.threads.getState()`.\n */\n getState?: AgentServerAdapter[\"getState\"];\n\n constructor(options: HttpAgentServerAdapterOptions) {\n this.threadId = options.threadId;\n this.apiUrl = options.apiUrl;\n this.#delegate =\n options.webSocketFactory != null\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n paths: options.paths,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n fetch: options.fetch,\n asyncCaller: options.asyncCaller,\n paths: options.paths,\n });\n\n if (options.webSocketFactory == null) {\n const sse = this.#delegate as ProtocolSseTransportAdapter;\n this.getState = sse.getState.bind(sse);\n }\n }\n\n open(): Promise<void> {\n return this.#delegate.open();\n }\n\n send(command: Command): Promise<CommandResponse | ErrorResponse | void> {\n return this.#delegate.send(command);\n }\n\n events(): AsyncIterable<Message> {\n return this.#delegate.events();\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.#delegate.openEventStream == null) {\n throw new Error(\n \"HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path).\"\n );\n }\n return this.#delegate.openEventStream(params);\n }\n\n close(): Promise<void> {\n return this.#delegate.close();\n }\n}\n"],"mappings":";;;AAkEA,IAAa,yBAAb,MAAkE;CAChE;CAEA;CAEA;;;;;CAMA;CAEA,YAAY,SAAwC;AAClD,OAAK,WAAW,QAAQ;AACxB,OAAK,SAAS,QAAQ;AACtB,QAAA,WACE,QAAQ,oBAAoB,OACxB,IAAIC,kBAAAA,kCAAkC;GACpC,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAIC,aAAAA,4BAA4B;GAC9B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,aAAa,QAAQ;GACrB,OAAO,QAAQ;GAChB,CAAC;AAER,MAAI,QAAQ,oBAAoB,MAAM;GACpC,MAAM,MAAM,MAAA;AACZ,QAAK,WAAW,IAAI,SAAS,KAAK,IAAI;;;CAI1C,OAAsB;AACpB,SAAO,MAAA,SAAe,MAAM;;CAG9B,KAAK,SAAmE;AACtE,SAAO,MAAA,SAAe,KAAK,QAAQ;;CAGrC,SAAiC;AAC/B,SAAO,MAAA,SAAe,QAAQ;;CAGhC,gBAAgB,QAA4C;AAC1D,MAAI,MAAA,SAAe,mBAAmB,KACpC,OAAM,IAAI,MACR,qFACD;AAEH,SAAO,MAAA,SAAe,gBAAgB,OAAO;;CAG/C,QAAuB;AACrB,SAAO,MAAA,SAAe,OAAO"} |
@@ -0,1 +1,2 @@ | ||
| import { AsyncCaller } from "../../../utils/async_caller.cjs"; | ||
| import { AgentServerAdapter, EventStreamHandle } from "../transport.cjs"; | ||
@@ -22,2 +23,8 @@ import { HeaderValue, ProtocolRequestHook, ProtocolTransportPaths } from "./types.cjs"; | ||
| /** | ||
| * Retries and concurrency for SSE/command HTTP. When omitted, requests | ||
| * use raw `fetch` with no automatic retries (same as constructing | ||
| * {@link ProtocolSseTransportAdapter} without this option). | ||
| */ | ||
| asyncCaller?: AsyncCaller; | ||
| /** | ||
| * Optional WebSocket factory. Supplying it flips the adapter into | ||
@@ -24,0 +31,0 @@ * WebSocket mode — SSE is bypassed entirely. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"agent-server.d.cts","names":[],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"mappings":";;;;;UAqCiB,6BAAA;EACf,MAAA;EACA,QAAA;EAMA;EAJA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAUhC;EARA,SAAA,GAAY,mBAAA;EAaZ;EAXA,KAAA,GAAQ,sBAAA;EAW4B;;;AAGtC;;EARE,KAAA,UAAe,KAAA;EAmBJ;;;;EAdX,gBAAA,IAAoB,GAAA,aAAgB,SAAA;AAAA;AAAA,cAGzB,sBAAA,YAAkC,kBAAA;EAAA;WACpC,QAAA;EAAA,SAEA,MAAA;EAkDiC;;;;EA1C1C,QAAA,GAAW,kBAAA;EAEX,WAAA,CAAY,OAAA,EAAS,6BAAA;EA4BrB,IAAA,CAAA,GAAQ,OAAA;EAIR,IAAA,CAAK,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAIlD,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAIxB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,iBAAA;EAS1C,KAAA,CAAA,GAAS,OAAA;AAAA"} | ||
| {"version":3,"file":"agent-server.d.cts","names":[],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"mappings":";;;;;;UAsCiB,6BAAA;EACf,MAAA;EACA,QAAA;EAIY;EAFZ,cAAA,GAAiB,MAAA,SAAe,WAAA;EAIxB;EAFR,SAAA,GAAY,mBAAA;EAQG;EANf,KAAA,GAAQ,sBAAA;EAYM;;;;;EANd,KAAA,UAAe,KAAA;EAcJ;;;;;EARX,WAAA,GAAc,WAAA;EAsDA;;;;EAjDd,gBAAA,IAAoB,GAAA,aAAgB,SAAA;AAAA;AAAA,cAGzB,sBAAA,YAAkC,kBAAA;EAAA;WACpC,QAAA;EAAA,SAEA,MAAA;EAHsD;;;;EAW/D,QAAA,GAAW,kBAAA;EAEX,WAAA,CAAY,OAAA,EAAS,6BAAA;EA6BrB,IAAA,CAAA,GAAQ,OAAA;EAIR,IAAA,CAAK,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAIlD,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAIxB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,iBAAA;EAS1C,KAAA,CAAA,GAAS,OAAA;AAAA"} |
@@ -0,1 +1,2 @@ | ||
| import { AsyncCaller } from "../../../utils/async_caller.js"; | ||
| import { AgentServerAdapter, EventStreamHandle } from "../transport.js"; | ||
@@ -22,2 +23,8 @@ import { HeaderValue, ProtocolRequestHook, ProtocolTransportPaths } from "./types.js"; | ||
| /** | ||
| * Retries and concurrency for SSE/command HTTP. When omitted, requests | ||
| * use raw `fetch` with no automatic retries (same as constructing | ||
| * {@link ProtocolSseTransportAdapter} without this option). | ||
| */ | ||
| asyncCaller?: AsyncCaller; | ||
| /** | ||
| * Optional WebSocket factory. Supplying it flips the adapter into | ||
@@ -24,0 +31,0 @@ * WebSocket mode — SSE is bypassed entirely. |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"agent-server.d.ts","names":[],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"mappings":";;;;;UAqCiB,6BAAA;EACf,MAAA;EACA,QAAA;EAMA;EAJA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAUhC;EARA,SAAA,GAAY,mBAAA;EAaZ;EAXA,KAAA,GAAQ,sBAAA;EAW4B;;;AAGtC;;EARE,KAAA,UAAe,KAAA;EAmBJ;;;;EAdX,gBAAA,IAAoB,GAAA,aAAgB,SAAA;AAAA;AAAA,cAGzB,sBAAA,YAAkC,kBAAA;EAAA;WACpC,QAAA;EAAA,SAEA,MAAA;EAkDiC;;;;EA1C1C,QAAA,GAAW,kBAAA;EAEX,WAAA,CAAY,OAAA,EAAS,6BAAA;EA4BrB,IAAA,CAAA,GAAQ,OAAA;EAIR,IAAA,CAAK,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAIlD,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAIxB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,iBAAA;EAS1C,KAAA,CAAA,GAAS,OAAA;AAAA"} | ||
| {"version":3,"file":"agent-server.d.ts","names":[],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"mappings":";;;;;;UAsCiB,6BAAA;EACf,MAAA;EACA,QAAA;EAIY;EAFZ,cAAA,GAAiB,MAAA,SAAe,WAAA;EAIxB;EAFR,SAAA,GAAY,mBAAA;EAQG;EANf,KAAA,GAAQ,sBAAA;EAYM;;;;;EANd,KAAA,UAAe,KAAA;EAcJ;;;;;EARX,WAAA,GAAc,WAAA;EAsDA;;;;EAjDd,gBAAA,IAAoB,GAAA,aAAgB,SAAA;AAAA;AAAA,cAGzB,sBAAA,YAAkC,kBAAA;EAAA;WACpC,QAAA;EAAA,SAEA,MAAA;EAHsD;;;;EAW/D,QAAA,GAAW,kBAAA;EAEX,WAAA,CAAY,OAAA,EAAS,6BAAA;EA6BrB,IAAA,CAAA,GAAQ,OAAA;EAIR,IAAA,CAAK,OAAA,EAAS,OAAA,GAAU,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAIlD,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAIxB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,iBAAA;EAS1C,KAAA,CAAA,GAAS,OAAA;AAAA"} |
@@ -0,3 +1,3 @@ | ||
| import { ProtocolWebSocketTransportAdapter } from "./websocket.js"; | ||
| import { ProtocolSseTransportAdapter } from "./http.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "./websocket.js"; | ||
| //#region src/client/stream/transport/agent-server.ts | ||
@@ -29,2 +29,3 @@ var HttpAgentServerAdapter = class { | ||
| fetch: options.fetch, | ||
| asyncCaller: options.asyncCaller, | ||
| paths: options.paths | ||
@@ -31,0 +32,0 @@ }); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"agent-server.js","names":["#delegate"],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"sourcesContent":["/**\n * Stock `AgentServerAdapter` implementation for \"point `useStream` at a\n * single HTTP endpoint that speaks the v2 protocol\" deployments.\n *\n * Internally delegates to the appropriate built-in transport:\n * - `new HttpAgentServerAdapter({ apiUrl, threadId })` → SSE\n * - `new HttpAgentServerAdapter({ apiUrl, threadId, webSocketFactory })`\n * → WebSocket\n *\n * Keeps the user-facing import surface small: callers only ever import\n * `HttpAgentServerAdapter` from `@langchain/langgraph-sdk` instead of\n * knowing the two wire-specific class names. The class is deliberately\n * thin — it forwards every method on {@link AgentServerAdapter} to the\n * delegate it picked at construction time.\n *\n * See `plan-custom-transport.md` §4.3 for motivation.\n */\nimport type {\n AgentServerAdapter,\n EventStreamHandle,\n TransportAdapter,\n} from \"../transport.js\";\nimport type {\n Command,\n CommandResponse,\n ErrorResponse,\n Message,\n SubscribeParams,\n} from \"@langchain/protocol\";\nimport { ProtocolSseTransportAdapter } from \"./http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"./websocket.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolTransportPaths,\n} from \"./types.js\";\n\nexport interface HttpAgentServerAdapterOptions {\n apiUrl: string;\n threadId: string;\n /** Auth / tenant / diagnostic headers applied to every request. */\n defaultHeaders?: Record<string, HeaderValue>;\n /** Per-request hook for last-mile header mutation. */\n onRequest?: ProtocolRequestHook;\n /** Override the default `/threads/:threadId/...` protocol paths. */\n paths?: ProtocolTransportPaths;\n /**\n * Optional `fetch` override, forwarded to the SSE transport. Useful\n * for auth proxies, Next.js route handlers, or tests with injected\n * mocks. Ignored when `webSocketFactory` is also supplied.\n */\n fetch?: typeof fetch;\n /**\n * Optional WebSocket factory. Supplying it flips the adapter into\n * WebSocket mode — SSE is bypassed entirely.\n */\n webSocketFactory?: (url: string) => WebSocket;\n}\n\nexport class HttpAgentServerAdapter implements AgentServerAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n readonly #delegate: TransportAdapter;\n\n /**\n * Thread-state reads are SSE-only. WebSocket delegates omit this so\n * {@link StreamController} falls back to `client.threads.getState()`.\n */\n getState?: AgentServerAdapter[\"getState\"];\n\n constructor(options: HttpAgentServerAdapterOptions) {\n this.threadId = options.threadId;\n this.apiUrl = options.apiUrl;\n this.#delegate =\n options.webSocketFactory != null\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n paths: options.paths,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n fetch: options.fetch,\n paths: options.paths,\n });\n\n if (options.webSocketFactory == null) {\n const sse = this.#delegate as ProtocolSseTransportAdapter;\n this.getState = sse.getState.bind(sse);\n }\n }\n\n open(): Promise<void> {\n return this.#delegate.open();\n }\n\n send(command: Command): Promise<CommandResponse | ErrorResponse | void> {\n return this.#delegate.send(command);\n }\n\n events(): AsyncIterable<Message> {\n return this.#delegate.events();\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.#delegate.openEventStream == null) {\n throw new Error(\n \"HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path).\"\n );\n }\n return this.#delegate.openEventStream(params);\n }\n\n close(): Promise<void> {\n return this.#delegate.close();\n }\n}\n"],"mappings":";;;AA2DA,IAAa,yBAAb,MAAkE;CAChE;CAEA;CAEA;;;;;CAMA;CAEA,YAAY,SAAwC;AAClD,OAAK,WAAW,QAAQ;AACxB,OAAK,SAAS,QAAQ;AACtB,QAAA,WACE,QAAQ,oBAAoB,OACxB,IAAI,kCAAkC;GACpC,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAI,4BAA4B;GAC9B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,OAAO,QAAQ;GAChB,CAAC;AAER,MAAI,QAAQ,oBAAoB,MAAM;GACpC,MAAM,MAAM,MAAA;AACZ,QAAK,WAAW,IAAI,SAAS,KAAK,IAAI;;;CAI1C,OAAsB;AACpB,SAAO,MAAA,SAAe,MAAM;;CAG9B,KAAK,SAAmE;AACtE,SAAO,MAAA,SAAe,KAAK,QAAQ;;CAGrC,SAAiC;AAC/B,SAAO,MAAA,SAAe,QAAQ;;CAGhC,gBAAgB,QAA4C;AAC1D,MAAI,MAAA,SAAe,mBAAmB,KACpC,OAAM,IAAI,MACR,qFACD;AAEH,SAAO,MAAA,SAAe,gBAAgB,OAAO;;CAG/C,QAAuB;AACrB,SAAO,MAAA,SAAe,OAAO"} | ||
| {"version":3,"file":"agent-server.js","names":["#delegate"],"sources":["../../../../src/client/stream/transport/agent-server.ts"],"sourcesContent":["/**\n * Stock `AgentServerAdapter` implementation for \"point `useStream` at a\n * single HTTP endpoint that speaks the v2 protocol\" deployments.\n *\n * Internally delegates to the appropriate built-in transport:\n * - `new HttpAgentServerAdapter({ apiUrl, threadId })` → SSE\n * - `new HttpAgentServerAdapter({ apiUrl, threadId, webSocketFactory })`\n * → WebSocket\n *\n * Keeps the user-facing import surface small: callers only ever import\n * `HttpAgentServerAdapter` from `@langchain/langgraph-sdk` instead of\n * knowing the two wire-specific class names. The class is deliberately\n * thin — it forwards every method on {@link AgentServerAdapter} to the\n * delegate it picked at construction time.\n *\n * See `plan-custom-transport.md` §4.3 for motivation.\n */\nimport type {\n AgentServerAdapter,\n EventStreamHandle,\n TransportAdapter,\n} from \"../transport.js\";\nimport type {\n Command,\n CommandResponse,\n ErrorResponse,\n Message,\n SubscribeParams,\n} from \"@langchain/protocol\";\nimport type { AsyncCaller } from \"../../../utils/async_caller.js\";\nimport { ProtocolSseTransportAdapter } from \"./http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"./websocket.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolTransportPaths,\n} from \"./types.js\";\n\nexport interface HttpAgentServerAdapterOptions {\n apiUrl: string;\n threadId: string;\n /** Auth / tenant / diagnostic headers applied to every request. */\n defaultHeaders?: Record<string, HeaderValue>;\n /** Per-request hook for last-mile header mutation. */\n onRequest?: ProtocolRequestHook;\n /** Override the default `/threads/:threadId/...` protocol paths. */\n paths?: ProtocolTransportPaths;\n /**\n * Optional `fetch` override, forwarded to the SSE transport. Useful\n * for auth proxies, Next.js route handlers, or tests with injected\n * mocks. Ignored when `webSocketFactory` is also supplied.\n */\n fetch?: typeof fetch;\n /**\n * Retries and concurrency for SSE/command HTTP. When omitted, requests\n * use raw `fetch` with no automatic retries (same as constructing\n * {@link ProtocolSseTransportAdapter} without this option).\n */\n asyncCaller?: AsyncCaller;\n /**\n * Optional WebSocket factory. Supplying it flips the adapter into\n * WebSocket mode — SSE is bypassed entirely.\n */\n webSocketFactory?: (url: string) => WebSocket;\n}\n\nexport class HttpAgentServerAdapter implements AgentServerAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n readonly #delegate: TransportAdapter;\n\n /**\n * Thread-state reads are SSE-only. WebSocket delegates omit this so\n * {@link StreamController} falls back to `client.threads.getState()`.\n */\n getState?: AgentServerAdapter[\"getState\"];\n\n constructor(options: HttpAgentServerAdapterOptions) {\n this.threadId = options.threadId;\n this.apiUrl = options.apiUrl;\n this.#delegate =\n options.webSocketFactory != null\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n paths: options.paths,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: options.apiUrl,\n threadId: options.threadId,\n defaultHeaders: options.defaultHeaders,\n onRequest: options.onRequest,\n fetch: options.fetch,\n asyncCaller: options.asyncCaller,\n paths: options.paths,\n });\n\n if (options.webSocketFactory == null) {\n const sse = this.#delegate as ProtocolSseTransportAdapter;\n this.getState = sse.getState.bind(sse);\n }\n }\n\n open(): Promise<void> {\n return this.#delegate.open();\n }\n\n send(command: Command): Promise<CommandResponse | ErrorResponse | void> {\n return this.#delegate.send(command);\n }\n\n events(): AsyncIterable<Message> {\n return this.#delegate.events();\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.#delegate.openEventStream == null) {\n throw new Error(\n \"HttpAgentServerAdapter delegate does not support openEventStream (WebSocket path).\"\n );\n }\n return this.#delegate.openEventStream(params);\n }\n\n close(): Promise<void> {\n return this.#delegate.close();\n }\n}\n"],"mappings":";;;AAkEA,IAAa,yBAAb,MAAkE;CAChE;CAEA;CAEA;;;;;CAMA;CAEA,YAAY,SAAwC;AAClD,OAAK,WAAW,QAAQ;AACxB,OAAK,SAAS,QAAQ;AACtB,QAAA,WACE,QAAQ,oBAAoB,OACxB,IAAI,kCAAkC;GACpC,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAI,4BAA4B;GAC9B,QAAQ,QAAQ;GAChB,UAAU,QAAQ;GAClB,gBAAgB,QAAQ;GACxB,WAAW,QAAQ;GACnB,OAAO,QAAQ;GACf,aAAa,QAAQ;GACrB,OAAO,QAAQ;GAChB,CAAC;AAER,MAAI,QAAQ,oBAAoB,MAAM;GACpC,MAAM,MAAM,MAAA;AACZ,QAAK,WAAW,IAAI,SAAS,KAAK,IAAI;;;CAI1C,OAAsB;AACpB,SAAO,MAAA,SAAe,MAAM;;CAG9B,KAAK,SAAmE;AACtE,SAAO,MAAA,SAAe,KAAK,QAAQ;;CAGrC,SAAiC;AAC/B,SAAO,MAAA,SAAe,QAAQ;;CAGhC,gBAAgB,QAA4C;AAC1D,MAAI,MAAA,SAAe,mBAAmB,KACpC,OAAM,IAAI,MACR,qFACD;AAEH,SAAO,MAAA,SAAe,gBAAgB,OAAO;;CAG/C,QAAuB;AACrB,SAAO,MAAA,SAAe,OAAO"} |
@@ -5,2 +5,3 @@ const require_sse = require("../../../utils/sse.cjs"); | ||
| const require_utils = require("./utils.cjs"); | ||
| const require_websocket = require("./websocket.cjs"); | ||
| //#region src/client/stream/transport/http.ts | ||
@@ -21,2 +22,6 @@ /** | ||
| fetchFactory; | ||
| asyncCaller; | ||
| maxReconnectAttempts; | ||
| onReconnect; | ||
| reconnectDelayMs; | ||
| commandsUrl; | ||
@@ -34,2 +39,6 @@ streamUrl; | ||
| this.fetchFactory = options.fetchFactory; | ||
| this.asyncCaller = options.asyncCaller; | ||
| this.maxReconnectAttempts = options.fetch != null ? 0 : options.maxReconnectAttempts ?? 5; | ||
| this.onReconnect = options.onReconnect; | ||
| this.reconnectDelayMs = options.reconnectDelayMs ?? require_websocket.webSocketReconnectDelayMs; | ||
| this.threadId = options.threadId; | ||
@@ -114,5 +123,7 @@ this.commandsUrl = options.paths?.commands ?? `/threads/${this.threadId}/commands`; | ||
| }); | ||
| const since = params.since; | ||
| let resumeAfterSeq = typeof params.since === "number" ? params.since : void 0; | ||
| let readySettled = false; | ||
| const startStream = async () => { | ||
| try { | ||
| let attempt = 0; | ||
| while (!ac.signal.aborted && !this.closed) try { | ||
| const response = await this.request(streamUrl, { | ||
@@ -128,7 +139,10 @@ method: "POST", | ||
| ...params.depth != null ? { depth: params.depth } : {}, | ||
| ...typeof since === "number" ? { since } : {} | ||
| ...resumeAfterSeq != null ? { since: resumeAfterSeq } : {} | ||
| }), | ||
| signal: ac.signal | ||
| }); | ||
| resolveReady(); | ||
| }, { stream: true }); | ||
| if (!readySettled) { | ||
| readySettled = true; | ||
| resolveReady(); | ||
| } | ||
| const stream = (response.body ?? new ReadableStream({ start(controller) { | ||
@@ -142,2 +156,3 @@ controller.close(); | ||
| const msg = event.data; | ||
| if (typeof msg.seq === "number") resumeAfterSeq = msg.seq; | ||
| streamQueue.push(msg); | ||
@@ -147,9 +162,28 @@ } | ||
| streamQueue.close(); | ||
| return; | ||
| } catch (error) { | ||
| rejectReady(error); | ||
| if (ac.signal.aborted || this.closed) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(); | ||
| return; | ||
| } | ||
| streamQueue.close(error); | ||
| if (this.maxReconnectAttempts <= 0) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(require_utils.toError(error)); | ||
| return; | ||
| } | ||
| attempt += 1; | ||
| if (attempt > this.maxReconnectAttempts) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(require_utils.toError(error)); | ||
| return; | ||
| } | ||
| this.onReconnect?.({ | ||
| attempt, | ||
| cause: error | ||
| }); | ||
| const delay = this.reconnectDelayMs(attempt); | ||
| if (delay > 0) await new Promise((resolve) => { | ||
| setTimeout(resolve, delay); | ||
| }); | ||
| } | ||
@@ -186,3 +220,3 @@ }; | ||
| } | ||
| async request(path, init) { | ||
| async request(path, init, options) { | ||
| const url = require_utils.toAbsoluteUrl(this.apiUrl, path); | ||
@@ -194,5 +228,7 @@ let requestInit = { | ||
| if (this.onRequest) requestInit = await this.onRequest(url, requestInit); | ||
| try { | ||
| const useAsyncCaller = this.asyncCaller != null && !options?.stream; | ||
| const execute = async () => { | ||
| const response = await (await this.resolveFetch())(url.toString(), requestInit); | ||
| if (!response.ok) { | ||
| if (useAsyncCaller) throw response; | ||
| let detail = ""; | ||
@@ -209,2 +245,5 @@ try { | ||
| return response; | ||
| }; | ||
| try { | ||
| return useAsyncCaller ? await this.asyncCaller.call(execute) : await execute(); | ||
| } catch (error) { | ||
@@ -211,0 +250,0 @@ throw require_utils.toError(error); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"http.cjs","names":["AsyncQueue","toAbsoluteUrl","mergeHeaders","toError","isProtocolResponse","BytesLineDecoder","SSEDecoder","IterableReadableStream","isRecord"],"sources":["../../../../src/client/stream/transport/http.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n SubscribeParams,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolSseTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter, EventStreamHandle } from \"../transport.js\";\nimport {\n toAbsoluteUrl,\n isRecord,\n mergeHeaders,\n toError,\n isProtocolResponse,\n} from \"./utils.js\";\nimport { BytesLineDecoder, SSEDecoder } from \"../../../utils/sse.js\";\nimport { IterableReadableStream } from \"../../../utils/stream.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over HTTP\n * commands plus SSE event streams. Bound to a specific `threadId`\n * at construction. Each {@link openEventStream} call opens an independent\n * filtered SSE connection via `POST /threads/:thread_id/stream/events`.\n */\nexport class ProtocolSseTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly fetchImpl: typeof fetch;\n\n private readonly defaultHeaders: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly fetchFactory?: () => typeof fetch | Promise<typeof fetch>;\n\n private readonly commandsUrl: string;\n\n private readonly streamUrl: string;\n\n private readonly stateUrl: string;\n\n private readonly sessionAbortController = new AbortController();\n\n private readonly eventStreams = new Set<AbortController>();\n\n private closed = false;\n\n constructor(options: ProtocolSseTransportOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n this.apiUrl = options.apiUrl;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.onRequest = options.onRequest;\n this.fetchFactory = options.fetchFactory;\n this.threadId = options.threadId;\n this.commandsUrl =\n options.paths?.commands ?? `/threads/${this.threadId}/commands`;\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.stateUrl = options.paths?.state ?? `/threads/${this.threadId}/state`;\n }\n\n /**\n * Fetch checkpointed thread state for hydration.\n *\n * Uses `GET`, matching `client.threads.getState()` and both LangGraph\n * Platform and Agent Protocol custom backends (`POST` is reserved for\n * `updateState`).\n */\n async getState<StateType = unknown>(): Promise<{\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n } | null> {\n const url = toAbsoluteUrl(this.apiUrl, this.stateUrl);\n let requestInit: RequestInit = {\n method: \"GET\",\n headers: mergeHeaders(this.defaultHeaders, {}),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n const error = toError(\n new Error(\n `Thread state request failed: ${response.status} ${response.statusText}`\n )\n ) as Error & { status?: number };\n error.status = response.status;\n throw error;\n }\n\n return (await response.json()) as {\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n };\n }\n\n private async resolveFetch(): Promise<typeof fetch> {\n if (this.fetchFactory) {\n return await this.fetchFactory();\n }\n return this.fetchImpl;\n }\n\n /**\n * HTTP/SSE transports have no handshake — connections are made\n * per-command and per-subscription.\n */\n async open(): Promise<void> {\n // no-op\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n const response = await this.request(this.commandsUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(command),\n signal: this.sessionAbortController.signal,\n });\n\n if (response.status === 202 || response.status === 204) {\n return undefined;\n }\n\n const payload = (await response.json()) as unknown;\n if (!isProtocolResponse(payload)) {\n throw new Error(\"Protocol command did not return a valid response.\");\n }\n return payload;\n }\n\n /**\n * WebSocket-style single event stream.\n * For the SSE transport this returns a dummy iterable; real event\n * delivery happens via {@link openEventStream}.\n */\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.closed) {\n throw new Error(\"Protocol transport is closed.\");\n }\n\n const ac = new AbortController();\n this.eventStreams.add(ac);\n const streamQueue = new AsyncQueue<Message>();\n const streamUrl = this.streamUrl;\n\n let resolveReady!: () => void;\n let rejectReady!: (err: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n const since = (params as SubscribeParams & { since?: unknown }).since;\n\n const startStream = async () => {\n try {\n const response = await this.request(streamUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body: JSON.stringify({\n channels: params.channels,\n ...(params.namespaces ? { namespaces: params.namespaces } : {}),\n ...(params.depth != null ? { depth: params.depth } : {}),\n ...(typeof since === \"number\" ? { since } : {}),\n }),\n signal: ac.signal,\n });\n\n resolveReady();\n\n const readable =\n response.body ??\n new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n\n const stream = readable\n .pipeThrough(BytesLineDecoder())\n .pipeThrough(SSEDecoder());\n const iterable = IterableReadableStream.fromReadableStream(stream);\n\n for await (const event of iterable) {\n if (ac.signal.aborted || this.closed) {\n break;\n }\n if (isRecord(event.data)) {\n const msg = event.data as Message & {\n seq?: number;\n method?: string;\n };\n streamQueue.push(msg);\n }\n }\n streamQueue.close();\n } catch (error) {\n rejectReady(error);\n if (ac.signal.aborted || this.closed) {\n streamQueue.close();\n return;\n }\n streamQueue.close(error);\n }\n };\n\n void startStream();\n\n const cleanup = () => {\n this.eventStreams.delete(ac);\n ac.abort();\n streamQueue.close();\n };\n\n return {\n events: {\n [Symbol.asyncIterator]: () => ({\n next: async () => await streamQueue.shift(),\n return: async () => {\n cleanup();\n return { done: true, value: undefined };\n },\n }),\n },\n ready,\n close: cleanup,\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.sessionAbortController.abort();\n for (const ac of this.eventStreams) ac.abort();\n this.eventStreams.clear();\n this.queue.close();\n }\n\n private async request(path: string, init: RequestInit): Promise<Response> {\n const url = toAbsoluteUrl(this.apiUrl, path);\n let requestInit: RequestInit = {\n ...init,\n headers: mergeHeaders(this.defaultHeaders, init.headers),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n try {\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (!response.ok) {\n let detail = \"\";\n try {\n const body = await response.text();\n const parsed = JSON.parse(body);\n if (typeof parsed === \"object\" && parsed != null) {\n detail =\n ((parsed as Record<string, unknown>).message as string) ??\n ((parsed as Record<string, unknown>).error as string) ??\n \"\";\n }\n if (!detail) detail = body;\n } catch {\n // body unreadable or not JSON — fall through\n }\n const message = detail\n ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}`\n : `Protocol request failed: ${response.status} ${response.statusText}`;\n thro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AAI,cAA2B;GAC7B,GAAG;GACH,SAASC,cAAAA,aAAa,KAAK,gBAAgB,KAAK,QAAQ;GACzD;AAED,MAAI,KAAK,UACP,eAAc,MAAM,KAAK,UAAU,KAAK,YAAY;AAGtD,MAAI;GAEF,MAAM,WAAW,OADC,MAAM,KAAK,cAAc,EACV,IAAI,UAAU,EAAE,YAAY;AAC7D,OAAI,CAAC,SAAS,IAAI;IAChB,IAAI,SAAS;AACb,QAAI;KACF,MAAM,OAAO,MAAM,SAAS,MAAM;KAClC,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,SAAI,OAAO,WAAW,YAAY,UAAU,KAC1C,UACI,OAAmC,WACnC,OAAmC,SACrC;AAEJ,SAAI,CAAC,OAAQ,UAAS;YAChB;IAGR,MAAM,UAAU,SACZ,4BAA4B,SAAS,OAAO,GAAG,SAAS,WAAW,KAAK,WACxE,4BAA4B,SAAS,OAAO,GAAG,SAAS;AAC5D,UAAM,IAAI,MAAM,QAAQ;;AAE1B,UAAO;WACA,OAAO;AACd,SAAMC,cAAAA,QAAQ,MAAM"} | ||
| {"version":3,"file":"http.cjs","names":["AsyncQueue","webSocketReconnectDelayMs","toAbsoluteUrl","mergeHeaders","toError","isProtocolResponse","BytesLineDecoder","SSEDecoder","IterableReadableStream","isRecord"],"sources":["../../../../src/client/stream/transport/http.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n SubscribeParams,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport type { AsyncCaller } from \"../../../utils/async_caller.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolSseTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter, EventStreamHandle } from \"../transport.js\";\nimport {\n toAbsoluteUrl,\n isRecord,\n mergeHeaders,\n toError,\n isProtocolResponse,\n} from \"./utils.js\";\nimport { BytesLineDecoder, SSEDecoder } from \"../../../utils/sse.js\";\nimport { IterableReadableStream } from \"../../../utils/stream.js\";\nimport { webSocketReconnectDelayMs } from \"./websocket.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over HTTP\n * commands plus SSE event streams. Bound to a specific `threadId`\n * at construction. Each {@link openEventStream} call opens an independent\n * filtered SSE connection via `POST /threads/:thread_id/stream/events`.\n */\nexport class ProtocolSseTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly fetchImpl: typeof fetch;\n\n private readonly defaultHeaders: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly fetchFactory?: () => typeof fetch | Promise<typeof fetch>;\n\n private readonly asyncCaller?: AsyncCaller;\n\n private readonly maxReconnectAttempts: number;\n\n private readonly onReconnect?: ProtocolSseTransportOptions[\"onReconnect\"];\n\n private readonly reconnectDelayMs: (attempt: number) => number;\n\n private readonly commandsUrl: string;\n\n private readonly streamUrl: string;\n\n private readonly stateUrl: string;\n\n private readonly sessionAbortController = new AbortController();\n\n private readonly eventStreams = new Set<AbortController>();\n\n private closed = false;\n\n constructor(options: ProtocolSseTransportOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n this.apiUrl = options.apiUrl;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.onRequest = options.onRequest;\n this.fetchFactory = options.fetchFactory;\n this.asyncCaller = options.asyncCaller;\n // Custom fetch (tests/mocks) must not auto-reconnect — same policy as skipping AsyncCaller.\n this.maxReconnectAttempts =\n options.fetch != null ? 0 : (options.maxReconnectAttempts ?? 5);\n this.onReconnect = options.onReconnect;\n this.reconnectDelayMs =\n options.reconnectDelayMs ?? webSocketReconnectDelayMs;\n this.threadId = options.threadId;\n this.commandsUrl =\n options.paths?.commands ?? `/threads/${this.threadId}/commands`;\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.stateUrl = options.paths?.state ?? `/threads/${this.threadId}/state`;\n }\n\n /**\n * Fetch checkpointed thread state for hydration.\n *\n * Uses `GET`, matching `client.threads.getState()` and both LangGraph\n * Platform and Agent Protocol custom backends (`POST` is reserved for\n * `updateState`).\n */\n async getState<StateType = unknown>(): Promise<{\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n } | null> {\n const url = toAbsoluteUrl(this.apiUrl, this.stateUrl);\n let requestInit: RequestInit = {\n method: \"GET\",\n headers: mergeHeaders(this.defaultHeaders, {}),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n const error = toError(\n new Error(\n `Thread state request failed: ${response.status} ${response.statusText}`\n )\n ) as Error & { status?: number };\n error.status = response.status;\n throw error;\n }\n\n return (await response.json()) as {\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n };\n }\n\n private async resolveFetch(): Promise<typeof fetch> {\n if (this.fetchFactory) {\n return await this.fetchFactory();\n }\n return this.fetchImpl;\n }\n\n /**\n * HTTP/SSE transports have no handshake — connections are made\n * per-command and per-subscription.\n */\n async open(): Promise<void> {\n // no-op\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n const response = await this.request(this.commandsUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(command),\n signal: this.sessionAbortController.signal,\n });\n\n if (response.status === 202 || response.status === 204) {\n return undefined;\n }\n\n const payload = (await response.json()) as unknown;\n if (!isProtocolResponse(payload)) {\n throw new Error(\"Protocol command did not return a valid response.\");\n }\n return payload;\n }\n\n /**\n * WebSocket-style single event stream.\n * For the SSE transport this returns a dummy iterable; real event\n * delivery happens via {@link openEventStream}.\n */\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.closed) {\n throw new Error(\"Protocol transport is closed.\");\n }\n\n const ac = new AbortController();\n this.eventStreams.add(ac);\n const streamQueue = new AsyncQueue<Message>();\n const streamUrl = this.streamUrl;\n\n let resolveReady!: () => void;\n let rejectReady!: (err: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n let resumeAfterSeq =\n typeof (params as SubscribeParams & { since?: unknown }).since ===\n \"number\"\n ? (params as SubscribeParams & { since: number }).since\n : undefined;\n\n let readySettled = false;\n\n const startStream = async () => {\n let attempt = 0;\n\n while (!ac.signal.aborted && !this.closed) {\n try {\n const response = await this.request(\n streamUrl,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body: JSON.stringify({\n channels: params.channels,\n ...(params.namespaces ? { namespaces: params.namespaces } : {}),\n ...(params.depth != null ? { depth: params.depth } : {}),\n ...(resumeAfterSeq != null ? { since: resumeAfterSeq } : {}),\n }),\n signal: ac.signal,\n },\n { stream: true }\n );\n\n if (!readySettled) {\n readySettled = true;\n resolveReady();\n }\n\n const readable =\n response.body ??\n new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n\n const stream = readable\n .pipeThrough(BytesLineDecoder())\n .pipeThrough(SSEDecoder());\n const iterable = IterableReadableStream.fromReadableStream(stream);\n\n for await (const event of iterable) {\n if (ac.signal.aborted || this.closed) {\n break;\n }\n if (isRecord(event.data)) {\n const msg = event.data as Message & {\n seq?: number;\n method?: string;\n };\n if (typeof msg.seq === \"number\") {\n resumeAfterSeq = msg.seq;\n }\n streamQueue.push(msg);\n }\n }\n streamQueue.close();\n return;\n } catch (error) {\n if (ac.signal.aborted || this.closed) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close();\n return;\n }\n if (this.maxReconnectAttempts <= 0) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close(toError(error));\n return;\n }\n attempt += 1;\n if (attempt > this.maxReconnectAttempts) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close(toError(error));\n return;\n }\n this.onReconnect?.({ attempt, cause: error });\n const delay = this.reconnectDelayMs(attempt);\n if (delay > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delay);\n });\n }\n }\n }\n };\n\n void startStream();\n\n const cleanup = () => {\n this.eventStreams.delete(ac);\n ac.abort();\n streamQueue.close();\n };\n\n return {\n events: {\n [Symbol.asyncIterator]: () => ({\n next: async () => await streamQueue.shift(),\n return: async () => {\n cleanup();\n return { done: true, value: undefined };\n },\n }),\n },\n ready,\n close: cleanup,\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.sessionAbortController.abort();\n for (const ac of this.eventStreams) ac.abort();\n this.eventStreams.clear();\n this.queue.close();\n }\n\n private async request(\n path: string,\n init: RequestInit,\n options?: { stream?: boolean }\n ): Promise<Response> {\n const url = toAbsoluteUrl(this.apiUrl, path);\n let requestInit: RequestInit = {\n ...init,\n headers: mergeHeaders(this.defaultHeaders, init.headers),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n // Long-lived SSE event streams must not run through AsyncCaller: its\n // p-queue/p-retry semantics are designed for discrete request/response\n // calls, and wrapping a streaming response stalls the call (and can\n // leak retries). Stream resilience is handled separately by the\n // reconnect loop in `openEventStream`.\n const useAsyncCaller = this.asyncCaller != null && !options?.stream;\n\n const execute = async (): Promise<Response> => {\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (!response.ok) {\n // Reject with the Response so AsyncCaller maps it to HTTPError and\n // applies STATUS_NO_RETRY / retry policy consistently with REST.\n if (useAsyncCaller) {\n throw response;\n }\n let detail = \"\";\n try {\n const body = await response.text();\n const parsed = JSON.parse(body);\n if (typeof parsed === \"object\" && parsed != null) {\n detail =\n ((parsed as Record<string, unknown>).message as string) ??\n ((parsed as Record<string, unknown>).error as string) ??\n \"\";\n }\n if (!detail) detail = body;\n } catch {\n // body unreadable or not JSON — fall through\n }\n const message = detail\n ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}`\n : `Protocol request failed: ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n return response;\n };\n\n try {\n return useAsyncCaller\n ? await this.asyncCaller!.call(execute)\n : await execute();\n } catch (error) {\n throw toError(error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiCA,IAAa,8BAAb,MAAqE;CACnE;CAEA;CAEA,QAAyB,IAAIA,cAAAA,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,yBAA0C,IAAI,iBAAiB;CAE/D,+BAAgC,IAAI,KAAsB;CAE1D,SAAiB;CAEjB,YAAY,SAAsC;AAChD,OAAK,YAAY,QAAQ,SAAS;AAClC,OAAK,SAAS,QAAQ;AACtB,OAAK,iBAAiB,QAAQ,kBAAkB,EAAE;AAClD,OAAK,YAAY,QAAQ;AACzB,OAAK,eAAe,QAAQ;AAC5B,OAAK,cAAc,QAAQ;AAE3B,OAAK,uBACH,QAAQ,SAAS,OAAO,IAAK,QAAQ,wBAAwB;AAC/D,OAAK,cAAc,QAAQ;AAC3B,OAAK,mBACH,QAAQ,oBAAoBC,kBAAAA;AAC9B,OAAK,WAAW,QAAQ;AACxB,OAAK,cACH,QAAQ,OAAO,YAAY,YAAY,KAAK,SAAS;AACvD,OAAK,YACH,QAAQ,OAAO,UAAU,YAAY,KAAK,SAAS;AACrD,OAAK,WAAW,QAAQ,OAAO,SAAS,YAAY,KAAK,SAAS;;;;;;;;;CAUpE,MAAM,WAOI;EACR,MAAM,MAAMC,cAAAA,cAAc,KAAK,QAAQ,KAAK,S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Aa,KAAK,gBAAgB,KAAK,QAAQ;GACzD;AAED,MAAI,KAAK,UACP,eAAc,MAAM,KAAK,UAAU,KAAK,YAAY;EAQtD,MAAM,iBAAiB,KAAK,eAAe,QAAQ,CAAC,SAAS;EAE7D,MAAM,UAAU,YAA+B;GAE7C,MAAM,WAAW,OADC,MAAM,KAAK,cAAc,EACV,IAAI,UAAU,EAAE,YAAY;AAC7D,OAAI,CAAC,SAAS,IAAI;AAGhB,QAAI,eACF,OAAM;IAER,IAAI,SAAS;AACb,QAAI;KACF,MAAM,OAAO,MAAM,SAAS,MAAM;KAClC,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,SAAI,OAAO,WAAW,YAAY,UAAU,KAC1C,UACI,OAAmC,WACnC,OAAmC,SACrC;AAEJ,SAAI,CAAC,OAAQ,UAAS;YAChB;IAGR,MAAM,UAAU,SACZ,4BAA4B,SAAS,OAAO,GAAG,SAAS,WAAW,KAAK,WACxE,4BAA4B,SAAS,OAAO,GAAG,SAAS;AAC5D,UAAM,IAAI,MAAM,QAAQ;;AAE1B,UAAO;;AAGT,MAAI;AACF,UAAO,iBACH,MAAM,KAAK,YAAa,KAAK,QAAQ,GACrC,MAAM,SAAS;WACZ,OAAO;AACd,SAAMC,cAAAA,QAAQ,MAAM"} |
@@ -20,2 +20,6 @@ import { EventStreamHandle, TransportAdapter } from "../transport.cjs"; | ||
| private readonly fetchFactory?; | ||
| private readonly asyncCaller?; | ||
| private readonly maxReconnectAttempts; | ||
| private readonly onReconnect?; | ||
| private readonly reconnectDelayMs; | ||
| private readonly commandsUrl; | ||
@@ -22,0 +26,0 @@ private readonly streamUrl; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"http.d.cts","names":[],"sources":["../../../../src/client/stream/transport/http.ts"],"mappings":";;;;;;;AA+BA;;;;cAAa,2BAAA,YAAuC,gBAAA;EAAA,SACzC,QAAA;EAAA,SAEA,MAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,SAAA;EAAA,i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EAAQ,SAAA;IACR,IAAA;IACA,KAAA;IACA,QAAA;IACA,UAAA;MAAe,aAAA;IAAA;IACf,iBAAA;MAAsB,aAAA;IAAA;EAAA;EAAA,QAmCV,YAAA;EAxCZ;;;;EAmDI,IAAA,CAAA,GAAQ,OAAA;EAIR,IAAA,CACJ,OAAA,EAAS,OAAA,GACR,OAAA,CAAQ,eAAA,GAAkB,aAAA;EArDZ;;;;;EA6EjB,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAaxB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,iBAAA;EA6IpC,KAAA,CAAA,GAAS,OAAA;EAAA,QAWD,OAAA;AAAA"} |
@@ -20,2 +20,6 @@ import { EventStreamHandle, TransportAdapter } from "../transport.js"; | ||
| private readonly fetchFactory?; | ||
| private readonly asyncCaller?; | ||
| private readonly maxReconnectAttempts; | ||
| private readonly onReconnect?; | ||
| private readonly reconnectDelayMs; | ||
| private readonly commandsUrl; | ||
@@ -22,0 +26,0 @@ private readonly streamUrl; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"http.d.ts","names":[],"sources":["../../../../src/client/stream/transport/http.ts"],"mappings":";;;;;;;AA+BA;;;;cAAa,2BAAA,YAAuC,gBAAA;EAAA,SACzC,QAAA;EAAA,SAEA,MAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,cAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,YAAA;EAAA,iBAEA,WAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,QAAA;EAAA,iBAEA,sBAAA;EAAA,iBAEA,YAAA;EAAA,QAET,MAAA;EAER,WAAA,CAAY,OAAA,EAAS,2BAAA;EA3B6B;;;;;;;EAgD5C,QAAA,qBAAA,CAAA,GAAiC,OAAA;IACrC,MAAA,EAAQ,SAAA;IACR,IAAA;IACA,KAAA;IACA,QAAA;IACA,UAAA;MAAe,aAAA;IAAA;IACf,iBAAA;MAAsB,aAAA;IAAA;EA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A,GAAS,OAAA;EAAA,QAWD,OAAA;AAAA"} |
@@ -5,2 +5,3 @@ import { BytesLineDecoder, SSEDecoder } from "../../../utils/sse.js"; | ||
| import { isProtocolResponse, isRecord, mergeHeaders, toAbsoluteUrl, toError } from "./utils.js"; | ||
| import { webSocketReconnectDelayMs } from "./websocket.js"; | ||
| //#region src/client/stream/transport/http.ts | ||
@@ -21,2 +22,6 @@ /** | ||
| fetchFactory; | ||
| asyncCaller; | ||
| maxReconnectAttempts; | ||
| onReconnect; | ||
| reconnectDelayMs; | ||
| commandsUrl; | ||
@@ -34,2 +39,6 @@ streamUrl; | ||
| this.fetchFactory = options.fetchFactory; | ||
| this.asyncCaller = options.asyncCaller; | ||
| this.maxReconnectAttempts = options.fetch != null ? 0 : options.maxReconnectAttempts ?? 5; | ||
| this.onReconnect = options.onReconnect; | ||
| this.reconnectDelayMs = options.reconnectDelayMs ?? webSocketReconnectDelayMs; | ||
| this.threadId = options.threadId; | ||
@@ -114,5 +123,7 @@ this.commandsUrl = options.paths?.commands ?? `/threads/${this.threadId}/commands`; | ||
| }); | ||
| const since = params.since; | ||
| let resumeAfterSeq = typeof params.since === "number" ? params.since : void 0; | ||
| let readySettled = false; | ||
| const startStream = async () => { | ||
| try { | ||
| let attempt = 0; | ||
| while (!ac.signal.aborted && !this.closed) try { | ||
| const response = await this.request(streamUrl, { | ||
@@ -128,7 +139,10 @@ method: "POST", | ||
| ...params.depth != null ? { depth: params.depth } : {}, | ||
| ...typeof since === "number" ? { since } : {} | ||
| ...resumeAfterSeq != null ? { since: resumeAfterSeq } : {} | ||
| }), | ||
| signal: ac.signal | ||
| }); | ||
| resolveReady(); | ||
| }, { stream: true }); | ||
| if (!readySettled) { | ||
| readySettled = true; | ||
| resolveReady(); | ||
| } | ||
| const stream = (response.body ?? new ReadableStream({ start(controller) { | ||
@@ -142,2 +156,3 @@ controller.close(); | ||
| const msg = event.data; | ||
| if (typeof msg.seq === "number") resumeAfterSeq = msg.seq; | ||
| streamQueue.push(msg); | ||
@@ -147,9 +162,28 @@ } | ||
| streamQueue.close(); | ||
| return; | ||
| } catch (error) { | ||
| rejectReady(error); | ||
| if (ac.signal.aborted || this.closed) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(); | ||
| return; | ||
| } | ||
| streamQueue.close(error); | ||
| if (this.maxReconnectAttempts <= 0) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(toError(error)); | ||
| return; | ||
| } | ||
| attempt += 1; | ||
| if (attempt > this.maxReconnectAttempts) { | ||
| if (!readySettled) rejectReady(error); | ||
| streamQueue.close(toError(error)); | ||
| return; | ||
| } | ||
| this.onReconnect?.({ | ||
| attempt, | ||
| cause: error | ||
| }); | ||
| const delay = this.reconnectDelayMs(attempt); | ||
| if (delay > 0) await new Promise((resolve) => { | ||
| setTimeout(resolve, delay); | ||
| }); | ||
| } | ||
@@ -186,3 +220,3 @@ }; | ||
| } | ||
| async request(path, init) { | ||
| async request(path, init, options) { | ||
| const url = toAbsoluteUrl(this.apiUrl, path); | ||
@@ -194,5 +228,7 @@ let requestInit = { | ||
| if (this.onRequest) requestInit = await this.onRequest(url, requestInit); | ||
| try { | ||
| const useAsyncCaller = this.asyncCaller != null && !options?.stream; | ||
| const execute = async () => { | ||
| const response = await (await this.resolveFetch())(url.toString(), requestInit); | ||
| if (!response.ok) { | ||
| if (useAsyncCaller) throw response; | ||
| let detail = ""; | ||
@@ -209,2 +245,5 @@ try { | ||
| return response; | ||
| }; | ||
| try { | ||
| return useAsyncCaller ? await this.asyncCaller.call(execute) : await execute(); | ||
| } catch (error) { | ||
@@ -211,0 +250,0 @@ throw toError(error); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"http.js","names":[],"sources":["../../../../src/client/stream/transport/http.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n SubscribeParams,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolSseTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter, EventStreamHandle } from \"../transport.js\";\nimport {\n toAbsoluteUrl,\n isRecord,\n mergeHeaders,\n toError,\n isProtocolResponse,\n} from \"./utils.js\";\nimport { BytesLineDecoder, SSEDecoder } from \"../../../utils/sse.js\";\nimport { IterableReadableStream } from \"../../../utils/stream.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over HTTP\n * commands plus SSE event streams. Bound to a specific `threadId`\n * at construction. Each {@link openEventStream} call opens an independent\n * filtered SSE connection via `POST /threads/:thread_id/stream/events`.\n */\nexport class ProtocolSseTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly fetchImpl: typeof fetch;\n\n private readonly defaultHeaders: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly fetchFactory?: () => typeof fetch | Promise<typeof fetch>;\n\n private readonly commandsUrl: string;\n\n private readonly streamUrl: string;\n\n private readonly stateUrl: string;\n\n private readonly sessionAbortController = new AbortController();\n\n private readonly eventStreams = new Set<AbortController>();\n\n private closed = false;\n\n constructor(options: ProtocolSseTransportOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n this.apiUrl = options.apiUrl;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.onRequest = options.onRequest;\n this.fetchFactory = options.fetchFactory;\n this.threadId = options.threadId;\n this.commandsUrl =\n options.paths?.commands ?? `/threads/${this.threadId}/commands`;\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.stateUrl = options.paths?.state ?? `/threads/${this.threadId}/state`;\n }\n\n /**\n * Fetch checkpointed thread state for hydration.\n *\n * Uses `GET`, matching `client.threads.getState()` and both LangGraph\n * Platform and Agent Protocol custom backends (`POST` is reserved for\n * `updateState`).\n */\n async getState<StateType = unknown>(): Promise<{\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n } | null> {\n const url = toAbsoluteUrl(this.apiUrl, this.stateUrl);\n let requestInit: RequestInit = {\n method: \"GET\",\n headers: mergeHeaders(this.defaultHeaders, {}),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n const error = toError(\n new Error(\n `Thread state request failed: ${response.status} ${response.statusText}`\n )\n ) as Error & { status?: number };\n error.status = response.status;\n throw error;\n }\n\n return (await response.json()) as {\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n };\n }\n\n private async resolveFetch(): Promise<typeof fetch> {\n if (this.fetchFactory) {\n return await this.fetchFactory();\n }\n return this.fetchImpl;\n }\n\n /**\n * HTTP/SSE transports have no handshake — connections are made\n * per-command and per-subscription.\n */\n async open(): Promise<void> {\n // no-op\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n const response = await this.request(this.commandsUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(command),\n signal: this.sessionAbortController.signal,\n });\n\n if (response.status === 202 || response.status === 204) {\n return undefined;\n }\n\n const payload = (await response.json()) as unknown;\n if (!isProtocolResponse(payload)) {\n throw new Error(\"Protocol command did not return a valid response.\");\n }\n return payload;\n }\n\n /**\n * WebSocket-style single event stream.\n * For the SSE transport this returns a dummy iterable; real event\n * delivery happens via {@link openEventStream}.\n */\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.closed) {\n throw new Error(\"Protocol transport is closed.\");\n }\n\n const ac = new AbortController();\n this.eventStreams.add(ac);\n const streamQueue = new AsyncQueue<Message>();\n const streamUrl = this.streamUrl;\n\n let resolveReady!: () => void;\n let rejectReady!: (err: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n const since = (params as SubscribeParams & { since?: unknown }).since;\n\n const startStream = async () => {\n try {\n const response = await this.request(streamUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body: JSON.stringify({\n channels: params.channels,\n ...(params.namespaces ? { namespaces: params.namespaces } : {}),\n ...(params.depth != null ? { depth: params.depth } : {}),\n ...(typeof since === \"number\" ? { since } : {}),\n }),\n signal: ac.signal,\n });\n\n resolveReady();\n\n const readable =\n response.body ??\n new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n\n const stream = readable\n .pipeThrough(BytesLineDecoder())\n .pipeThrough(SSEDecoder());\n const iterable = IterableReadableStream.fromReadableStream(stream);\n\n for await (const event of iterable) {\n if (ac.signal.aborted || this.closed) {\n break;\n }\n if (isRecord(event.data)) {\n const msg = event.data as Message & {\n seq?: number;\n method?: string;\n };\n streamQueue.push(msg);\n }\n }\n streamQueue.close();\n } catch (error) {\n rejectReady(error);\n if (ac.signal.aborted || this.closed) {\n streamQueue.close();\n return;\n }\n streamQueue.close(error);\n }\n };\n\n void startStream();\n\n const cleanup = () => {\n this.eventStreams.delete(ac);\n ac.abort();\n streamQueue.close();\n };\n\n return {\n events: {\n [Symbol.asyncIterator]: () => ({\n next: async () => await streamQueue.shift(),\n return: async () => {\n cleanup();\n return { done: true, value: undefined };\n },\n }),\n },\n ready,\n close: cleanup,\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.sessionAbortController.abort();\n for (const ac of this.eventStreams) ac.abort();\n this.eventStreams.clear();\n this.queue.close();\n }\n\n private async request(path: string, init: RequestInit): Promise<Response> {\n const url = toAbsoluteUrl(this.apiUrl, path);\n let requestInit: RequestInit = {\n ...init,\n headers: mergeHeaders(this.defaultHeaders, init.headers),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n try {\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (!response.ok) {\n let detail = \"\";\n try {\n const body = await response.text();\n const parsed = JSON.parse(body);\n if (typeof parsed === \"object\" && parsed != null) {\n detail =\n ((parsed as Record<string, unknown>).message as string) ??\n ((parsed as Record<string, unknown>).error as string) ??\n \"\";\n }\n if (!detail) detail = body;\n } catch {\n // body unreadable or not JSON — fall through\n }\n const message = detail\n ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}`\n : `Protocol request failed: ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n return response;\n } catch (error) {\n throw toError(error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA+BA,IAAa,8BAAb,MAAqE;CACnE;CAEA;CAEA,QAAyB,IAAI,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,yBAA0C,IAAI,iBAAiB;CAE/D,+BAAgC,IAAI,KAAsB;CAE1D,SAAiB;CAEjB,YAAY,SAAsC;AAChD,OAAK,YAAY,QAAQ,SAAS;AAClC,OAAK,SAAS,QAAQ;AACtB,OAAK,iBAAiB,QAAQ,kBAAkB,EAAE;AAClD,OAAK,YAAY,QAAQ;AACzB,OAAK,eAAe,QAAQ;AAC5B,OAAK,WAAW,QAAQ;AACxB,OAAK,cACH,QAAQ,OAAO,YAAY,YAAY,KAAK,SAAS;AACvD,OAAK,YACH,QAAQ,OAAO,UAAU,YAAY,KAAK,SAAS;AACrD,OAAK,WAAW,QAAQ,OAAO,SAAS,YAAY,KAAK,SAAS;;;;;;;;;CAUpE,MAAM,WAOI;EACR,MAAM,MAAM,cAAc,KAAK,QAAQ,KAAK,SAAS;EACrD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Q,GACL,OAAO,uBAAuB;IAC7B,MAAM,YAAY,MAAM,YAAY,OAAO;IAC3C,QAAQ,YAAY;AAClB,cAAS;AACT,YAAO;MAAE,MAAM;MAAM,OAAO,KAAA;MAAW;;IAE1C,GACF;GACD;GACA,OAAO;GACR;;CAGH,MAAM,QAAuB;AAC3B,MAAI,KAAK,OACP;AAEF,OAAK,SAAS;AACd,OAAK,uBAAuB,OAAO;AACnC,OAAK,MAAM,MAAM,KAAK,aAAc,IAAG,OAAO;AAC9C,OAAK,aAAa,OAAO;AACzB,OAAK,MAAM,OAAO;;CAGpB,MAAc,QAAQ,MAAc,MAAsC;EACxE,MAAM,MAAM,cAAc,KAAK,QAAQ,KAAK;EAC5C,IAAI,cAA2B;GAC7B,GAAG;GACH,SAAS,aAAa,KAAK,gBAAgB,KAAK,QAAQ;GACzD;AAED,MAAI,KAAK,UACP,eAAc,MAAM,KAAK,UAAU,KAAK,YAAY;AAGtD,MAAI;GAEF,MAAM,WAAW,OADC,MAAM,KAAK,cAAc,EACV,IAAI,UAAU,EAAE,YAAY;AAC7D,OAAI,CAAC,SAAS,IAAI;IAChB,IAAI,SAAS;AACb,QAAI;KACF,MAAM,OAAO,MAAM,SAAS,MAAM;KAClC,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,SAAI,OAAO,WAAW,YAAY,UAAU,KAC1C,UACI,OAAmC,WACnC,OAAmC,SACrC;AAEJ,SAAI,CAAC,OAAQ,UAAS;YAChB;IAGR,MAAM,UAAU,SACZ,4BAA4B,SAAS,OAAO,GAAG,SAAS,WAAW,KAAK,WACxE,4BAA4B,SAAS,OAAO,GAAG,SAAS;AAC5D,UAAM,IAAI,MAAM,QAAQ;;AAE1B,UAAO;WACA,OAAO;AACd,SAAM,QAAQ,MAAM"} | ||
| {"version":3,"file":"http.js","names":[],"sources":["../../../../src/client/stream/transport/http.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n SubscribeParams,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport type { AsyncCaller } from \"../../../utils/async_caller.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n ProtocolSseTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter, EventStreamHandle } from \"../transport.js\";\nimport {\n toAbsoluteUrl,\n isRecord,\n mergeHeaders,\n toError,\n isProtocolResponse,\n} from \"./utils.js\";\nimport { BytesLineDecoder, SSEDecoder } from \"../../../utils/sse.js\";\nimport { IterableReadableStream } from \"../../../utils/stream.js\";\nimport { webSocketReconnectDelayMs } from \"./websocket.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over HTTP\n * commands plus SSE event streams. Bound to a specific `threadId`\n * at construction. Each {@link openEventStream} call opens an independent\n * filtered SSE connection via `POST /threads/:thread_id/stream/events`.\n */\nexport class ProtocolSseTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n readonly apiUrl: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly fetchImpl: typeof fetch;\n\n private readonly defaultHeaders: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly fetchFactory?: () => typeof fetch | Promise<typeof fetch>;\n\n private readonly asyncCaller?: AsyncCaller;\n\n private readonly maxReconnectAttempts: number;\n\n private readonly onReconnect?: ProtocolSseTransportOptions[\"onReconnect\"];\n\n private readonly reconnectDelayMs: (attempt: number) => number;\n\n private readonly commandsUrl: string;\n\n private readonly streamUrl: string;\n\n private readonly stateUrl: string;\n\n private readonly sessionAbortController = new AbortController();\n\n private readonly eventStreams = new Set<AbortController>();\n\n private closed = false;\n\n constructor(options: ProtocolSseTransportOptions) {\n this.fetchImpl = options.fetch ?? fetch;\n this.apiUrl = options.apiUrl;\n this.defaultHeaders = options.defaultHeaders ?? {};\n this.onRequest = options.onRequest;\n this.fetchFactory = options.fetchFactory;\n this.asyncCaller = options.asyncCaller;\n // Custom fetch (tests/mocks) must not auto-reconnect — same policy as skipping AsyncCaller.\n this.maxReconnectAttempts =\n options.fetch != null ? 0 : (options.maxReconnectAttempts ?? 5);\n this.onReconnect = options.onReconnect;\n this.reconnectDelayMs =\n options.reconnectDelayMs ?? webSocketReconnectDelayMs;\n this.threadId = options.threadId;\n this.commandsUrl =\n options.paths?.commands ?? `/threads/${this.threadId}/commands`;\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.stateUrl = options.paths?.state ?? `/threads/${this.threadId}/state`;\n }\n\n /**\n * Fetch checkpointed thread state for hydration.\n *\n * Uses `GET`, matching `client.threads.getState()` and both LangGraph\n * Platform and Agent Protocol custom backends (`POST` is reserved for\n * `updateState`).\n */\n async getState<StateType = unknown>(): Promise<{\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n } | null> {\n const url = toAbsoluteUrl(this.apiUrl, this.stateUrl);\n let requestInit: RequestInit = {\n method: \"GET\",\n headers: mergeHeaders(this.defaultHeaders, {}),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (response.status === 404) return null;\n if (!response.ok) {\n const error = toError(\n new Error(\n `Thread state request failed: ${response.status} ${response.statusText}`\n )\n ) as Error & { status?: number };\n error.status = response.status;\n throw error;\n }\n\n return (await response.json()) as {\n values: StateType;\n next?: unknown;\n tasks?: unknown;\n metadata?: unknown;\n checkpoint?: { checkpoint_id?: string } | null;\n parent_checkpoint?: { checkpoint_id?: string } | null;\n };\n }\n\n private async resolveFetch(): Promise<typeof fetch> {\n if (this.fetchFactory) {\n return await this.fetchFactory();\n }\n return this.fetchImpl;\n }\n\n /**\n * HTTP/SSE transports have no handshake — connections are made\n * per-command and per-subscription.\n */\n async open(): Promise<void> {\n // no-op\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n const response = await this.request(this.commandsUrl, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(command),\n signal: this.sessionAbortController.signal,\n });\n\n if (response.status === 202 || response.status === 204) {\n return undefined;\n }\n\n const payload = (await response.json()) as unknown;\n if (!isProtocolResponse(payload)) {\n throw new Error(\"Protocol command did not return a valid response.\");\n }\n return payload;\n }\n\n /**\n * WebSocket-style single event stream.\n * For the SSE transport this returns a dummy iterable; real event\n * delivery happens via {@link openEventStream}.\n */\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n openEventStream(params: SubscribeParams): EventStreamHandle {\n if (this.closed) {\n throw new Error(\"Protocol transport is closed.\");\n }\n\n const ac = new AbortController();\n this.eventStreams.add(ac);\n const streamQueue = new AsyncQueue<Message>();\n const streamUrl = this.streamUrl;\n\n let resolveReady!: () => void;\n let rejectReady!: (err: unknown) => void;\n const ready = new Promise<void>((resolve, reject) => {\n resolveReady = resolve;\n rejectReady = reject;\n });\n\n let resumeAfterSeq =\n typeof (params as SubscribeParams & { since?: unknown }).since ===\n \"number\"\n ? (params as SubscribeParams & { since: number }).since\n : undefined;\n\n let readySettled = false;\n\n const startStream = async () => {\n let attempt = 0;\n\n while (!ac.signal.aborted && !this.closed) {\n try {\n const response = await this.request(\n streamUrl,\n {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body: JSON.stringify({\n channels: params.channels,\n ...(params.namespaces ? { namespaces: params.namespaces } : {}),\n ...(params.depth != null ? { depth: params.depth } : {}),\n ...(resumeAfterSeq != null ? { since: resumeAfterSeq } : {}),\n }),\n signal: ac.signal,\n },\n { stream: true }\n );\n\n if (!readySettled) {\n readySettled = true;\n resolveReady();\n }\n\n const readable =\n response.body ??\n new ReadableStream<Uint8Array>({\n start(controller) {\n controller.close();\n },\n });\n\n const stream = readable\n .pipeThrough(BytesLineDecoder())\n .pipeThrough(SSEDecoder());\n const iterable = IterableReadableStream.fromReadableStream(stream);\n\n for await (const event of iterable) {\n if (ac.signal.aborted || this.closed) {\n break;\n }\n if (isRecord(event.data)) {\n const msg = event.data as Message & {\n seq?: number;\n method?: string;\n };\n if (typeof msg.seq === \"number\") {\n resumeAfterSeq = msg.seq;\n }\n streamQueue.push(msg);\n }\n }\n streamQueue.close();\n return;\n } catch (error) {\n if (ac.signal.aborted || this.closed) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close();\n return;\n }\n if (this.maxReconnectAttempts <= 0) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close(toError(error));\n return;\n }\n attempt += 1;\n if (attempt > this.maxReconnectAttempts) {\n if (!readySettled) {\n rejectReady(error);\n }\n streamQueue.close(toError(error));\n return;\n }\n this.onReconnect?.({ attempt, cause: error });\n const delay = this.reconnectDelayMs(attempt);\n if (delay > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delay);\n });\n }\n }\n }\n };\n\n void startStream();\n\n const cleanup = () => {\n this.eventStreams.delete(ac);\n ac.abort();\n streamQueue.close();\n };\n\n return {\n events: {\n [Symbol.asyncIterator]: () => ({\n next: async () => await streamQueue.shift(),\n return: async () => {\n cleanup();\n return { done: true, value: undefined };\n },\n }),\n },\n ready,\n close: cleanup,\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n this.closed = true;\n this.sessionAbortController.abort();\n for (const ac of this.eventStreams) ac.abort();\n this.eventStreams.clear();\n this.queue.close();\n }\n\n private async request(\n path: string,\n init: RequestInit,\n options?: { stream?: boolean }\n ): Promise<Response> {\n const url = toAbsoluteUrl(this.apiUrl, path);\n let requestInit: RequestInit = {\n ...init,\n headers: mergeHeaders(this.defaultHeaders, init.headers),\n };\n\n if (this.onRequest) {\n requestInit = await this.onRequest(url, requestInit);\n }\n\n // Long-lived SSE event streams must not run through AsyncCaller: its\n // p-queue/p-retry semantics are designed for discrete request/response\n // calls, and wrapping a streaming response stalls the call (and can\n // leak retries). Stream resilience is handled separately by the\n // reconnect loop in `openEventStream`.\n const useAsyncCaller = this.asyncCaller != null && !options?.stream;\n\n const execute = async (): Promise<Response> => {\n const fetchImpl = await this.resolveFetch();\n const response = await fetchImpl(url.toString(), requestInit);\n if (!response.ok) {\n // Reject with the Response so AsyncCaller maps it to HTTPError and\n // applies STATUS_NO_RETRY / retry policy consistently with REST.\n if (useAsyncCaller) {\n throw response;\n }\n let detail = \"\";\n try {\n const body = await response.text();\n const parsed = JSON.parse(body);\n if (typeof parsed === \"object\" && parsed != null) {\n detail =\n ((parsed as Record<string, unknown>).message as string) ??\n ((parsed as Record<string, unknown>).error as string) ??\n \"\";\n }\n if (!detail) detail = body;\n } catch {\n // body unreadable or not JSON — fall through\n }\n const message = detail\n ? `Protocol request failed: ${response.status} ${response.statusText} — ${detail}`\n : `Protocol request failed: ${response.status} ${response.statusText}`;\n throw new Error(message);\n }\n return response;\n };\n\n try {\n return useAsyncCaller\n ? await this.asyncCaller!.call(execute)\n : await execute();\n } catch (error) {\n throw toError(error);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AAiCA,IAAa,8BAAb,MAAqE;CACnE;CAEA;CAEA,QAAyB,IAAI,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,yBAA0C,IAAI,iBAAiB;CAE/D,+BAAgC,IAAI,KAAsB;CAE1D,SAAiB;CAEjB,YAAY,SAAsC;AAChD,OAAK,YAAY,QAAQ,SAAS;AAClC,OAAK,SAAS,QAAQ;AACtB,OAAK,iBAAiB,QAAQ,kBAAkB,EAAE;AAClD,OAAK,YAAY,QAAQ;AACzB,OAAK,eAAe,QAAQ;AAC5B,OAAK,cAAc,QAAQ;AAE3B,OAAK,uBACH,QAAQ,SAAS,OAAO,IAAK,QAAQ,wBAAwB;AAC/D,OAAK,cAAc,QAAQ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AM,KAAK,aAAc,IAAG,OAAO;AAC9C,OAAK,aAAa,OAAO;AACzB,OAAK,MAAM,OAAO;;CAGpB,MAAc,QACZ,MACA,MACA,SACmB;EACnB,MAAM,MAAM,cAAc,KAAK,QAAQ,KAAK;EAC5C,IAAI,cAA2B;GAC7B,GAAG;GACH,SAAS,aAAa,KAAK,gBAAgB,KAAK,QAAQ;GACzD;AAED,MAAI,KAAK,UACP,eAAc,MAAM,KAAK,UAAU,KAAK,YAAY;EAQtD,MAAM,iBAAiB,KAAK,eAAe,QAAQ,CAAC,SAAS;EAE7D,MAAM,UAAU,YAA+B;GAE7C,MAAM,WAAW,OADC,MAAM,KAAK,cAAc,EACV,IAAI,UAAU,EAAE,YAAY;AAC7D,OAAI,CAAC,SAAS,IAAI;AAGhB,QAAI,eACF,OAAM;IAER,IAAI,SAAS;AACb,QAAI;KACF,MAAM,OAAO,MAAM,SAAS,MAAM;KAClC,MAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,SAAI,OAAO,WAAW,YAAY,UAAU,KAC1C,UACI,OAAmC,WACnC,OAAmC,SACrC;AAEJ,SAAI,CAAC,OAAQ,UAAS;YAChB;IAGR,MAAM,UAAU,SACZ,4BAA4B,SAAS,OAAO,GAAG,SAAS,WAAW,KAAK,WACxE,4BAA4B,SAAS,OAAO,GAAG,SAAS;AAC5D,UAAM,IAAI,MAAM,QAAQ;;AAE1B,UAAO;;AAGT,MAAI;AACF,UAAO,iBACH,MAAM,KAAK,YAAa,KAAK,QAAQ,GACrC,MAAM,SAAS;WACZ,OAAO;AACd,SAAM,QAAQ,MAAM"} |
@@ -0,3 +1,4 @@ | ||
| require("../error.cjs"); | ||
| require("./websocket.cjs"); | ||
| require("./http.cjs"); | ||
| require("./websocket.cjs"); | ||
| require("./agent-server.cjs"); |
@@ -0,4 +1,5 @@ | ||
| import "../error.js"; | ||
| import "./websocket.js"; | ||
| import "./http.js"; | ||
| import "./websocket.js"; | ||
| import "./agent-server.js"; | ||
| export {}; |
@@ -0,1 +1,2 @@ | ||
| import { AsyncCaller } from "../../../utils/async_caller.cjs"; | ||
| import { CommandResponse, ErrorResponse } from "@langchain/protocol"; | ||
@@ -18,3 +19,24 @@ | ||
| fetchFactory?: () => typeof fetch | Promise<typeof fetch>; | ||
| /** | ||
| * When set, command and SSE subscription HTTP requests are executed | ||
| * through {@link AsyncCaller} (retries, concurrency). Typically wired | ||
| * from {@link BaseClient} via `client.threads.stream()`. | ||
| */ | ||
| asyncCaller?: AsyncCaller; | ||
| paths?: ProtocolTransportPaths; | ||
| /** | ||
| * Maximum reconnect attempts after an unexpected SSE disconnect. | ||
| * Defaults to 5. Set to 0 to disable automatic reconnection. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** Called before each SSE reconnect attempt (after backoff delay). */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| /** | ||
| * Backoff before each SSE reconnect attempt. Defaults to | ||
| * {@link webSocketReconnectDelayMs} from `./websocket.js`. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| } | ||
@@ -28,2 +50,24 @@ interface ProtocolWebSocketTransportOptions { | ||
| paths?: Pick<ProtocolTransportPaths, "stream">; | ||
| /** | ||
| * Maximum reconnect attempts after an unexpected socket close. | ||
| * Defaults to 5. Set to 0 to disable automatic reconnection. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** | ||
| * Called before each reconnect attempt (after backoff delay). | ||
| */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| /** | ||
| * Invoked after the socket has been re-established. Use to restore | ||
| * server-side subscription state (see `ThreadStream`). | ||
| */ | ||
| onReconnected?: () => void | Promise<void>; | ||
| /** | ||
| * Backoff before each reconnect attempt. Defaults to | ||
| * {@link webSocketReconnectDelayMs}. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| } | ||
@@ -30,0 +74,0 @@ type HeaderValue = string | undefined | null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"types.d.cts","names":[],"sources":["../../../../src/client/stream/transport/types.ts"],"mappings":";;;KAEY,mBAAA,IACV,GAAA,EAAK,GAAA,EACL,IAAA,EAAM,WAAA,KACH,OAAA,CAAQ,WAAA,IAAe,WAAA;AAAA,UAEX,sBAAA;EACf,QAAA;EACA,MAAA;;EAEA,KAAA;AAAA;AAAA,UAGe,2BAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,KAAA,UAAe,KAAA;EACf,YAAA,gBAA4B,KAAA,GAAQ,OAAA,QAAe,KAAA;EACnD,KAAA,GAAQ,sBAAA;AAAA;AAAA,UAGO,iCAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,gBAAA,IAAoB,GAAA,aAAgB,SAAA;EACpC,KAAA,GAAQ,IAAA,CAAK,sBAAA;AAAA;AAAA,KAGH,WAAA"} | ||
| {"version":3,"file":"types.d.cts","names":[],"sources":["../../../../src/client/stream/transport/types.ts"],"mappings":";;;;KAGY,mBAAA,IACV,GAAA,EAAK,GAAA,EACL,IAAA,EAAM,WAAA,KACH,OAAA,CAAQ,WAAA,IAAe,WAAA;AAAA,UAEX,sBAAA;EACf,QAAA;EACA,MAAA;;EAEA,KAAA;AAAA;AAAA,UAGe,2BAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,KAAA,UAAe,KAAA;EACf,YAAA,gBAA4B,KAAA,GAAQ,OAAA,QAAe,KAAA;EAhB7C;;;;;EAsBN,WAAA,GAAc,WAAA;EACd,KAAA,GAAQ,sBAAA;EApBO;;;;EAyBf,oBAAA;EAvBA;EAyBA,WAAA,IAAe,OAAA;IAAW,OAAA;IAAiB,KAAA;EAAA;EApBD;;;;EAyB1C,gBAAA,IAAoB,OAAA;AAAA;AAAA,UAGL,iCAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,gBAAA,IAAoB,GAAA,aAAgB,SAAA;EACpC,KAAA,GAAQ,IAAA,CAAK,sBAAA;EAjCb;;;;EAsCA,oBAAA;EAnCA;;;EAuCA,WAAA,IAAe,OAAA;IAAW,OAAA;IAAiB,KAAA;EAAA;EArCQ;;;;EA0CnD,aAAA,gBAA6B,OAAA;EA9B7B;;;;EAmCA,gBAAA,IAAoB,OAAA;AAAA;AAAA,KAGV,WAAA"} |
@@ -0,1 +1,2 @@ | ||
| import { AsyncCaller } from "../../../utils/async_caller.js"; | ||
| import { CommandResponse, ErrorResponse } from "@langchain/protocol"; | ||
@@ -18,3 +19,24 @@ | ||
| fetchFactory?: () => typeof fetch | Promise<typeof fetch>; | ||
| /** | ||
| * When set, command and SSE subscription HTTP requests are executed | ||
| * through {@link AsyncCaller} (retries, concurrency). Typically wired | ||
| * from {@link BaseClient} via `client.threads.stream()`. | ||
| */ | ||
| asyncCaller?: AsyncCaller; | ||
| paths?: ProtocolTransportPaths; | ||
| /** | ||
| * Maximum reconnect attempts after an unexpected SSE disconnect. | ||
| * Defaults to 5. Set to 0 to disable automatic reconnection. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** Called before each SSE reconnect attempt (after backoff delay). */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| /** | ||
| * Backoff before each SSE reconnect attempt. Defaults to | ||
| * {@link webSocketReconnectDelayMs} from `./websocket.js`. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| } | ||
@@ -28,2 +50,24 @@ interface ProtocolWebSocketTransportOptions { | ||
| paths?: Pick<ProtocolTransportPaths, "stream">; | ||
| /** | ||
| * Maximum reconnect attempts after an unexpected socket close. | ||
| * Defaults to 5. Set to 0 to disable automatic reconnection. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** | ||
| * Called before each reconnect attempt (after backoff delay). | ||
| */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| /** | ||
| * Invoked after the socket has been re-established. Use to restore | ||
| * server-side subscription state (see `ThreadStream`). | ||
| */ | ||
| onReconnected?: () => void | Promise<void>; | ||
| /** | ||
| * Backoff before each reconnect attempt. Defaults to | ||
| * {@link webSocketReconnectDelayMs}. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| } | ||
@@ -30,0 +74,0 @@ type HeaderValue = string | undefined | null; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/client/stream/transport/types.ts"],"mappings":";;;KAEY,mBAAA,IACV,GAAA,EAAK,GAAA,EACL,IAAA,EAAM,WAAA,KACH,OAAA,CAAQ,WAAA,IAAe,WAAA;AAAA,UAEX,sBAAA;EACf,QAAA;EACA,MAAA;;EAEA,KAAA;AAAA;AAAA,UAGe,2BAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,KAAA,UAAe,KAAA;EACf,YAAA,gBAA4B,KAAA,GAAQ,OAAA,QAAe,KAAA;EACnD,KAAA,GAAQ,sBAAA;AAAA;AAAA,UAGO,iCAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,gBAAA,IAAoB,GAAA,aAAgB,SAAA;EACpC,KAAA,GAAQ,IAAA,CAAK,sBAAA;AAAA;AAAA,KAGH,WAAA"} | ||
| {"version":3,"file":"types.d.ts","names":[],"sources":["../../../../src/client/stream/transport/types.ts"],"mappings":";;;;KAGY,mBAAA,IACV,GAAA,EAAK,GAAA,EACL,IAAA,EAAM,WAAA,KACH,OAAA,CAAQ,WAAA,IAAe,WAAA;AAAA,UAEX,sBAAA;EACf,QAAA;EACA,MAAA;;EAEA,KAAA;AAAA;AAAA,UAGe,2BAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,KAAA,UAAe,KAAA;EACf,YAAA,gBAA4B,KAAA,GAAQ,OAAA,QAAe,KAAA;EAhB7C;;;;;EAsBN,WAAA,GAAc,WAAA;EACd,KAAA,GAAQ,sBAAA;EApBO;;;;EAyBf,oBAAA;EAvBA;EAyBA,WAAA,IAAe,OAAA;IAAW,OAAA;IAAiB,KAAA;EAAA;EApBD;;;;EAyB1C,gBAAA,IAAoB,OAAA;AAAA;AAAA,UAGL,iCAAA;EACf,MAAA;EACA,QAAA;EACA,cAAA,GAAiB,MAAA,SAAe,WAAA;EAChC,SAAA,GAAY,mBAAA;EACZ,gBAAA,IAAoB,GAAA,aAAgB,SAAA;EACpC,KAAA,GAAQ,IAAA,CAAK,sBAAA;EAjCb;;;;EAsCA,oBAAA;EAnCA;;;EAuCA,WAAA,IAAe,OAAA;IAAW,OAAA;IAAiB,KAAA;EAAA;EArCQ;;;;EA0CnD,aAAA,gBAA6B,OAAA;EA9B7B;;;;EAmCA,gBAAA,IAAoB,OAAA;AAAA;AAAA,KAGV,WAAA"} |
@@ -0,8 +1,26 @@ | ||
| const require_error = require("../error.cjs"); | ||
| const require_queue = require("./queue.cjs"); | ||
| const require_utils = require("./utils.cjs"); | ||
| //#region src/client/stream/transport/websocket.ts | ||
| const WEB_SOCKET_CONNECTING = 0; | ||
| const WEB_SOCKET_OPEN = 1; | ||
| const WEB_SOCKET_CLOSED = 3; | ||
| /** | ||
| * Exponential backoff with jitter for WebSocket reconnect. Mirrors | ||
| * {@link streamWithRetry} in `utils/stream.ts` (capped at 5s + 1s jitter). | ||
| */ | ||
| function webSocketReconnectDelayMs(attempt) { | ||
| return Math.min(1e3 * 2 ** (attempt - 1), 5e3) + Math.random() * 1e3; | ||
| } | ||
| /** | ||
| * Transport adapter that speaks the thread-centric protocol over a | ||
| * bidirectional WebSocket. Bound to a specific `threadId` — the socket | ||
| * connects to `ws://.../threads/:thread_id/stream/events`. | ||
| * | ||
| * On unexpected disconnect the adapter reconnects with exponential | ||
| * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}). | ||
| * The server replays buffered events on the new socket; the SDK | ||
| * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected} | ||
| * runs after each successful reconnect so `ThreadStream` can re-issue | ||
| * `subscription.subscribe` commands. | ||
| */ | ||
@@ -17,2 +35,6 @@ var ProtocolWebSocketTransportAdapter = class { | ||
| streamUrl; | ||
| maxReconnectAttempts; | ||
| onReconnect; | ||
| reconnectDelayMs; | ||
| onReconnected; | ||
| pending = /* @__PURE__ */ new Map(); | ||
@@ -22,2 +44,3 @@ socket = null; | ||
| intentionalClose = false; | ||
| reconnectInFlight = null; | ||
| constructor(options) { | ||
@@ -30,5 +53,22 @@ this.apiUrl = options.apiUrl; | ||
| this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; | ||
| this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5; | ||
| this.onReconnect = options.onReconnect; | ||
| this.onReconnected = options.onReconnected; | ||
| this.reconnectDelayMs = options.reconnectDelayMs ?? webSocketReconnectDelayMs; | ||
| } | ||
| /** | ||
| * Register a callback invoked after each successful reconnect. Used | ||
| * by {@link ThreadStream} to re-send active `subscription.subscribe` | ||
| * commands. | ||
| */ | ||
| setOnReconnected(handler) { | ||
| this.onReconnected = handler; | ||
| } | ||
| async open() { | ||
| if (this.socket != null) return; | ||
| if (this.closed) throw new Error("Protocol WebSocket transport is closed."); | ||
| if (this.socket?.readyState === WEB_SOCKET_OPEN) return; | ||
| if (this.socket != null) { | ||
| this.#detachSocket(this.socket); | ||
| this.socket = null; | ||
| } | ||
| this.assertBrowserSafeTransportConfig(); | ||
@@ -38,7 +78,4 @@ const wsUrl = require_utils.toWebSocketUrl(require_utils.toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()); | ||
| this.socket = socket; | ||
| this.closed = false; | ||
| this.intentionalClose = false; | ||
| socket.addEventListener("message", this.handleMessage); | ||
| socket.addEventListener("close", this.handleClose); | ||
| socket.addEventListener("error", this.handleSocketError); | ||
| this.#attachSocket(socket); | ||
| await new Promise((resolve, reject) => { | ||
@@ -87,4 +124,5 @@ const onOpen = () => { | ||
| if (!socket) return; | ||
| this.#detachSocket(socket); | ||
| await new Promise((resolve) => { | ||
| if (socket.readyState === WebSocket.CLOSED) { | ||
| if (socket.readyState === WEB_SOCKET_CLOSED) { | ||
| resolve(); | ||
@@ -98,3 +136,3 @@ return; | ||
| socket.addEventListener("close", onClose, { once: true }); | ||
| if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close(); | ||
| if (socket.readyState === WEB_SOCKET_OPEN || socket.readyState === WEB_SOCKET_CONNECTING) socket.close(); | ||
| else resolve(); | ||
@@ -107,4 +145,8 @@ }); | ||
| async sendCommand(command) { | ||
| const socket = this.socket; | ||
| if (socket == null || socket.readyState !== WebSocket.OPEN) throw new Error("Protocol WebSocket is not open."); | ||
| let socket = this.socket; | ||
| if (this.reconnectInFlight != null && (socket == null || socket.readyState !== WEB_SOCKET_OPEN)) { | ||
| await this.reconnectInFlight.catch(() => void 0); | ||
| socket = this.socket; | ||
| } | ||
| if (socket == null || socket.readyState !== WEB_SOCKET_OPEN) throw new Error("Protocol WebSocket is not open."); | ||
| return await new Promise((resolve, reject) => { | ||
@@ -123,2 +165,12 @@ this.pending.set(command.id, { | ||
| } | ||
| #attachSocket(socket) { | ||
| socket.addEventListener("message", this.handleMessage); | ||
| socket.addEventListener("close", this.handleClose); | ||
| socket.addEventListener("error", this.handleSocketError); | ||
| } | ||
| #detachSocket(socket) { | ||
| socket.removeEventListener("message", this.handleMessage); | ||
| socket.removeEventListener("close", this.handleClose); | ||
| socket.removeEventListener("error", this.handleSocketError); | ||
| } | ||
| handleMessage = (event) => { | ||
@@ -142,2 +194,4 @@ let payload; | ||
| handleClose = () => { | ||
| const socket = this.socket; | ||
| if (socket != null) this.#detachSocket(socket); | ||
| this.socket = null; | ||
@@ -148,18 +202,53 @@ if (this.intentionalClose || this.closed) { | ||
| } | ||
| const error = /* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly."); | ||
| for (const { reject } of this.pending.values()) reject(error); | ||
| this.pending.clear(); | ||
| this.queue.close(error); | ||
| this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly.")); | ||
| }; | ||
| handleSocketError = () => { | ||
| if (this.closed || this.intentionalClose) return; | ||
| const error = /* @__PURE__ */ new Error("Protocol WebSocket encountered an error."); | ||
| this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket encountered an error.")); | ||
| }; | ||
| #handleUnexpectedDisconnect(cause) { | ||
| const error = require_utils.toError(cause); | ||
| for (const { reject } of this.pending.values()) reject(error); | ||
| this.pending.clear(); | ||
| this.queue.close(error); | ||
| }; | ||
| if (this.maxReconnectAttempts <= 0) { | ||
| this.queue.close(error); | ||
| return; | ||
| } | ||
| this.#scheduleReconnect(cause); | ||
| } | ||
| #scheduleReconnect(cause) { | ||
| if (this.closed || this.intentionalClose) return; | ||
| if (this.reconnectInFlight != null) return; | ||
| this.reconnectInFlight = this.#runReconnectLoop(cause).finally(() => { | ||
| this.reconnectInFlight = null; | ||
| }); | ||
| } | ||
| async #runReconnectLoop(initialCause) { | ||
| let lastError = initialCause; | ||
| for (let attempt = 1; attempt <= this.maxReconnectAttempts; attempt += 1) { | ||
| if (this.closed || this.intentionalClose) return; | ||
| this.onReconnect?.({ | ||
| attempt, | ||
| cause: lastError | ||
| }); | ||
| const delay = this.reconnectDelayMs(attempt); | ||
| if (delay > 0) await new Promise((resolve) => { | ||
| setTimeout(resolve, delay); | ||
| }); | ||
| if (this.closed || this.intentionalClose) return; | ||
| try { | ||
| await this.open(); | ||
| if (this.onReconnected) await this.onReconnected(); | ||
| return; | ||
| } catch (error) { | ||
| lastError = error; | ||
| } | ||
| } | ||
| this.queue.close(new require_error.MaxWebSocketReconnectAttemptsError(this.maxReconnectAttempts, lastError)); | ||
| } | ||
| }; | ||
| //#endregion | ||
| exports.ProtocolWebSocketTransportAdapter = ProtocolWebSocketTransportAdapter; | ||
| exports.webSocketReconnectDelayMs = webSocketReconnectDelayMs; | ||
| //# sourceMappingURL=websocket.cjs.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"websocket.cjs","names":["AsyncQueue","toWebSocketUrl","toAbsoluteUrl","hasHeaders","toError","isRecord"],"sources":["../../../../src/client/stream/transport/websocket.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport {\n toAbsoluteUrl,\n toWebSocketUrl,\n isRecord,\n hasHeaders,\n toError,\n} from \"./utils.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n PendingResponse,\n ProtocolWebSocketTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter } from \"../transport.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over a\n * bidirectional WebSocket. Bound to a specific `threadId` — the socket\n * connects to `ws://.../threads/:thread_id/stream/events`.\n */\nexport class ProtocolWebSocketTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly apiUrl: string;\n\n private readonly defaultHeaders?: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly webSocketFactory: (url: string) => WebSocket;\n\n private readonly streamUrl: string;\n\n private readonly pending = new Map<number, PendingResponse>();\n\n private socket: WebSocket | null = null;\n\n private closed = false;\n\n private intentionalClose = false;\n\n constructor(options: ProtocolWebSocketTransportOptions) {\n this.apiUrl = options.apiUrl;\n this.threadId = options.threadId;\n this.defaultHeaders = options.defaultHeaders;\n this.onRequest = options.onRequest;\n this.webSocketFactory =\n options.webSocketFactory ?? ((url) => new WebSocket(url));\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n }\n\n async open(): Promise<void> {\n if (this.socket != null) return;\n this.assertBrowserSafeTransportConfig();\n\n const wsUrl = toWebSocketUrl(\n toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()\n );\n const socket = this.webSocketFactory(wsUrl);\n this.socket = socket;\n this.closed = false;\n this.intentionalClose = false;\n\n socket.addEventListener(\"message\", this.handleMessage);\n socket.addEventListener(\"close\", this.handleClose);\n socket.addEventListener(\"error\", this.handleSocketError);\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onError = () => {\n cleanup();\n reject(new Error(\"Failed to open protocol WebSocket.\"));\n };\n const cleanup = () => {\n socket.removeEventListener(\"open\", onOpen);\n socket.removeEventListener(\"error\", onError);\n };\n socket.addEventListener(\"open\", onOpen, { once: true });\n socket.addEventListener(\"error\", onError, { once: true });\n });\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n return await this.sendCommand(command);\n }\n\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.intentionalClose = true;\n\n for (const { reject } of this.pending.values()) {\n reject(new Error(\"Protocol WebSocket connection closed.\"));\n }\n this.pending.clear();\n this.queue.close();\n\n const socket = this.socket;\n this.socket = null;\n if (!socket) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n if (socket.readyState === WebSocket.CLOSED) {\n resolve();\n return;\n }\n\n const onClose = () => {\n socket.removeEventListener(\"close\", onClose);\n resolve();\n };\n\n socket.addEventListener(\"close\", onClose, { once: true });\n if (\n socket.readyState === WebSocket.OPEN ||\n socket.readyState === WebSocket.CONNECTING\n ) {\n socket.close();\n } else {\n resolve();\n }\n });\n }\n\n private assertBrowserSafeTransportConfig(): void {\n if (hasHeaders(this.defaultHeaders) || this.onRequest != null) {\n throw new Error(\n \"Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup.\"\n );\n }\n }\n\n private async sendCommand(\n command: Command\n ): Promise<CommandResponse | ErrorResponse> {\n const socket = this.socket;\n if (socket == null || socket.readyState !== WebSocket.OPEN) {\n throw new Error(\"Protocol WebSocket is not open.\");\n }\n\n return await new Promise<CommandResponse | ErrorResponse>(\n (resolve, reject) => {\n this.pending.set(command.id, { resolve, reject });\n\n try {\n socket.send(JSON.stringify(command));\n } catch (error) {\n this.pending.delete(command.id);\n reject(toError(error));\n }\n }\n );\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n let payload: unknown;\n try {\n payload = JSON.parse(String(event.data));\n } catch {\n return;\n }\n\n if (\n isRecord(payload) &&\n typeof payload.id === \"number\" &&\n (payload.type === \"success\" || payload.type === \"error\")\n ) {\n const pending = this.pending.get(payload.id);\n if (pending) {\n this.pending.delete(payload.id);\n pending.resolve(payload as CommandResponse | ErrorResponse);\n }\n return;\n }\n\n if (isRecord(payload) && payload.type === \"event\") {\n this.queue.push(payload as Message);\n }\n };\n\n private readonly handleClose = (): void => {\n this.socket = null;\n\n if (this.intentionalClose || this.closed) {\n this.queue.close();\n return;\n }\n\n const error = new Error(\"Protocol WebSocket closed unexpectedly.\");\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n this.queue.close(error);\n };\n\n private readonly handleSocketError = (): void => {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n const error = new Error(\"Protocol WebSocket encountered an error.\");\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n this.queue.close(error);\n };\n}\n"],"mappings":";;;;;;;;AA4BA,IAAa,oCAAb,MAA2E;CACzE;CAEA,QAA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AGH,iBAAkC,UAA8B;EAC9D,IAAI;AACJ,MAAI;AACF,aAAU,KAAK,MAAM,OAAO,MAAM,KAAK,CAAC;UAClC;AACN;;AAGF,MACEC,cAAAA,SAAS,QAAQ,IACjB,OAAO,QAAQ,OAAO,aACrB,QAAQ,SAAS,aAAa,QAAQ,SAAS,UAChD;GACA,MAAM,UAAU,KAAK,QAAQ,IAAI,QAAQ,GAAG;AAC5C,OAAI,SAAS;AACX,SAAK,QAAQ,OAAO,QAAQ,GAAG;AAC/B,YAAQ,QAAQ,QAA2C;;AAE7D;;AAGF,MAAIA,cAAAA,SAAS,QAAQ,IAAI,QAAQ,SAAS,QACxC,MAAK,MAAM,KAAK,QAAmB;;CAIvC,oBAA2C;AACzC,OAAK,SAAS;AAEd,MAAI,KAAK,oBAAoB,KAAK,QAAQ;AACxC,QAAK,MAAM,OAAO;AAClB;;EAGF,MAAM,wBAAQ,IAAI,MAAM,0CAA0C;AAClE,OAAK,MAAM,EAAE,YAAY,KAAK,QAAQ,QAAQ,CAC5C,QAAO,MAAM;AAEf,OAAK,QAAQ,OAAO;AACpB,OAAK,MAAM,MAAM,MAAM;;CAGzB,0BAAiD;AAC/C,MAAI,KAAK,UAAU,KAAK,iBACtB;EAGF,MAAM,wBAAQ,IAAI,MAAM,2CAA2C;AACnE,OAAK,MAAM,EAAE,YAAY,KAAK,QAAQ,QAAQ,CAC5C,QAAO,MAAM;AAEf,OAAK,QAAQ,OAAO;AACpB,OAAK,MAAM,MAAM,MAAM"} | ||
| {"version":3,"file":"websocket.cjs","names":["AsyncQueue","#detachSocket","toWebSocketUrl","toAbsoluteUrl","#attachSocket","hasHeaders","toError","isRecord","#handleUnexpectedDisconnect","#scheduleReconnect","#runReconnectLoop","MaxWebSocketReconnectAttemptsError"],"sources":["../../../../src/client/stream/transport/websocket.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport {\n toAbsoluteUrl,\n toWebSocketUrl,\n isRecord,\n hasHeaders,\n toError,\n} from \"./utils.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n PendingResponse,\n ProtocolWebSocketTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter } from \"../transport.js\";\nimport { MaxWebSocketReconnectAttemptsError } from \"../error.js\";\n\nconst WEB_SOCKET_CONNECTING = 0;\nconst WEB_SOCKET_OPEN = 1;\nconst WEB_SOCKET_CLOSED = 3;\n\n/**\n * Reconnect tuning for {@link ProtocolWebSocketTransportAdapter}. A subset\n * of {@link ProtocolWebSocketTransportOptions}.\n */\nexport interface WebSocketReconnectOptions {\n /**\n * Maximum reconnection attempts after an unexpected disconnect.\n * Defaults to 5.\n */\n maxReconnectAttempts?: number;\n\n /**\n * Invoked before each reconnect attempt (after backoff).\n */\n onReconnect?: (options: { attempt: number; cause: unknown }) => void;\n}\n\n/**\n * Exponential backoff with jitter for WebSocket reconnect. Mirrors\n * {@link streamWithRetry} in `utils/stream.ts` (capped at 5s + 1s jitter).\n */\nexport function webSocketReconnectDelayMs(attempt: number): number {\n const baseDelay = Math.min(1000 * 2 ** (attempt - 1), 5000);\n const jitter = Math.random() * 1000;\n return baseDelay + jitter;\n}\n\n/**\n * Transport adapter that speaks the thread-centric protocol over a\n * bidirectional WebSocket. Bound to a specific `threadId` — the socket\n * connects to `ws://.../threads/:thread_id/stream/events`.\n *\n * On unexpected disconnect the adapter reconnects with exponential\n * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}).\n * The server replays buffered events on the new socket; the SDK\n * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected}\n * runs after each successful reconnect so `ThreadStream` can re-issue\n * `subscription.subscribe` commands.\n */\nexport class ProtocolWebSocketTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly apiUrl: string;\n\n private readonly defaultHeaders?: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly webSocketFactory: (url: string) => WebSocket;\n\n private readonly streamUrl: string;\n\n private readonly maxReconnectAttempts: number;\n\n private readonly onReconnect?: ProtocolWebSocketTransportOptions[\"onReconnect\"];\n\n private readonly reconnectDelayMs: (attempt: number) => number;\n\n private onReconnected?: () => void | Promise<void>;\n\n private readonly pending = new Map<number, PendingResponse>();\n\n private socket: WebSocket | null = null;\n\n private closed = false;\n\n private intentionalClose = false;\n\n private reconnectInFlight: Promise<void> | null = null;\n\n constructor(options: ProtocolWebSocketTransportOptions) {\n this.apiUrl = options.apiUrl;\n this.threadId = options.threadId;\n this.defaultHeaders = options.defaultHeaders;\n this.onRequest = options.onRequest;\n this.webSocketFactory =\n options.webSocketFactory ?? ((url) => new WebSocket(url));\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n this.onReconnect = options.onReconnect;\n this.onReconnected = options.onReconnected;\n this.reconnectDelayMs =\n options.reconnectDelayMs ?? webSocketReconnectDelayMs;\n }\n\n /**\n * Register a callback invoked after each successful reconnect. Used\n * by {@link ThreadStream} to re-send active `subscription.subscribe`\n * commands.\n */\n setOnReconnected(handler: () => void | Promise<void>): void {\n this.onReconnected = handler;\n }\n\n async open(): Promise<void> {\n if (this.closed) {\n throw new Error(\"Protocol WebSocket transport is closed.\");\n }\n if (this.socket?.readyState === WEB_SOCKET_OPEN) {\n return;\n }\n if (this.socket != null) {\n this.#detachSocket(this.socket);\n this.socket = null;\n }\n\n this.assertBrowserSafeTransportConfig();\n\n const wsUrl = toWebSocketUrl(\n toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()\n );\n const socket = this.webSocketFactory(wsUrl);\n this.socket = socket;\n this.intentionalClose = false;\n\n this.#attachSocket(socket);\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onError = () => {\n cleanup();\n reject(new Error(\"Failed to open protocol WebSocket.\"));\n };\n const cleanup = () => {\n socket.removeEventListener(\"open\", onOpen);\n socket.removeEventListener(\"error\", onError);\n };\n socket.addEventListener(\"open\", onOpen, { once: true });\n socket.addEventListener(\"error\", onError, { once: true });\n });\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n return await this.sendCommand(command);\n }\n\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.intentionalClose = true;\n\n for (const { reject } of this.pending.values()) {\n reject(new Error(\"Protocol WebSocket connection closed.\"));\n }\n this.pending.clear();\n this.queue.close();\n\n const socket = this.socket;\n this.socket = null;\n if (!socket) {\n return;\n }\n\n this.#detachSocket(socket);\n\n await new Promise<void>((resolve) => {\n if (socket.readyState === WEB_SOCKET_CLOSED) {\n resolve();\n return;\n }\n\n const onClose = () => {\n socket.removeEventListener(\"close\", onClose);\n resolve();\n };\n\n socket.addEventListener(\"close\", onClose, { once: true });\n if (\n socket.readyState === WEB_SOCKET_OPEN ||\n socket.readyState === WEB_SOCKET_CONNECTING\n ) {\n socket.close();\n } else {\n resolve();\n }\n });\n }\n\n private assertBrowserSafeTransportConfig(): void {\n if (hasHeaders(this.defaultHeaders) || this.onRequest != null) {\n throw new Error(\n \"Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup.\"\n );\n }\n }\n\n private async sendCommand(\n command: Command\n ): Promise<CommandResponse | ErrorResponse> {\n // Wait for an in-flight reconnect only when the socket is not usable.\n // After `open()` succeeds, `#runReconnectLoop` may still be awaiting\n // `onReconnected` (e.g. ThreadStream resubscribe). Those callbacks call\n // `sendCommand` and must not await the same `reconnectInFlight` promise.\n let socket = this.socket;\n if (\n this.reconnectInFlight != null &&\n (socket == null || socket.readyState !== WEB_SOCKET_OPEN)\n ) {\n await this.reconnectInFlight.catch(() => undefined);\n socket = this.socket;\n }\n\n if (socket == null || socket.readyState !== WEB_SOCKET_OPEN) {\n throw new Error(\"Protocol WebSocket is not open.\");\n }\n\n return await new Promise<CommandResponse | ErrorResponse>(\n (resolve, reject) => {\n this.pending.set(command.id, { resolve, reject });\n\n try {\n socket.send(JSON.stringify(command));\n } catch (error) {\n this.pending.delete(command.id);\n reject(toError(error));\n }\n }\n );\n }\n\n #attachSocket(socket: WebSocket): void {\n socket.addEventListener(\"message\", this.handleMessage);\n socket.addEventListener(\"close\", this.handleClose);\n socket.addEventListener(\"error\", this.handleSocketError);\n }\n\n #detachSocket(socket: WebSocket): void {\n socket.removeEventListener(\"message\", this.handleMessage);\n socket.removeEventListener(\"close\", this.handleClose);\n socket.removeEventListener(\"error\", this.handleSocketError);\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n let payload: unknown;\n try {\n payload = JSON.parse(String(event.data));\n } catch {\n return;\n }\n\n if (\n isRecord(payload) &&\n typeof payload.id === \"number\" &&\n (payload.type === \"success\" || payload.type === \"error\")\n ) {\n const pending = this.pending.get(payload.id);\n if (pending) {\n this.pending.delete(payload.id);\n pending.resolve(payload as CommandResponse | ErrorResponse);\n }\n return;\n }\n\n if (isRecord(payload) && payload.type === \"event\") {\n this.queue.push(payload as Message);\n }\n };\n\n private readonly handleClose = (): void => {\n const socket = this.socket;\n if (socket != null) {\n this.#detachSocket(socket);\n }\n this.socket = null;\n\n if (this.intentionalClose || this.closed) {\n this.queue.close();\n return;\n }\n\n this.#handleUnexpectedDisconnect(\n new Error(\"Protocol WebSocket closed unexpectedly.\")\n );\n };\n\n private readonly handleSocketError = (): void => {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n this.#handleUnexpectedDisconnect(\n new Error(\"Protocol WebSocket encountered an error.\")\n );\n };\n\n #handleUnexpectedDisconnect(cause: unknown): void {\n const error = toError(cause);\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n\n if (this.maxReconnectAttempts <= 0) {\n this.queue.close(error);\n return;\n }\n\n this.#scheduleReconnect(cause);\n }\n\n #scheduleReconnect(cause: unknown): void {\n if (this.closed || this.intentionalClose) {\n return;\n }\n if (this.reconnectInFlight != null) {\n return;\n }\n\n this.reconnectInFlight = this.#runReconnectLoop(cause).finally(() => {\n this.reconnectInFlight = null;\n });\n }\n\n async #runReconnectLoop(initialCause: unknown): Promise<void> {\n let lastError: unknown = initialCause;\n\n for (let attempt = 1; attempt <= this.maxReconnectAttempts; attempt += 1) {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n this.onReconnect?.({ attempt, cause: lastError });\n\n const delay = this.reconnectDelayMs(attempt);\n if (delay > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delay);\n });\n }\n\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n try {\n await this.open();\n if (this.onReconnected) {\n await this.onReconnected();\n }\n return;\n } catch (error) {\n lastError = error;\n }\n }\n\n this.queue.close(\n new MaxWebSocketReconnectAttemptsError(\n this.maxReconnectAttempts,\n lastError\n )\n );\n }\n}\n"],"mappings":";;;;AAwBA,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;;;;;AAuB1B,SAAgB,0BAA0B,SAAyB;AAGjE,QAFkB,KAAK,IAAI,MAAO,MAAM,UAAU,IAAI,IAAK,GAC5C,KAAK,QAAQ,GAAG;;;;;;;;;;;;;;AAgBjC,IAAa,oCAAb,MAA2E;CACzE;CAEA,QAAyB,IAAIA,cAAAA,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,0BAA2B,IAAI,KAA8B;CAE7D,SAAmC;CAEnC,SAAiB;CAEjB,mBAA2B;CAE3B,oBAAkD;CAElD,YAAY,SAA4C;AACtD,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,QAAQ;AACxB,OAAK,iBA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C5B,OAAK,MAAM,EAAE,YAAY,KAAK,QAAQ,QAAQ,CAC5C,QAAO,MAAM;AAEf,OAAK,QAAQ,OAAO;AAEpB,MAAI,KAAK,wBAAwB,GAAG;AAClC,QAAK,MAAM,MAAM,MAAM;AACvB;;AAGF,QAAA,kBAAwB,MAAM;;CAGhC,mBAAmB,OAAsB;AACvC,MAAI,KAAK,UAAU,KAAK,iBACtB;AAEF,MAAI,KAAK,qBAAqB,KAC5B;AAGF,OAAK,oBAAoB,MAAA,iBAAuB,MAAM,CAAC,cAAc;AACnE,QAAK,oBAAoB;IACzB;;CAGJ,OAAA,iBAAwB,cAAsC;EAC5D,IAAI,YAAqB;AAEzB,OAAK,IAAI,UAAU,GAAG,WAAW,KAAK,sBAAsB,WAAW,GAAG;AACxE,OAAI,KAAK,UAAU,KAAK,iBACtB;AAGF,QAAK,cAAc;IAAE;IAAS,OAAO;IAAW,CAAC;GAEjD,MAAM,QAAQ,KAAK,iBAAiB,QAAQ;AAC5C,OAAI,QAAQ,EACV,OAAM,IAAI,SAAe,YAAY;AACnC,eAAW,SAAS,MAAM;KAC1B;AAGJ,OAAI,KAAK,UAAU,KAAK,iBACtB;AAGF,OAAI;AACF,UAAM,KAAK,MAAM;AACjB,QAAI,KAAK,cACP,OAAM,KAAK,eAAe;AAE5B;YACO,OAAO;AACd,gBAAY;;;AAIhB,OAAK,MAAM,MACT,IAAIK,cAAAA,mCACF,KAAK,sBACL,UACD,CACF"} |
@@ -10,4 +10,12 @@ import { TransportAdapter } from "../transport.cjs"; | ||
| * connects to `ws://.../threads/:thread_id/stream/events`. | ||
| * | ||
| * On unexpected disconnect the adapter reconnects with exponential | ||
| * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}). | ||
| * The server replays buffered events on the new socket; the SDK | ||
| * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected} | ||
| * runs after each successful reconnect so `ThreadStream` can re-issue | ||
| * `subscription.subscribe` commands. | ||
| */ | ||
| declare class ProtocolWebSocketTransportAdapter implements TransportAdapter { | ||
| #private; | ||
| readonly threadId: string; | ||
@@ -20,2 +28,6 @@ private readonly queue; | ||
| private readonly streamUrl; | ||
| private readonly maxReconnectAttempts; | ||
| private readonly onReconnect?; | ||
| private readonly reconnectDelayMs; | ||
| private onReconnected?; | ||
| private readonly pending; | ||
@@ -25,3 +37,10 @@ private socket; | ||
| private intentionalClose; | ||
| private reconnectInFlight; | ||
| constructor(options: ProtocolWebSocketTransportOptions); | ||
| /** | ||
| * Register a callback invoked after each successful reconnect. Used | ||
| * by {@link ThreadStream} to re-send active `subscription.subscribe` | ||
| * commands. | ||
| */ | ||
| setOnReconnected(handler: () => void | Promise<void>): void; | ||
| open(): Promise<void>; | ||
@@ -28,0 +47,0 @@ send(command: Command): Promise<CommandResponse | ErrorResponse | void>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"websocket.d.cts","names":[],"sources":["../../../../src/client/stream/transport/websocket.ts"],"mappings":";;;;;;;AA4BA;;;cAAa,iCAAA,YAA6C,gBAAA;EAAA,SAC/C,QAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,MAAA;EAAA,iBAEA,cAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,gBAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,OAAA;EAAA,QAET,MAAA;EAAA,QAEA,MAAA;EAAA,QAEA,gBAAA;EAER,WAAA,CAAY,OAAA,EAAS,iCAAA;EAWf,IAAA,CAAA,GAAQ,OAAA;EAkCR,IAAA,CACJ,OAAA,EAAS,OAAA,GACR,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAI7B,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAalB,KAAA,CAAA,GAAS,OAAA;EAAA,QA2CP,gCAAA;EAAA,QAQM,WAAA;EAAA,iBAsBG,aAAA;EAAA,iBA0BA,WAAA;EAAA,iBAgBA,iBAAA;AAAA"} | ||
| {"version":3,"file":"websocket.d.cts","names":[],"sources":["../../../../src/client/stream/transport/websocket.ts"],"mappings":";;;;;;;;;;;;;;;;;cAmEa,iCAAA,YAA6C,gBAAA;EAAA;WAC/C,QAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,MAAA;EAAA,iBAEA,cAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,gBAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,oBAAA;EAAA,iBAEA,WAAA;EAAA,iBAEA,gBAAA;EAAA,QAET,aAAA;EAAA,iBAES,OAAA;EAAA,QAET,MAAA;EAAA,QAEA,MAAA;EAAA,QAEA,gBAAA;EAAA,QAEA,iBAAA;EAER,WAAA,CAAY,OAAA,EAAS,iCAAA;EAqFN;;;;;EAhEf,gBAAA,CAAiB,OAAA,eAAsB,OAAA;EAIjC,IAAA,CAAA,GAAQ,OAAA;EAyCR,IAAA,CACJ,OAAA,EAAS,OAAA,GACR,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAI7B,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAalB,KAAA,CAAA,GAAS,OAAA;EAAA,QA6CP,gCAAA;EAAA,QAQM,WAAA;EAAA,iBA8CG,aAAA;EAAA,iBA0BA,WAAA;EAAA,iBAiBA,iBAAA;AAAA"} |
@@ -10,4 +10,12 @@ import { TransportAdapter } from "../transport.js"; | ||
| * connects to `ws://.../threads/:thread_id/stream/events`. | ||
| * | ||
| * On unexpected disconnect the adapter reconnects with exponential | ||
| * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}). | ||
| * The server replays buffered events on the new socket; the SDK | ||
| * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected} | ||
| * runs after each successful reconnect so `ThreadStream` can re-issue | ||
| * `subscription.subscribe` commands. | ||
| */ | ||
| declare class ProtocolWebSocketTransportAdapter implements TransportAdapter { | ||
| #private; | ||
| readonly threadId: string; | ||
@@ -20,2 +28,6 @@ private readonly queue; | ||
| private readonly streamUrl; | ||
| private readonly maxReconnectAttempts; | ||
| private readonly onReconnect?; | ||
| private readonly reconnectDelayMs; | ||
| private onReconnected?; | ||
| private readonly pending; | ||
@@ -25,3 +37,10 @@ private socket; | ||
| private intentionalClose; | ||
| private reconnectInFlight; | ||
| constructor(options: ProtocolWebSocketTransportOptions); | ||
| /** | ||
| * Register a callback invoked after each successful reconnect. Used | ||
| * by {@link ThreadStream} to re-send active `subscription.subscribe` | ||
| * commands. | ||
| */ | ||
| setOnReconnected(handler: () => void | Promise<void>): void; | ||
| open(): Promise<void>; | ||
@@ -28,0 +47,0 @@ send(command: Command): Promise<CommandResponse | ErrorResponse | void>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"websocket.d.ts","names":[],"sources":["../../../../src/client/stream/transport/websocket.ts"],"mappings":";;;;;;;AA4BA;;;cAAa,iCAAA,YAA6C,gBAAA;EAAA,SAC/C,QAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,MAAA;EAAA,iBAEA,cAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,gBAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,OAAA;EAAA,QAET,MAAA;EAAA,QAEA,MAAA;EAAA,QAEA,gBAAA;EAER,WAAA,CAAY,OAAA,EAAS,iCAAA;EAWf,IAAA,CAAA,GAAQ,OAAA;EAkCR,IAAA,CACJ,OAAA,EAAS,OAAA,GACR,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAI7B,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAalB,KAAA,CAAA,GAAS,OAAA;EAAA,QA2CP,gCAAA;EAAA,QAQM,WAAA;EAAA,iBAsBG,aAAA;EAAA,iBA0BA,WAAA;EAAA,iBAgBA,iBAAA;AAAA"} | ||
| {"version":3,"file":"websocket.d.ts","names":[],"sources":["../../../../src/client/stream/transport/websocket.ts"],"mappings":";;;;;;;;;;;;;;;;;cAmEa,iCAAA,YAA6C,gBAAA;EAAA;WAC/C,QAAA;EAAA,iBAEQ,KAAA;EAAA,iBAEA,MAAA;EAAA,iBAEA,cAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,gBAAA;EAAA,iBAEA,SAAA;EAAA,iBAEA,oBAAA;EAAA,iBAEA,WAAA;EAAA,iBAEA,gBAAA;EAAA,QAET,aAAA;EAAA,iBAES,OAAA;EAAA,QAET,MAAA;EAAA,QAEA,MAAA;EAAA,QAEA,gBAAA;EAAA,QAEA,iBAAA;EAER,WAAA,CAAY,OAAA,EAAS,iCAAA;EAqFN;;;;;EAhEf,gBAAA,CAAiB,OAAA,eAAsB,OAAA;EAIjC,IAAA,CAAA,GAAQ,OAAA;EAyCR,IAAA,CACJ,OAAA,EAAS,OAAA,GACR,OAAA,CAAQ,eAAA,GAAkB,aAAA;EAI7B,MAAA,CAAA,GAAU,aAAA,CAAc,OAAA;EAalB,KAAA,CAAA,GAAS,OAAA;EAAA,QA6CP,gCAAA;EAAA,QAQM,WAAA;EAAA,iBA8CG,aAAA;EAAA,iBA0BA,WAAA;EAAA,iBAiBA,iBAAA;AAAA"} |
@@ -0,8 +1,26 @@ | ||
| import { MaxWebSocketReconnectAttemptsError } from "../error.js"; | ||
| import { AsyncQueue } from "./queue.js"; | ||
| import { hasHeaders, isRecord, toAbsoluteUrl, toError, toWebSocketUrl } from "./utils.js"; | ||
| //#region src/client/stream/transport/websocket.ts | ||
| const WEB_SOCKET_CONNECTING = 0; | ||
| const WEB_SOCKET_OPEN = 1; | ||
| const WEB_SOCKET_CLOSED = 3; | ||
| /** | ||
| * Exponential backoff with jitter for WebSocket reconnect. Mirrors | ||
| * {@link streamWithRetry} in `utils/stream.ts` (capped at 5s + 1s jitter). | ||
| */ | ||
| function webSocketReconnectDelayMs(attempt) { | ||
| return Math.min(1e3 * 2 ** (attempt - 1), 5e3) + Math.random() * 1e3; | ||
| } | ||
| /** | ||
| * Transport adapter that speaks the thread-centric protocol over a | ||
| * bidirectional WebSocket. Bound to a specific `threadId` — the socket | ||
| * connects to `ws://.../threads/:thread_id/stream/events`. | ||
| * | ||
| * On unexpected disconnect the adapter reconnects with exponential | ||
| * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}). | ||
| * The server replays buffered events on the new socket; the SDK | ||
| * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected} | ||
| * runs after each successful reconnect so `ThreadStream` can re-issue | ||
| * `subscription.subscribe` commands. | ||
| */ | ||
@@ -17,2 +35,6 @@ var ProtocolWebSocketTransportAdapter = class { | ||
| streamUrl; | ||
| maxReconnectAttempts; | ||
| onReconnect; | ||
| reconnectDelayMs; | ||
| onReconnected; | ||
| pending = /* @__PURE__ */ new Map(); | ||
@@ -22,2 +44,3 @@ socket = null; | ||
| intentionalClose = false; | ||
| reconnectInFlight = null; | ||
| constructor(options) { | ||
@@ -30,5 +53,22 @@ this.apiUrl = options.apiUrl; | ||
| this.streamUrl = options.paths?.stream ?? `/threads/${this.threadId}/stream/events`; | ||
| this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5; | ||
| this.onReconnect = options.onReconnect; | ||
| this.onReconnected = options.onReconnected; | ||
| this.reconnectDelayMs = options.reconnectDelayMs ?? webSocketReconnectDelayMs; | ||
| } | ||
| /** | ||
| * Register a callback invoked after each successful reconnect. Used | ||
| * by {@link ThreadStream} to re-send active `subscription.subscribe` | ||
| * commands. | ||
| */ | ||
| setOnReconnected(handler) { | ||
| this.onReconnected = handler; | ||
| } | ||
| async open() { | ||
| if (this.socket != null) return; | ||
| if (this.closed) throw new Error("Protocol WebSocket transport is closed."); | ||
| if (this.socket?.readyState === WEB_SOCKET_OPEN) return; | ||
| if (this.socket != null) { | ||
| this.#detachSocket(this.socket); | ||
| this.socket = null; | ||
| } | ||
| this.assertBrowserSafeTransportConfig(); | ||
@@ -38,7 +78,4 @@ const wsUrl = toWebSocketUrl(toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()); | ||
| this.socket = socket; | ||
| this.closed = false; | ||
| this.intentionalClose = false; | ||
| socket.addEventListener("message", this.handleMessage); | ||
| socket.addEventListener("close", this.handleClose); | ||
| socket.addEventListener("error", this.handleSocketError); | ||
| this.#attachSocket(socket); | ||
| await new Promise((resolve, reject) => { | ||
@@ -87,4 +124,5 @@ const onOpen = () => { | ||
| if (!socket) return; | ||
| this.#detachSocket(socket); | ||
| await new Promise((resolve) => { | ||
| if (socket.readyState === WebSocket.CLOSED) { | ||
| if (socket.readyState === WEB_SOCKET_CLOSED) { | ||
| resolve(); | ||
@@ -98,3 +136,3 @@ return; | ||
| socket.addEventListener("close", onClose, { once: true }); | ||
| if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) socket.close(); | ||
| if (socket.readyState === WEB_SOCKET_OPEN || socket.readyState === WEB_SOCKET_CONNECTING) socket.close(); | ||
| else resolve(); | ||
@@ -107,4 +145,8 @@ }); | ||
| async sendCommand(command) { | ||
| const socket = this.socket; | ||
| if (socket == null || socket.readyState !== WebSocket.OPEN) throw new Error("Protocol WebSocket is not open."); | ||
| let socket = this.socket; | ||
| if (this.reconnectInFlight != null && (socket == null || socket.readyState !== WEB_SOCKET_OPEN)) { | ||
| await this.reconnectInFlight.catch(() => void 0); | ||
| socket = this.socket; | ||
| } | ||
| if (socket == null || socket.readyState !== WEB_SOCKET_OPEN) throw new Error("Protocol WebSocket is not open."); | ||
| return await new Promise((resolve, reject) => { | ||
@@ -123,2 +165,12 @@ this.pending.set(command.id, { | ||
| } | ||
| #attachSocket(socket) { | ||
| socket.addEventListener("message", this.handleMessage); | ||
| socket.addEventListener("close", this.handleClose); | ||
| socket.addEventListener("error", this.handleSocketError); | ||
| } | ||
| #detachSocket(socket) { | ||
| socket.removeEventListener("message", this.handleMessage); | ||
| socket.removeEventListener("close", this.handleClose); | ||
| socket.removeEventListener("error", this.handleSocketError); | ||
| } | ||
| handleMessage = (event) => { | ||
@@ -142,2 +194,4 @@ let payload; | ||
| handleClose = () => { | ||
| const socket = this.socket; | ||
| if (socket != null) this.#detachSocket(socket); | ||
| this.socket = null; | ||
@@ -148,18 +202,52 @@ if (this.intentionalClose || this.closed) { | ||
| } | ||
| const error = /* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly."); | ||
| for (const { reject } of this.pending.values()) reject(error); | ||
| this.pending.clear(); | ||
| this.queue.close(error); | ||
| this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket closed unexpectedly.")); | ||
| }; | ||
| handleSocketError = () => { | ||
| if (this.closed || this.intentionalClose) return; | ||
| const error = /* @__PURE__ */ new Error("Protocol WebSocket encountered an error."); | ||
| this.#handleUnexpectedDisconnect(/* @__PURE__ */ new Error("Protocol WebSocket encountered an error.")); | ||
| }; | ||
| #handleUnexpectedDisconnect(cause) { | ||
| const error = toError(cause); | ||
| for (const { reject } of this.pending.values()) reject(error); | ||
| this.pending.clear(); | ||
| this.queue.close(error); | ||
| }; | ||
| if (this.maxReconnectAttempts <= 0) { | ||
| this.queue.close(error); | ||
| return; | ||
| } | ||
| this.#scheduleReconnect(cause); | ||
| } | ||
| #scheduleReconnect(cause) { | ||
| if (this.closed || this.intentionalClose) return; | ||
| if (this.reconnectInFlight != null) return; | ||
| this.reconnectInFlight = this.#runReconnectLoop(cause).finally(() => { | ||
| this.reconnectInFlight = null; | ||
| }); | ||
| } | ||
| async #runReconnectLoop(initialCause) { | ||
| let lastError = initialCause; | ||
| for (let attempt = 1; attempt <= this.maxReconnectAttempts; attempt += 1) { | ||
| if (this.closed || this.intentionalClose) return; | ||
| this.onReconnect?.({ | ||
| attempt, | ||
| cause: lastError | ||
| }); | ||
| const delay = this.reconnectDelayMs(attempt); | ||
| if (delay > 0) await new Promise((resolve) => { | ||
| setTimeout(resolve, delay); | ||
| }); | ||
| if (this.closed || this.intentionalClose) return; | ||
| try { | ||
| await this.open(); | ||
| if (this.onReconnected) await this.onReconnected(); | ||
| return; | ||
| } catch (error) { | ||
| lastError = error; | ||
| } | ||
| } | ||
| this.queue.close(new MaxWebSocketReconnectAttemptsError(this.maxReconnectAttempts, lastError)); | ||
| } | ||
| }; | ||
| //#endregion | ||
| export { ProtocolWebSocketTransportAdapter }; | ||
| export { ProtocolWebSocketTransportAdapter, webSocketReconnectDelayMs }; | ||
| //# sourceMappingURL=websocket.js.map |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"websocket.js","names":[],"sources":["../../../../src/client/stream/transport/websocket.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport {\n toAbsoluteUrl,\n toWebSocketUrl,\n isRecord,\n hasHeaders,\n toError,\n} from \"./utils.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n PendingResponse,\n ProtocolWebSocketTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter } from \"../transport.js\";\n\n/**\n * Transport adapter that speaks the thread-centric protocol over a\n * bidirectional WebSocket. Bound to a specific `threadId` — the socket\n * connects to `ws://.../threads/:thread_id/stream/events`.\n */\nexport class ProtocolWebSocketTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly apiUrl: string;\n\n private readonly defaultHeaders?: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly webSocketFactory: (url: string) => WebSocket;\n\n private readonly streamUrl: string;\n\n private readonly pending = new Map<number, PendingResponse>();\n\n private socket: WebSocket | null = null;\n\n private closed = false;\n\n private intentionalClose = false;\n\n constructor(options: ProtocolWebSocketTransportOptions) {\n this.apiUrl = options.apiUrl;\n this.threadId = options.threadId;\n this.defaultHeaders = options.defaultHeaders;\n this.onRequest = options.onRequest;\n this.webSocketFactory =\n options.webSocketFactory ?? ((url) => new WebSocket(url));\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n }\n\n async open(): Promise<void> {\n if (this.socket != null) return;\n this.assertBrowserSafeTransportConfig();\n\n const wsUrl = toWebSocketUrl(\n toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()\n );\n const socket = this.webSocketFactory(wsUrl);\n this.socket = socket;\n this.closed = false;\n this.intentionalClose = false;\n\n socket.addEventListener(\"message\", this.handleMessage);\n socket.addEventListener(\"close\", this.handleClose);\n socket.addEventListener(\"error\", this.handleSocketError);\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onError = () => {\n cleanup();\n reject(new Error(\"Failed to open protocol WebSocket.\"));\n };\n const cleanup = () => {\n socket.removeEventListener(\"open\", onOpen);\n socket.removeEventListener(\"error\", onError);\n };\n socket.addEventListener(\"open\", onOpen, { once: true });\n socket.addEventListener(\"error\", onError, { once: true });\n });\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n return await this.sendCommand(command);\n }\n\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.intentionalClose = true;\n\n for (const { reject } of this.pending.values()) {\n reject(new Error(\"Protocol WebSocket connection closed.\"));\n }\n this.pending.clear();\n this.queue.close();\n\n const socket = this.socket;\n this.socket = null;\n if (!socket) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n if (socket.readyState === WebSocket.CLOSED) {\n resolve();\n return;\n }\n\n const onClose = () => {\n socket.removeEventListener(\"close\", onClose);\n resolve();\n };\n\n socket.addEventListener(\"close\", onClose, { once: true });\n if (\n socket.readyState === WebSocket.OPEN ||\n socket.readyState === WebSocket.CONNECTING\n ) {\n socket.close();\n } else {\n resolve();\n }\n });\n }\n\n private assertBrowserSafeTransportConfig(): void {\n if (hasHeaders(this.defaultHeaders) || this.onRequest != null) {\n throw new Error(\n \"Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup.\"\n );\n }\n }\n\n private async sendCommand(\n command: Command\n ): Promise<CommandResponse | ErrorResponse> {\n const socket = this.socket;\n if (socket == null || socket.readyState !== WebSocket.OPEN) {\n throw new Error(\"Protocol WebSocket is not open.\");\n }\n\n return await new Promise<CommandResponse | ErrorResponse>(\n (resolve, reject) => {\n this.pending.set(command.id, { resolve, reject });\n\n try {\n socket.send(JSON.stringify(command));\n } catch (error) {\n this.pending.delete(command.id);\n reject(toError(error));\n }\n }\n );\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n let payload: unknown;\n try {\n payload = JSON.parse(String(event.data));\n } catch {\n return;\n }\n\n if (\n isRecord(payload) &&\n typeof payload.id === \"number\" &&\n (payload.type === \"success\" || payload.type === \"error\")\n ) {\n const pending = this.pending.get(payload.id);\n if (pending) {\n this.pending.delete(payload.id);\n pending.resolve(payload as CommandResponse | ErrorResponse);\n }\n return;\n }\n\n if (isRecord(payload) && payload.type === \"event\") {\n this.queue.push(payload as Message);\n }\n };\n\n private readonly handleClose = (): void => {\n this.socket = null;\n\n if (this.intentionalClose || this.closed) {\n this.queue.close();\n return;\n }\n\n const error = new Error(\"Protocol WebSocket closed unexpectedly.\");\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n this.queue.close(error);\n };\n\n private readonly handleSocketError = (): void => {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n const error = new Error(\"Protocol WebSocket encountered an error.\");\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n this.queue.close(error);\n };\n}\n"],"mappings":";;;;;;;;AA4BA,IAAa,oCAAb,MAA2E;CACzE;CAEA,QAAyB,IAAI,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA,0BAA2B,IAAI,KAA8B;CAE7D,SAAmC;CAEnC,SAAiB;CAEjB,mBAA2B;CAE3B,YAAY,SAA4C;AACtD,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,QAAQ;AACxB,OAAK,iBAAiB,QAAQ;AAC9B,OAAK,YAAY,QAAQ;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,OAAO,QAAQ,GAAG;AAC/B,YAAQ,QAAQ,QAA2C;;AAE7D;;AAGF,MAAI,SAAS,QAAQ,IAAI,QAAQ,SAAS,QACxC,MAAK,MAAM,KAAK,QAAmB;;CAIvC,oBAA2C;AACzC,OAAK,SAAS;AAEd,MAAI,KAAK,oBAAoB,KAAK,QAAQ;AACxC,QAAK,MAAM,OAAO;AAClB;;EAGF,MAAM,wBAAQ,IAAI,MAAM,0CAA0C;AAClE,OAAK,MAAM,EAAE,YAAY,KAAK,QAAQ,QAAQ,CAC5C,QAAO,MAAM;AAEf,OAAK,QAAQ,OAAO;AACpB,OAAK,MAAM,MAAM,MAAM;;CAGzB,0BAAiD;AAC/C,MAAI,KAAK,UAAU,KAAK,iBACtB;EAGF,MAAM,wBAAQ,IAAI,MAAM,2CAA2C;AACnE,OAAK,MAAM,EAAE,YAAY,KAAK,QAAQ,QAAQ,CAC5C,QAAO,MAAM;AAEf,OAAK,QAAQ,OAAO;AACpB,OAAK,MAAM,MAAM,MAAM"} | ||
| {"version":3,"file":"websocket.js","names":["#detachSocket","#attachSocket","#handleUnexpectedDisconnect","#scheduleReconnect","#runReconnectLoop"],"sources":["../../../../src/client/stream/transport/websocket.ts"],"sourcesContent":["import { AsyncQueue } from \"./queue.js\";\nimport type {\n Message,\n Command,\n CommandResponse,\n ErrorResponse,\n} from \"@langchain/protocol\";\n\nimport {\n toAbsoluteUrl,\n toWebSocketUrl,\n isRecord,\n hasHeaders,\n toError,\n} from \"./utils.js\";\nimport type {\n HeaderValue,\n ProtocolRequestHook,\n PendingResponse,\n ProtocolWebSocketTransportOptions,\n} from \"./types.js\";\nimport type { TransportAdapter } from \"../transport.js\";\nimport { MaxWebSocketReconnectAttemptsError } from \"../error.js\";\n\nconst WEB_SOCKET_CONNECTING = 0;\nconst WEB_SOCKET_OPEN = 1;\nconst WEB_SOCKET_CLOSED = 3;\n\n/**\n * Reconnect tuning for {@link ProtocolWebSocketTransportAdapter}. A subset\n * of {@link ProtocolWebSocketTransportOptions}.\n */\nexport interface WebSocketReconnectOptions {\n /**\n * Maximum reconnection attempts after an unexpected disconnect.\n * Defaults to 5.\n */\n maxReconnectAttempts?: number;\n\n /**\n * Invoked before each reconnect attempt (after backoff).\n */\n onReconnect?: (options: { attempt: number; cause: unknown }) => void;\n}\n\n/**\n * Exponential backoff with jitter for WebSocket reconnect. Mirrors\n * {@link streamWithRetry} in `utils/stream.ts` (capped at 5s + 1s jitter).\n */\nexport function webSocketReconnectDelayMs(attempt: number): number {\n const baseDelay = Math.min(1000 * 2 ** (attempt - 1), 5000);\n const jitter = Math.random() * 1000;\n return baseDelay + jitter;\n}\n\n/**\n * Transport adapter that speaks the thread-centric protocol over a\n * bidirectional WebSocket. Bound to a specific `threadId` — the socket\n * connects to `ws://.../threads/:thread_id/stream/events`.\n *\n * On unexpected disconnect the adapter reconnects with exponential\n * backoff (see {@link ProtocolWebSocketTransportOptions.maxReconnectAttempts}).\n * The server replays buffered events on the new socket; the SDK\n * deduplicates by `event_id`. {@link ProtocolWebSocketTransportOptions.onReconnected}\n * runs after each successful reconnect so `ThreadStream` can re-issue\n * `subscription.subscribe` commands.\n */\nexport class ProtocolWebSocketTransportAdapter implements TransportAdapter {\n readonly threadId: string;\n\n private readonly queue = new AsyncQueue<Message>();\n\n private readonly apiUrl: string;\n\n private readonly defaultHeaders?: Record<string, HeaderValue>;\n\n private readonly onRequest?: ProtocolRequestHook;\n\n private readonly webSocketFactory: (url: string) => WebSocket;\n\n private readonly streamUrl: string;\n\n private readonly maxReconnectAttempts: number;\n\n private readonly onReconnect?: ProtocolWebSocketTransportOptions[\"onReconnect\"];\n\n private readonly reconnectDelayMs: (attempt: number) => number;\n\n private onReconnected?: () => void | Promise<void>;\n\n private readonly pending = new Map<number, PendingResponse>();\n\n private socket: WebSocket | null = null;\n\n private closed = false;\n\n private intentionalClose = false;\n\n private reconnectInFlight: Promise<void> | null = null;\n\n constructor(options: ProtocolWebSocketTransportOptions) {\n this.apiUrl = options.apiUrl;\n this.threadId = options.threadId;\n this.defaultHeaders = options.defaultHeaders;\n this.onRequest = options.onRequest;\n this.webSocketFactory =\n options.webSocketFactory ?? ((url) => new WebSocket(url));\n this.streamUrl =\n options.paths?.stream ?? `/threads/${this.threadId}/stream/events`;\n this.maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n this.onReconnect = options.onReconnect;\n this.onReconnected = options.onReconnected;\n this.reconnectDelayMs =\n options.reconnectDelayMs ?? webSocketReconnectDelayMs;\n }\n\n /**\n * Register a callback invoked after each successful reconnect. Used\n * by {@link ThreadStream} to re-send active `subscription.subscribe`\n * commands.\n */\n setOnReconnected(handler: () => void | Promise<void>): void {\n this.onReconnected = handler;\n }\n\n async open(): Promise<void> {\n if (this.closed) {\n throw new Error(\"Protocol WebSocket transport is closed.\");\n }\n if (this.socket?.readyState === WEB_SOCKET_OPEN) {\n return;\n }\n if (this.socket != null) {\n this.#detachSocket(this.socket);\n this.socket = null;\n }\n\n this.assertBrowserSafeTransportConfig();\n\n const wsUrl = toWebSocketUrl(\n toAbsoluteUrl(this.apiUrl, this.streamUrl).toString()\n );\n const socket = this.webSocketFactory(wsUrl);\n this.socket = socket;\n this.intentionalClose = false;\n\n this.#attachSocket(socket);\n\n await new Promise<void>((resolve, reject) => {\n const onOpen = () => {\n cleanup();\n resolve();\n };\n const onError = () => {\n cleanup();\n reject(new Error(\"Failed to open protocol WebSocket.\"));\n };\n const cleanup = () => {\n socket.removeEventListener(\"open\", onOpen);\n socket.removeEventListener(\"error\", onError);\n };\n socket.addEventListener(\"open\", onOpen, { once: true });\n socket.addEventListener(\"error\", onError, { once: true });\n });\n }\n\n async send(\n command: Command\n ): Promise<CommandResponse | ErrorResponse | void> {\n return await this.sendCommand(command);\n }\n\n events(): AsyncIterable<Message> {\n const queue = this.queue;\n return {\n [Symbol.asyncIterator]: () => ({\n next: async () => await queue.shift(),\n return: async () => {\n queue.close();\n return { done: true, value: undefined };\n },\n }),\n };\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n this.intentionalClose = true;\n\n for (const { reject } of this.pending.values()) {\n reject(new Error(\"Protocol WebSocket connection closed.\"));\n }\n this.pending.clear();\n this.queue.close();\n\n const socket = this.socket;\n this.socket = null;\n if (!socket) {\n return;\n }\n\n this.#detachSocket(socket);\n\n await new Promise<void>((resolve) => {\n if (socket.readyState === WEB_SOCKET_CLOSED) {\n resolve();\n return;\n }\n\n const onClose = () => {\n socket.removeEventListener(\"close\", onClose);\n resolve();\n };\n\n socket.addEventListener(\"close\", onClose, { once: true });\n if (\n socket.readyState === WEB_SOCKET_OPEN ||\n socket.readyState === WEB_SOCKET_CONNECTING\n ) {\n socket.close();\n } else {\n resolve();\n }\n });\n }\n\n private assertBrowserSafeTransportConfig(): void {\n if (hasHeaders(this.defaultHeaders) || this.onRequest != null) {\n throw new Error(\n \"Browser WebSocket protocol transport does not support defaultHeaders or onRequest hooks. Supply a custom protocolWebSocketFactory if you need custom WebSocket setup.\"\n );\n }\n }\n\n private async sendCommand(\n command: Command\n ): Promise<CommandResponse | ErrorResponse> {\n // Wait for an in-flight reconnect only when the socket is not usable.\n // After `open()` succeeds, `#runReconnectLoop` may still be awaiting\n // `onReconnected` (e.g. ThreadStream resubscribe). Those callbacks call\n // `sendCommand` and must not await the same `reconnectInFlight` promise.\n let socket = this.socket;\n if (\n this.reconnectInFlight != null &&\n (socket == null || socket.readyState !== WEB_SOCKET_OPEN)\n ) {\n await this.reconnectInFlight.catch(() => undefined);\n socket = this.socket;\n }\n\n if (socket == null || socket.readyState !== WEB_SOCKET_OPEN) {\n throw new Error(\"Protocol WebSocket is not open.\");\n }\n\n return await new Promise<CommandResponse | ErrorResponse>(\n (resolve, reject) => {\n this.pending.set(command.id, { resolve, reject });\n\n try {\n socket.send(JSON.stringify(command));\n } catch (error) {\n this.pending.delete(command.id);\n reject(toError(error));\n }\n }\n );\n }\n\n #attachSocket(socket: WebSocket): void {\n socket.addEventListener(\"message\", this.handleMessage);\n socket.addEventListener(\"close\", this.handleClose);\n socket.addEventListener(\"error\", this.handleSocketError);\n }\n\n #detachSocket(socket: WebSocket): void {\n socket.removeEventListener(\"message\", this.handleMessage);\n socket.removeEventListener(\"close\", this.handleClose);\n socket.removeEventListener(\"error\", this.handleSocketError);\n }\n\n private readonly handleMessage = (event: MessageEvent): void => {\n let payload: unknown;\n try {\n payload = JSON.parse(String(event.data));\n } catch {\n return;\n }\n\n if (\n isRecord(payload) &&\n typeof payload.id === \"number\" &&\n (payload.type === \"success\" || payload.type === \"error\")\n ) {\n const pending = this.pending.get(payload.id);\n if (pending) {\n this.pending.delete(payload.id);\n pending.resolve(payload as CommandResponse | ErrorResponse);\n }\n return;\n }\n\n if (isRecord(payload) && payload.type === \"event\") {\n this.queue.push(payload as Message);\n }\n };\n\n private readonly handleClose = (): void => {\n const socket = this.socket;\n if (socket != null) {\n this.#detachSocket(socket);\n }\n this.socket = null;\n\n if (this.intentionalClose || this.closed) {\n this.queue.close();\n return;\n }\n\n this.#handleUnexpectedDisconnect(\n new Error(\"Protocol WebSocket closed unexpectedly.\")\n );\n };\n\n private readonly handleSocketError = (): void => {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n this.#handleUnexpectedDisconnect(\n new Error(\"Protocol WebSocket encountered an error.\")\n );\n };\n\n #handleUnexpectedDisconnect(cause: unknown): void {\n const error = toError(cause);\n for (const { reject } of this.pending.values()) {\n reject(error);\n }\n this.pending.clear();\n\n if (this.maxReconnectAttempts <= 0) {\n this.queue.close(error);\n return;\n }\n\n this.#scheduleReconnect(cause);\n }\n\n #scheduleReconnect(cause: unknown): void {\n if (this.closed || this.intentionalClose) {\n return;\n }\n if (this.reconnectInFlight != null) {\n return;\n }\n\n this.reconnectInFlight = this.#runReconnectLoop(cause).finally(() => {\n this.reconnectInFlight = null;\n });\n }\n\n async #runReconnectLoop(initialCause: unknown): Promise<void> {\n let lastError: unknown = initialCause;\n\n for (let attempt = 1; attempt <= this.maxReconnectAttempts; attempt += 1) {\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n this.onReconnect?.({ attempt, cause: lastError });\n\n const delay = this.reconnectDelayMs(attempt);\n if (delay > 0) {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delay);\n });\n }\n\n if (this.closed || this.intentionalClose) {\n return;\n }\n\n try {\n await this.open();\n if (this.onReconnected) {\n await this.onReconnected();\n }\n return;\n } catch (error) {\n lastError = error;\n }\n }\n\n this.queue.close(\n new MaxWebSocketReconnectAttemptsError(\n this.maxReconnectAttempts,\n lastError\n )\n );\n }\n}\n"],"mappings":";;;;AAwBA,MAAM,wBAAwB;AAC9B,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;;;;;AAuB1B,SAAgB,0BAA0B,SAAyB;AAGjE,QAFkB,KAAK,IAAI,MAAO,MAAM,UAAU,IAAI,IAAK,GAC5C,KAAK,QAAQ,GAAG;;;;;;;;;;;;;;AAgBjC,IAAa,oCAAb,MAA2E;CACzE;CAEA,QAAyB,IAAI,YAAqB;CAElD;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA;CAEA,0BAA2B,IAAI,KAA8B;CAE7D,SAAmC;CAEnC,SAAiB;CAEjB,mBAA2B;CAE3B,oBAAkD;CAElD,YAAY,SAA4C;AACtD,OAAK,SAAS,QAAQ;AACtB,OAAK,WAAW,QAAQ;AACxB,OAAK,iBAAiB,QAAQ;AAC9B,OAAK,YAAY,QAAQ;AACzB,OAAK,mBACH,QAAQ,sBAAsB,QAAQ,IAAI,UAAU,IAAI;AAC1D,OAAK,YACH,QAAQ,OAAO,UAAU,YAAY,KAAK,SAAS;AACrD,OAAK,uBAAuB,QAAQ,wBAAwB;AAC5D,OAAK,cAAc,QAAQ;AAC3B,OAAK,gBAAgB,QAAQ;AAC7B,OAAK,mBACH,QAAQ,oBAAoB;;;;;;;CAQhC,iBAAiB,SAA2C;AAC1D,OAAK,gBAAgB;;CAGvB,MAAM,OAAsB;AAC1B,MAAI,KAAK,OACP,OAAM,IAAI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AAG,WAAW,KAAK,sBAAsB,WAAW,GAAG;AACxE,OAAI,KAAK,UAAU,KAAK,iBACtB;AAGF,QAAK,cAAc;IAAE;IAAS,OAAO;IAAW,CAAC;GAEjD,MAAM,QAAQ,KAAK,iBAAiB,QAAQ;AAC5C,OAAI,QAAQ,EACV,OAAM,IAAI,SAAe,YAAY;AACnC,eAAW,SAAS,MAAM;KAC1B;AAGJ,OAAI,KAAK,UAAU,KAAK,iBACtB;AAGF,OAAI;AACF,UAAM,KAAK,MAAM;AACjB,QAAI,KAAK,cACP,OAAM,KAAK,eAAe;AAE5B;YACO,OAAO;AACd,gBAAY;;;AAIhB,OAAK,MAAM,MACT,IAAI,mCACF,KAAK,sBACL,UACD,CACF"} |
@@ -99,2 +99,19 @@ import { AssembledMessage } from "./messages.cjs"; | ||
| webSocketFactory?: (url: string) => WebSocket; | ||
| /** | ||
| * Built-in `"sse"` / `"websocket"` transports only: max reconnect | ||
| * attempts after an unexpected disconnect. Defaults to 5. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** | ||
| * Built-in transports only: delay before each reconnect attempt. | ||
| * Defaults to exponential backoff with jitter. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| /** | ||
| * Built-in transports only: invoked before each reconnect attempt. | ||
| */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| } | ||
@@ -101,0 +118,0 @@ interface SessionOrderingState { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"types.d.cts","names":[],"sources":["../../../src/client/stream/types.ts"],"mappings":";;;;;UAoBiB,sBAAA,SAA+B,cAAA;EAC9C,QAAA;EACA,iBAAA;AAAA;AAAA,KAGU,gBAAA,GAAmB,IAAA,CAAK,eAAA;AAAA,KAExB,oBAAA;EACV,MAAA;EACA,OAAA;EACA,QAAA;EACA,KAAA;EACA,MAAA;EACA,SAAA;EACA,KAAA;EACA,KAAA;EACA,WAAA;EACA,KAAA;AAAA;AA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AAA,EAAQ,cAAA,GAAiB,OAAA,CAAQ,cAAA;EACrC,eAAA,CACE,MAAA,EAAQ,qBAAA,GACP,OAAA,CAAQ,qBAAA;EACX,IAAA,CAAK,MAAA,EAAQ,eAAA,GAAkB,OAAA,CAAQ,eAAA;AAAA;;;;UAMxB,aAAA;EACf,GAAA;IAxC2D;;AAG7D;;;IA2CI,KAAA,CACE,MAAA,EAAQ,IAAA,CAAK,sBAAA,oBACZ,OAAA,CAAQ,SAAA;EAAA;EAEb,KAAA;IACE,OAAA,CAAQ,MAAA;MAAW,MAAA;IAAA,IAAoB,OAAA,CAAQ,WAAA;EAAA;EAEjD,KAAA,EAAO,WAAA;EACP,KAAA,EAAO,WAAA;AAAA;;;;;;;;;;;UAaQ,gBAAA;EACf,WAAA;EACA,OAAA,EAAS,QAAA;EAvDT;EAyDA,SAAA;AAAA;;AAtDF;;;;;;;;;;;;;;;;;UA2EiB,eAAA,sBACP,aAAA,CAAc,CAAA,GAAI,WAAA,CAAY,CAAA;;;;;;;;;;;;;;KAe5B,eAAA,MACV,CAAA,SAAU,WAAA,YAAuB,CAAA,GAAI,CAAA,SAAU,aAAA,YAAyB,CAAA,GAAI,CAAA;;;;;AAjF9E;;;;;;;;;;;KAkGY,gBAAA,qBACU,MAAA,oBAA0B,MAAA,4CAEzB,WAAA,GAAc,eAAA,CACjC,eAAA,CAAgB,WAAA,CAAY,CAAA;EAAA,UAGpB,IAAA,WAAe,eAAA;AAAA"} |
@@ -99,2 +99,19 @@ import { AssembledMessage } from "./messages.js"; | ||
| webSocketFactory?: (url: string) => WebSocket; | ||
| /** | ||
| * Built-in `"sse"` / `"websocket"` transports only: max reconnect | ||
| * attempts after an unexpected disconnect. Defaults to 5. | ||
| */ | ||
| maxReconnectAttempts?: number; | ||
| /** | ||
| * Built-in transports only: delay before each reconnect attempt. | ||
| * Defaults to exponential backoff with jitter. | ||
| */ | ||
| reconnectDelayMs?: (attempt: number) => number; | ||
| /** | ||
| * Built-in transports only: invoked before each reconnect attempt. | ||
| */ | ||
| onReconnect?: (options: { | ||
| attempt: number; | ||
| cause: unknown; | ||
| }) => void; | ||
| } | ||
@@ -101,0 +118,0 @@ interface SessionOrderingState { |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"types.d.ts","names":[],"sources":["../../../src/client/stream/types.ts"],"mappings":";;;;;UAoBiB,sBAAA,SAA+B,cAAA;EAC9C,QAAA;EACA,iBAAA;AAAA;AAAA,KAGU,gBAAA,GAAmB,IAAA,CAAK,eAAA;AAAA,KAExB,oBAAA;EACV,MAAA;EACA,OAAA;EACA,QAAA;EACA,KAAA;EACA,MAAA;EACA,SAAA;EACA,KAAA;EACA,KAAA;EACA,WAAA;EACA,KAAA;AAAA;AAAA,KAGU,eAAA,kBAAiC,OAAA,IAC3C,QAAA,eAAuB,oBAAA,GACnB,OAAA,CAAQ,KAAA;EAAS,MAAA,EAAQ,oBAAA,CAAqB,QAAA;AAAA,KAC9C,QAAA,8BACE,OAAA,CAAQ,KAAA;EAAS,MAAA;AAAA;AAAA,KAGb,gBAAA,4BAA4C,OAAA,MACtD,eAAA,CAAgB,SAAA;;;;;;;KAQN,eAAA,kBAAiC,OAAA,IAC3C,QAAA,wCAAgD,eAAA,CAAgB,QAAA;AAAA,KAEtD,gBAAA,4BAA4C,OAAA,MACtD,eAAA,CAAgB,SAAA;;AApBlB;;;;;;;KA8BY,yBAAA;;;;;;;;;KAUA,qBAAA,GACR,yBAAA,GACA,kBAAA;;;;UAKa,mBAAA;EA7CM;;;;;EAmDrB,WAAA;EAjDuB;;;AAGzB;;;;;;;;;;EA4DE,SAAA,GAAY,qBAAA;EA3DI;;;AAQlB;EAwDE,iBAAA;EAxDyB;;;;;;;EAgEzB,KAAA,UAAe,KAAA;EAhE4B;;;;;;EAuE3C,gBAAA,IAAoB,GAAA,aAAgB,SAAA;AAAA;AAAA,UAGrB,oBAAA;EACf,WAAA;EACA,qBAAA;EACA,WAAA;AAAA;AAAA,UAGe,iBAAA,UACN,KAAA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ACU,MAAA,oBAA0B,MAAA,4CAEzB,WAAA,GAAc,eAAA,CACjC,eAAA,CAAgB,WAAA,CAAY,CAAA;EAAA,UAGpB,IAAA,WAAe,eAAA;AAAA"} |
| require("../../_virtual/_rolldown/runtime.cjs"); | ||
| const require_base = require("../base.cjs"); | ||
| const require_index = require("../stream/index.cjs"); | ||
| const require_websocket = require("../stream/transport/websocket.cjs"); | ||
| const require_http = require("../stream/transport/http.cjs"); | ||
| const require_websocket = require("../stream/transport/websocket.cjs"); | ||
| let uuid = require("uuid"); | ||
@@ -252,18 +252,34 @@ //#region src/client/threads/index.ts | ||
| }; | ||
| const userFetch = options.fetch; | ||
| const protocolFetch = userFetch ?? this.asyncCaller.fetch.bind(this.asyncCaller); | ||
| let transport; | ||
| if (options.transport != null && typeof options.transport !== "string") transport = options.transport; | ||
| else transport = (options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse")) === "websocket" ? new require_websocket.ProtocolWebSocketTransportAdapter({ | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| webSocketFactory: options.webSocketFactory | ||
| }) : new require_http.ProtocolSseTransportAdapter({ | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| fetch: options.fetch | ||
| else { | ||
| const transportKind = options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse"); | ||
| const maxReconnectAttempts = options.maxReconnectAttempts ?? 5; | ||
| /** | ||
| * Common options for both transports. | ||
| */ | ||
| const commonOpts = { | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| maxReconnectAttempts, | ||
| reconnectDelayMs: options.reconnectDelayMs, | ||
| onReconnect: options.onReconnect | ||
| }; | ||
| transport = transportKind === "websocket" ? new require_websocket.ProtocolWebSocketTransportAdapter({ | ||
| ...commonOpts, | ||
| webSocketFactory: options.webSocketFactory | ||
| }) : new require_http.ProtocolSseTransportAdapter({ | ||
| ...commonOpts, | ||
| fetch: userFetch, | ||
| asyncCaller: userFetch ? void 0 : this.asyncCaller | ||
| }); | ||
| } | ||
| return new require_index.ThreadStream(transport, { | ||
| ...options, | ||
| fetch: protocolFetch | ||
| }); | ||
| return new require_index.ThreadStream(transport, options); | ||
| } | ||
@@ -270,0 +286,0 @@ }; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.cjs","names":["BaseClient","ProtocolWebSocketTransportAdapter","ProtocolSseTransportAdapter","ThreadStream"],"sources":["../../../src/client/threads/index.ts"],"sourcesContent":["import { v7 as uuidv7 } from \"uuid\";\n\nimport {\n Checkpoint,\n Config,\n DefaultValues,\n Metadata,\n SortOrder,\n Thread,\n ThreadSelectField,\n ThreadSortBy,\n ThreadState,\n ThreadStatus,\n ThreadValuesFilter,\n} from \"../../schema.js\";\nimport type { Command, OnConflictBehavior, StreamEvent } from \"../../types.js\";\nimport type { ThreadStreamMode } from \"../../types.stream.js\";\nimport { BaseClient } from \"../base.js\";\nimport { ThreadStream } from \"../stream/index.js\";\nimport type {\n ThreadStreamOptions,\n ThreadStreamTransportKind,\n} from \"../stream/types.js\";\nimport { ProtocolSseTransportAdapter } from \"../stream/transport/http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"../stream/transport/websocket.js\";\nimport type { TransportAdapter } from \"../stream/transport.js\";\n\nexport class ThreadsClient<\n TStateType = DefaultValues,\n TUpdateType = TStateType,\n> extends BaseClient {\n /**\n * Get a thread by ID.\n *\n * @param threadId ID of the thread.\n * @returns The thread.\n */\n async get<ValuesType = TStateType>(\n threadId: string,\n options?: { signal?: AbortSignal; include?: string[] }\n ): Promise<Thread<ValuesType>> {\n return this.fetch<Thread<ValuesType>>(`/threads/${threadId}`, {\n params: {\n include: options?.include ?? undefined,\n },\n signal: options?.signal,\n });\n }\n\n /**\n * Create a new thread.\n *\n * @param payload Payload for creating a thread.\n * @returns The created thread.\n */\n async create(payload?: {\n metadata?: Metadata;\n threadId?: string;\n ifExists?: OnConflictBehavior;\n graphId?: string;\n supersteps?: Array<{\n updates: Array<{ values: unknown; command?: Command; asNode: string }>;\n }>;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n signal?: AbortSignal;\n }): Promise<Thread<TStateType>> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread<TStateType>>(`/threads`, {\n method: \"POST\",\n json: {\n metadata: {\n ...payload?.metadata,\n graph_id: payload?.graphId,\n },\n thread_id: payload?.threadId,\n if_exists: payload?.ifExists,\n supersteps: payload?.supersteps?.map((s) => ({\n updates: s.updates.map((u) => ({\n values: u.values,\n command: u.command,\n as_node: u.asNode,\n })),\n })),\n ttl: ttlPayload,\n },\n signal: payload?.signal,\n });\n }\n\n /**\n * Copy an existing thread\n * @param threadId ID of the thread to be copied\n * @returns Newly copied thread\n */\n async copy(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<Thread<TStateType>> {\n return this.fetch<Thread<TStateType>>(`/threads/${threadId}/copy`, {\n method: \"POST\",\n signal: options?.signal,\n });\n }\n\n /**\n * Update a thread.\n *\n * @param threadId ID of the thread.\n * @param payload Payload for updating the thread.\n * @returns The updated thread.\n */\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: false;\n signal?: AbortSignal;\n }\n ): Promise<Thread>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: true;\n signal?: AbortSignal;\n }\n ): Promise<void>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void>;\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread | void>(`/threads/${threadId}`, {\n method: \"PATCH\",\n headers: payload?.returnMinimal\n ? { Prefer: \"return=minimal\" }\n : undefined,\n json: { metadata: payload?.metadata, ttl: ttlPayload },\n signal: payload?.signal,\n });\n }\n\n /**\n * Delete a thread.\n *\n * @param threadId ID of the thread.\n */\n async delete(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n return this.fetch<void>(`/threads/${threadId}`, {\n method: \"DELETE\",\n signal: options?.signal,\n });\n }\n\n /**\n * Prune threads by ID. The 'delete' strategy removes threads entirely.\n * The 'keep_latest' strategy prunes old checkpoints but keeps threads\n * and their latest state.\n *\n * @param threadIds List of thread IDs to prune.\n * @param options Additional options for pruning.\n * @param options.strategy The prune strategy. Defaults to 'delete'.\n * @param options.signal Signal to abort the request.\n * @returns An object containing `pruned_count`.\n */\n async prune(\n threadIds: string[],\n options?: {\n strategy?: \"delete\" | \"keep_latest\";\n signal?: AbortSignal;\n }\n ): Promise<{ pruned_count: number }> {\n return this.fetch<{ pruned_count: number }>(\"/threads/prune\", {\n method: \"POST\",\n json: {\n thread_ids: threadIds,\n strategy: options?.strategy ?? \"delete\",\n },\n signal: options?.signal,\n });\n }\n\n /**\n * List threads\n *\n * @param query Query options\n * @returns List of threads\n */\n async search<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n ids?: string[];\n limit?: number;\n offset?: number;\n status?: ThreadStatus;\n sortBy?: ThreadSortBy;\n sortOrder?: SortOrder;\n select?: ThreadSelectField[];\n values?: ThreadValuesFilter;\n extract?: Record<string, string>;\n signal?: AbortSignal;\n }): Promise<Thread<ValuesType>[]> {\n return this.fetch<Thread<ValuesType>[]>(\"/threads/search\", {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n ids: query?.ids ?? undefined,\n limit: query?.limit ?? 10,\n offset: query?.offset ?? 0,\n status: query?.status,\n sort_by: query?.sortBy,\n sort_order: query?.sortOrder,\n select: query?.select ?? undefined,\n values: query?.values ?? undefined,\n extract: query?.extract ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Count threads matching filters.\n *\n * @param query.metadata Thread metadata to filter on.\n * @param query.values State values to filter on.\n * @param query.status Thread status to filter on.\n * @returns Number of threads matching the criteria.\n */\n async count<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n values?: ValuesType;\n status?: ThreadStatus;\n signal?: AbortSignal;\n }): Promise<number> {\n return this.fetch<number>(`/threads/count`, {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n values: query?.values ?? undefined,\n status: query?.status ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Get state for a thread.\n *\n * @param threadId ID of the thread.\n * @returns Thread state.\n */\n async getState<ValuesType = TStateType>(\n threadId: string,\n checkpoint?: Checkpoint | string,\n options?: { subgraphs?: boolean; signal?: AbortSignal }\n ): Promise<ThreadState<ValuesType>> {\n if (checkpoint != null) {\n if (typeof checkpoint !== \"string\") {\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/checkpoint`,\n {\n method: \"POST\",\n json: { checkpoint, subgraphs: options?.subgraphs },\n signal: options?.signal,\n }\n );\n }\n\n // deprecated\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/${checkpoint}`,\n { params: { subgraphs: options?.subgraphs }, signal: options?.signal }\n );\n }\n\n return this.fetch<ThreadState<ValuesType>>(`/threads/${threadId}/state`, {\n params: { subgraphs: options?.subgraphs },\n signal: options?.signal,\n // Coalesce concurrent identical reads (e.g. two controllers\n // hydrating the same thread on reconnect). Skipped automatically\n // when a caller supplies its own `signal`.\n dedupe: true,\n });\n }\n\n /**\n * Add state to a thread.\n *\n * @param threadId The ID of the thread.\n * @returns\n */\n async updateState<ValuesType = TUpdateType>(\n threadId: string,\n options: {\n values: ValuesType;\n checkpoint?: Checkpoint;\n checkpointId?: string;\n asNode?: string;\n signal?: AbortSignal;\n }\n ): Promise<Pick<Config, \"configurable\">> {\n return this.fetch<Pick<Config, \"configurable\">>(\n `/threads/${threadId}/state`,\n {\n method: \"POST\",\n json: {\n values: options.values,\n checkpoint: options.checkpoint,\n checkpoint_id: options.checkpointId,\n as_node: options?.asNode,\n },\n signal: options?.signal,\n }\n );\n }\n\n /**\n * Patch the metadata of a thread.\n *\n * @param threadIdOrConfig Thread ID or config to patch the state of.\n * @param metadata Metadata to patch the state with.\n */\n async patchState(\n threadIdOrConfig: string | Config,\n metadata: Metadata,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n let threadId: string;\n\n if (typeof threadIdOrConfig !== \"string\") {\n if (typeof threadIdOrConfig.configurable?.thread_id !== \"string\") {\n throw new Error(\n \"Thread ID is required when updating state with a config.\"\n );\n }\n threadId = threadIdOrConfig.configurable.thread_id;\n } else {\n threadId = threadIdOrConfig;\n }\n\n return this.fetch<void>(`/threads/${threadId}/state`, {\n method: \"PATCH\",\n json: { metadata },\n signal: options?.signal,\n });\n }\n\n /**\n * Get all past states for a thread.\n *\n * @param threadId ID of the thread.\n * @param options Additional options.\n * @returns List of thread states.\n */\n async getHistory<ValuesType = TStateType>(\n threadId: string,\n options?: {\n limit?: number;\n before?: Config;\n checkpoint?: Partial<Omit<Checkpoint, \"thread_id\">>;\n metadata?: Metadata;\n signal?: AbortSignal;\n }\n ): Promise<ThreadState<ValuesType>[]> {\n return this.fetch<ThreadState<ValuesType>[]>(\n `/threads/${threadId}/history`,\n {\n method: \"POST\",\n json: {\n limit: options?.limit ?? 10,\n before: options?.before,\n metadata: options?.metadata,\n checkpoint: options?.checkpoint,\n },\n signal: options?.signal,\n // `getHistory` is a read despite using POST — coalesce the\n // hydrate-time discovery seed when two controllers reconnect to\n // the same thread concurrently. Skipped when `signal` is set.\n dedupe: true,\n }\n );\n }\n\n async *joinStream(\n threadId: string,\n options?: {\n lastEventId?: string;\n streamMode?: ThreadStreamMode | ThreadStreamMode[];\n signal?: AbortSignal;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }> {\n yield* this.streamWithRetry({\n endpoint: `/threads/${threadId}/stream`,\n method: \"GET\",\n signal: options?.signal,\n headers: options?.lastEventId\n ? { \"Last-Event-ID\": options.lastEventId }\n : undefined,\n params: options?.streamMode\n ? { stream_mode: options.streamMode }\n : undefined,\n });\n }\n\n /**\n * Open a protocol stream over the thread-centric v2 protocol.\n *\n * Returns a {@link ThreadStream} with lazy getters\n * (`.messages`, `.values`, `.toolCalls`, `.subgraphs`, `.subagents`,\n * `.output`) and `thread.run.start({ input, ... })` for starting runs.\n * Mirrors the in-process `graph.streamEvents(..., { version: \"v3\" })` API.\n *\n * The thread is bound to `options.assistantId` for its lifetime.\n * The wire transport defaults to SSE; pass `transport: \"websocket\"`\n * in options (or configure `streamProtocol: \"v2-websocket\"` on the\n * client) to use a WebSocket instead.\n *\n * @example New thread (UUID generated client-side)\n * ```ts\n * const thread = client.threads.stream({ assistantId: \"my-agent\" });\n * ```\n *\n * @example Attach to an existing thread\n * ```ts\n * const thread = client.threads.stream(threadId, { assistantId: \"my-agent\" });\n * ```\n *\n * @example WebSocket transport\n * ```ts\n * const thread = client.threads.stream({\n * assistantId: \"my-agent\",\n * transport: \"websocket\",\n * });\n * ```\n */\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadId: string,\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadIdOrOptions: string | ThreadStreamOptions,\n maybeOptions?: ThreadStreamOptions\n ): ThreadStream<TExtensions> {\n const { threadId, options } =\n typeof threadIdOrOptions === \"string\"\n ? {\n threadId: threadIdOrOptions,\n options: maybeOptions as ThreadStreamOptions,\n }\n : { threadId: uuidv7(), options: threadIdOrOptions };\n\n // `transport` accepts either a preset string (`\"sse\"` / `\"websocket\"`)\n // or a custom {@link AgentServerAdapter}. A custom adapter replaces\n // the built-in factories entirely — this is the seam that lets users\n // point `useStream` at any agent server (including the thin wrappers\n // produced by `HttpAgentServerAdapter`).\n let transport: TransportAdapter;\n if (options.transport != null && typeof options.transport !== \"string\") {\n transport = options.transport;\n } else {\n const transportKind: ThreadStreamTransportKind =\n options.transport ??\n (this.streamProtocol === \"v2-websocket\" ? \"websocket\" : \"sse\");\n transport =\n transportKind === \"websocket\"\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n fetch: options.fetch,\n });\n }\n\n return new ThreadStream<TExtensions>(transport, options);\n }\n}\n"],"mappings":";;;;;;;AA2BA,IAAa,gBAAb,cAGUA,aAAAA,WAAW;;;;;;;CAOnB,MAAM,IACJ,UACA,SAC6B;AAC7B,SAAO,KAAK,MAA0B,YAAY,YAAY;GAC5D,QAAQ,EACN,SAAS,SAAS,WAAW,KAAA,GAC9B;GACD,QAAQ,SAAS;GAClB,CAAC;;;;;;;;CASJ,MAAM,OAAO,SAUmB;EAC9B,MAAM,aACJ,OAAO,SAAS,QAAQ,WACpB;GAAE,KAAK,QAAQ;GAAK,UAAU;GAAmB,GACjD,SAAS;AAEf,SAAO,KAAK,MAA0B,YAAY;GAChD,QAAQ;GACR,MAAM;IACJ,UAAU;KACR,GAAG,SAAS;KACZ,UAAU,SAAS;KACpB;IACD,WAAW,SAAS;IACpB,WAAW,SAAS;IACpB,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ACR,MAAM,EAAE,UAAU;GAClB,QAAQ,SAAS;GAClB,CAAC;;;;;;;;;CAUJ,MAAM,WACJ,UACA,SAOoC;AACpC,SAAO,KAAK,MACV,YAAY,SAAS,WACrB;GACE,QAAQ;GACR,MAAM;IACJ,OAAO,SAAS,SAAS;IACzB,QAAQ,SAAS;IACjB,UAAU,SAAS;IACnB,YAAY,SAAS;IACtB;GACD,QAAQ,SAAS;GAIjB,QAAQ;GACT,CACF;;CAGH,OAAO,WACL,UACA,SAMgE;AAChE,SAAO,KAAK,gBAAgB;GAC1B,UAAU,YAAY,SAAS;GAC/B,QAAQ;GACR,QAAQ,SAAS;GACjB,SAAS,SAAS,cACd,EAAE,iBAAiB,QAAQ,aAAa,GACxC,KAAA;GACJ,QAAQ,SAAS,aACb,EAAE,aAAa,QAAQ,YAAY,GACnC,KAAA;GACL,CAAC;;CAyCJ,OACE,mBACA,cAC2B;EAC3B,MAAM,EAAE,UAAU,YAChB,OAAO,sBAAsB,WACzB;GACE,UAAU;GACV,SAAS;GACV,GACD;GAAE,WAAA,GAAA,KAAA,KAAkB;GAAE,SAAS;GAAmB;EAOxD,IAAI;AACJ,MAAI,QAAQ,aAAa,QAAQ,OAAO,QAAQ,cAAc,SAC5D,aAAY,QAAQ;MAKpB,cAFE,QAAQ,cACP,KAAK,mBAAmB,iBAAiB,cAAc,YAEtC,cACd,IAAIC,kBAAAA,kCAAkC;GACpC,QAAQ,KAAK;GACb;GACA,gBAAgB,KAAK;GACrB,WAAW,KAAK;GAChB,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAIC,aAAAA,4BAA4B;GAC9B,QAAQ,KAAK;GACb;GACA,gBAAgB,KAAK;GACrB,WAAW,KAAK;GAChB,OAAO,QAAQ;GAChB,CAAC;AAGV,SAAO,IAAIC,cAAAA,aAA0B,WAAW,QAAQ"} | ||
| {"version":3,"file":"index.cjs","names":["BaseClient","ProtocolWebSocketTransportAdapter","ProtocolSseTransportAdapter","ThreadStream"],"sources":["../../../src/client/threads/index.ts"],"sourcesContent":["import { v7 as uuidv7 } from \"uuid\";\n\nimport {\n Checkpoint,\n Config,\n DefaultValues,\n Metadata,\n SortOrder,\n Thread,\n ThreadSelectField,\n ThreadSortBy,\n ThreadState,\n ThreadStatus,\n ThreadValuesFilter,\n} from \"../../schema.js\";\nimport type { Command, OnConflictBehavior, StreamEvent } from \"../../types.js\";\nimport type { ThreadStreamMode } from \"../../types.stream.js\";\nimport { BaseClient } from \"../base.js\";\nimport { ThreadStream } from \"../stream/index.js\";\nimport type {\n ThreadStreamOptions,\n ThreadStreamTransportKind,\n} from \"../stream/types.js\";\nimport { ProtocolSseTransportAdapter } from \"../stream/transport/http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"../stream/transport/websocket.js\";\nimport type { TransportAdapter } from \"../stream/transport.js\";\n\nexport class ThreadsClient<\n TStateType = DefaultValues,\n TUpdateType = TStateType,\n> extends BaseClient {\n /**\n * Get a thread by ID.\n *\n * @param threadId ID of the thread.\n * @returns The thread.\n */\n async get<ValuesType = TStateType>(\n threadId: string,\n options?: { signal?: AbortSignal; include?: string[] }\n ): Promise<Thread<ValuesType>> {\n return this.fetch<Thread<ValuesType>>(`/threads/${threadId}`, {\n params: {\n include: options?.include ?? undefined,\n },\n signal: options?.signal,\n });\n }\n\n /**\n * Create a new thread.\n *\n * @param payload Payload for creating a thread.\n * @returns The created thread.\n */\n async create(payload?: {\n metadata?: Metadata;\n threadId?: string;\n ifExists?: OnConflictBehavior;\n graphId?: string;\n supersteps?: Array<{\n updates: Array<{ values: unknown; command?: Command; asNode: string }>;\n }>;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n signal?: AbortSignal;\n }): Promise<Thread<TStateType>> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread<TStateType>>(`/threads`, {\n method: \"POST\",\n json: {\n metadata: {\n ...payload?.metadata,\n graph_id: payload?.graphId,\n },\n thread_id: payload?.threadId,\n if_exists: payload?.ifExists,\n supersteps: payload?.supersteps?.map((s) => ({\n updates: s.updates.map((u) => ({\n values: u.values,\n command: u.command,\n as_node: u.asNode,\n })),\n })),\n ttl: ttlPayload,\n },\n signal: payload?.signal,\n });\n }\n\n /**\n * Copy an existing thread\n * @param threadId ID of the thread to be copied\n * @returns Newly copied thread\n */\n async copy(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<Thread<TStateType>> {\n return this.fetch<Thread<TStateType>>(`/threads/${threadId}/copy`, {\n method: \"POST\",\n signal: options?.signal,\n });\n }\n\n /**\n * Update a thread.\n *\n * @param threadId ID of the thread.\n * @param payload Payload for updating the thread.\n * @returns The updated thread.\n */\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: false;\n signal?: AbortSignal;\n }\n ): Promise<Thread>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: true;\n signal?: AbortSignal;\n }\n ): Promise<void>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void>;\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread | void>(`/threads/${threadId}`, {\n method: \"PATCH\",\n headers: payload?.returnMinimal\n ? { Prefer: \"return=minimal\" }\n : undefined,\n json: { metadata: payload?.metadata, ttl: ttlPayload },\n signal: payload?.signal,\n });\n }\n\n /**\n * Delete a thread.\n *\n * @param threadId ID of the thread.\n */\n async delete(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n return this.fetch<void>(`/threads/${threadId}`, {\n method: \"DELETE\",\n signal: options?.signal,\n });\n }\n\n /**\n * Prune threads by ID. The 'delete' strategy removes threads entirely.\n * The 'keep_latest' strategy prunes old checkpoints but keeps threads\n * and their latest state.\n *\n * @param threadIds List of thread IDs to prune.\n * @param options Additional options for pruning.\n * @param options.strategy The prune strategy. Defaults to 'delete'.\n * @param options.signal Signal to abort the request.\n * @returns An object containing `pruned_count`.\n */\n async prune(\n threadIds: string[],\n options?: {\n strategy?: \"delete\" | \"keep_latest\";\n signal?: AbortSignal;\n }\n ): Promise<{ pruned_count: number }> {\n return this.fetch<{ pruned_count: number }>(\"/threads/prune\", {\n method: \"POST\",\n json: {\n thread_ids: threadIds,\n strategy: options?.strategy ?? \"delete\",\n },\n signal: options?.signal,\n });\n }\n\n /**\n * List threads\n *\n * @param query Query options\n * @returns List of threads\n */\n async search<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n ids?: string[];\n limit?: number;\n offset?: number;\n status?: ThreadStatus;\n sortBy?: ThreadSortBy;\n sortOrder?: SortOrder;\n select?: ThreadSelectField[];\n values?: ThreadValuesFilter;\n extract?: Record<string, string>;\n signal?: AbortSignal;\n }): Promise<Thread<ValuesType>[]> {\n return this.fetch<Thread<ValuesType>[]>(\"/threads/search\", {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n ids: query?.ids ?? undefined,\n limit: query?.limit ?? 10,\n offset: query?.offset ?? 0,\n status: query?.status,\n sort_by: query?.sortBy,\n sort_order: query?.sortOrder,\n select: query?.select ?? undefined,\n values: query?.values ?? undefined,\n extract: query?.extract ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Count threads matching filters.\n *\n * @param query.metadata Thread metadata to filter on.\n * @param query.values State values to filter on.\n * @param query.status Thread status to filter on.\n * @returns Number of threads matching the criteria.\n */\n async count<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n values?: ValuesType;\n status?: ThreadStatus;\n signal?: AbortSignal;\n }): Promise<number> {\n return this.fetch<number>(`/threads/count`, {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n values: query?.values ?? undefined,\n status: query?.status ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Get state for a thread.\n *\n * @param threadId ID of the thread.\n * @returns Thread state.\n */\n async getState<ValuesType = TStateType>(\n threadId: string,\n checkpoint?: Checkpoint | string,\n options?: { subgraphs?: boolean; signal?: AbortSignal }\n ): Promise<ThreadState<ValuesType>> {\n if (checkpoint != null) {\n if (typeof checkpoint !== \"string\") {\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/checkpoint`,\n {\n method: \"POST\",\n json: { checkpoint, subgraphs: options?.subgraphs },\n signal: options?.signal,\n }\n );\n }\n\n // deprecated\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/${checkpoint}`,\n { params: { subgraphs: options?.subgraphs }, signal: options?.signal }\n );\n }\n\n return this.fetch<ThreadState<ValuesType>>(`/threads/${threadId}/state`, {\n params: { subgraphs: options?.subgraphs },\n signal: options?.signal,\n // Coalesce concurrent identical reads (e.g. two controllers\n // hydrating the same thread on reconnect). Skipped automatically\n // when a caller supplies its own `signal`.\n dedupe: true,\n });\n }\n\n /**\n * Add state to a thread.\n *\n * @param threadId The ID of the thread.\n * @returns\n */\n async updateState<ValuesType = TUpdateType>(\n threadId: string,\n options: {\n values: ValuesType;\n checkpoint?: Checkpoint;\n checkpointId?: string;\n asNode?: string;\n signal?: AbortSignal;\n }\n ): Promise<Pick<Config, \"configurable\">> {\n return this.fetch<Pick<Config, \"configurable\">>(\n `/threads/${threadId}/state`,\n {\n method: \"POST\",\n json: {\n values: options.values,\n checkpoint: options.checkpoint,\n checkpoint_id: options.checkpointId,\n as_node: options?.asNode,\n },\n signal: options?.signal,\n }\n );\n }\n\n /**\n * Patch the metadata of a thread.\n *\n * @param threadIdOrConfig Thread ID or config to patch the state of.\n * @param metadata Metadata to patch the state with.\n */\n async patchState(\n threadIdOrConfig: string | Config,\n metadata: Metadata,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n let threadId: string;\n\n if (typeof threadIdOrConfig !== \"string\") {\n if (typeof threadIdOrConfig.configurable?.thread_id !== \"string\") {\n throw new Error(\n \"Thread ID is required when updating state with a config.\"\n );\n }\n threadId = threadIdOrConfig.configurable.thread_id;\n } else {\n threadId = threadIdOrConfig;\n }\n\n return this.fetch<void>(`/threads/${threadId}/state`, {\n method: \"PATCH\",\n json: { metadata },\n signal: options?.signal,\n });\n }\n\n /**\n * Get all past states for a thread.\n *\n * @param threadId ID of the thread.\n * @param options Additional options.\n * @returns List of thread states.\n */\n async getHistory<ValuesType = TStateType>(\n threadId: string,\n options?: {\n limit?: number;\n before?: Config;\n checkpoint?: Partial<Omit<Checkpoint, \"thread_id\">>;\n metadata?: Metadata;\n signal?: AbortSignal;\n }\n ): Promise<ThreadState<ValuesType>[]> {\n return this.fetch<ThreadState<ValuesType>[]>(\n `/threads/${threadId}/history`,\n {\n method: \"POST\",\n json: {\n limit: options?.limit ?? 10,\n before: options?.before,\n metadata: options?.metadata,\n checkpoint: options?.checkpoint,\n },\n signal: options?.signal,\n // `getHistory` is a read despite using POST — coalesce the\n // hydrate-time discovery seed when two controllers reconnect to\n // the same thread concurrently. Skipped when `signal` is set.\n dedupe: true,\n }\n );\n }\n\n async *joinStream(\n threadId: string,\n options?: {\n lastEventId?: string;\n streamMode?: ThreadStreamMode | ThreadStreamMode[];\n signal?: AbortSignal;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }> {\n yield* this.streamWithRetry({\n endpoint: `/threads/${threadId}/stream`,\n method: \"GET\",\n signal: options?.signal,\n headers: options?.lastEventId\n ? { \"Last-Event-ID\": options.lastEventId }\n : undefined,\n params: options?.streamMode\n ? { stream_mode: options.streamMode }\n : undefined,\n });\n }\n\n /**\n * Open a protocol stream over the thread-centric v2 protocol.\n *\n * Returns a {@link ThreadStream} with lazy getters\n * (`.messages`, `.values`, `.toolCalls`, `.subgraphs`, `.subagents`,\n * `.output`) and `thread.run.start({ input, ... })` for starting runs.\n * Mirrors the in-process `graph.streamEvents(..., { version: \"v3\" })` API.\n *\n * The thread is bound to `options.assistantId` for its lifetime.\n * The wire transport defaults to SSE; pass `transport: \"websocket\"`\n * in options (or configure `streamProtocol: \"v2-websocket\"` on the\n * client) to use a WebSocket instead.\n *\n * @example New thread (UUID generated client-side)\n * ```ts\n * const thread = client.threads.stream({ assistantId: \"my-agent\" });\n * ```\n *\n * @example Attach to an existing thread\n * ```ts\n * const thread = client.threads.stream(threadId, { assistantId: \"my-agent\" });\n * ```\n *\n * @example WebSocket transport\n * ```ts\n * const thread = client.threads.stream({\n * assistantId: \"my-agent\",\n * transport: \"websocket\",\n * });\n * ```\n */\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadId: string,\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadIdOrOptions: string | ThreadStreamOptions,\n maybeOptions?: ThreadStreamOptions\n ): ThreadStream<TExtensions> {\n const { threadId, options } =\n typeof threadIdOrOptions === \"string\"\n ? {\n threadId: threadIdOrOptions,\n options: maybeOptions as ThreadStreamOptions,\n }\n : { threadId: uuidv7(), options: threadIdOrOptions };\n\n // `transport` accepts either a preset string (`\"sse\"` / `\"websocket\"`)\n // or a custom {@link AgentServerAdapter}. A custom adapter replaces\n // the built-in factories entirely — this is the seam that lets users\n // point `useStream` at any agent server (including the thin wrappers\n // produced by `HttpAgentServerAdapter`).\n // When callers supply `fetch`, use it verbatim (tests, auth shims). Otherwise\n // route protocol HTTP and media URL fetches through AsyncCaller like REST.\n const userFetch = options.fetch;\n const protocolFetch =\n userFetch ?? this.asyncCaller.fetch.bind(this.asyncCaller);\n\n let transport: TransportAdapter;\n if (options.transport != null && typeof options.transport !== \"string\") {\n transport = options.transport;\n } else {\n const transportKind: ThreadStreamTransportKind =\n options.transport ??\n (this.streamProtocol === \"v2-websocket\" ? \"websocket\" : \"sse\");\n const maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n\n /**\n * Common options for both transports.\n */\n const commonOpts = {\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n maxReconnectAttempts,\n reconnectDelayMs: options.reconnectDelayMs,\n onReconnect: options.onReconnect,\n };\n\n transport =\n transportKind === \"websocket\"\n ? new ProtocolWebSocketTransportAdapter({\n ...commonOpts,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n ...commonOpts,\n fetch: userFetch,\n asyncCaller: userFetch ? undefined : this.asyncCaller,\n });\n }\n\n return new ThreadStream<TExtensions>(transport, {\n ...options,\n fetch: protocolFetch,\n });\n }\n}\n"],"mappings":";;;;;;;AA2BA,IAAa,gBAAb,cAGUA,aAAAA,WAAW;;;;;;;CAOnB,MAAM,IACJ,UACA,SAC6B;AAC7B,SAAO,KAAK,MAA0B,YAAY,YAAY;GAC5D,QAAQ,EACN,SAAS,SAAS,WAAW,KAAA,GAC9B;GACD,QAAQ,SAAS;GAClB,CAAC;;;;;;;;CASJ,MAAM,OAAO,SAUmB;EAC9B,MAAM,aACJ,OAAO,SAAS,QAAQ,WACpB;GAAE,KAAK,QAAQ;GAAK,UAAU;GAAmB,GACjD,SAAS;AAEf,SAAO,KAAK,MAA0B,YAAY;GAChD,QAAQ;GACR,MAAM;IACJ,UAAU;KACR,GAAG,SAAS;KACZ,UAAU,SAAS;KACpB;IACD,WAAW,SAAS;IACpB,WAAW,SAAS;IACpB,YAAY,SAAS,YAAY,KAAK,OAAO,EAC3C,SAAS,EAAE,QAAQ,KAAK,OAAO;KAC7B,QAAQ,EAAE;KACV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A,aAA0B,WAAW;GAC9C,GAAG;GACH,OAAO;GACR,CAAC"} |
| import { BaseClient } from "../base.js"; | ||
| import { ThreadStream } from "../stream/index.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "../stream/transport/websocket.js"; | ||
| import { ProtocolSseTransportAdapter } from "../stream/transport/http.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "../stream/transport/websocket.js"; | ||
| import { v7 } from "uuid"; | ||
@@ -251,18 +251,34 @@ //#region src/client/threads/index.ts | ||
| }; | ||
| const userFetch = options.fetch; | ||
| const protocolFetch = userFetch ?? this.asyncCaller.fetch.bind(this.asyncCaller); | ||
| let transport; | ||
| if (options.transport != null && typeof options.transport !== "string") transport = options.transport; | ||
| else transport = (options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse")) === "websocket" ? new ProtocolWebSocketTransportAdapter({ | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| webSocketFactory: options.webSocketFactory | ||
| }) : new ProtocolSseTransportAdapter({ | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| fetch: options.fetch | ||
| else { | ||
| const transportKind = options.transport ?? (this.streamProtocol === "v2-websocket" ? "websocket" : "sse"); | ||
| const maxReconnectAttempts = options.maxReconnectAttempts ?? 5; | ||
| /** | ||
| * Common options for both transports. | ||
| */ | ||
| const commonOpts = { | ||
| apiUrl: this.apiUrl, | ||
| threadId, | ||
| defaultHeaders: this.defaultHeaders, | ||
| onRequest: this.onRequest, | ||
| maxReconnectAttempts, | ||
| reconnectDelayMs: options.reconnectDelayMs, | ||
| onReconnect: options.onReconnect | ||
| }; | ||
| transport = transportKind === "websocket" ? new ProtocolWebSocketTransportAdapter({ | ||
| ...commonOpts, | ||
| webSocketFactory: options.webSocketFactory | ||
| }) : new ProtocolSseTransportAdapter({ | ||
| ...commonOpts, | ||
| fetch: userFetch, | ||
| asyncCaller: userFetch ? void 0 : this.asyncCaller | ||
| }); | ||
| } | ||
| return new ThreadStream(transport, { | ||
| ...options, | ||
| fetch: protocolFetch | ||
| }); | ||
| return new ThreadStream(transport, options); | ||
| } | ||
@@ -269,0 +285,0 @@ }; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"index.js","names":["uuidv7"],"sources":["../../../src/client/threads/index.ts"],"sourcesContent":["import { v7 as uuidv7 } from \"uuid\";\n\nimport {\n Checkpoint,\n Config,\n DefaultValues,\n Metadata,\n SortOrder,\n Thread,\n ThreadSelectField,\n ThreadSortBy,\n ThreadState,\n ThreadStatus,\n ThreadValuesFilter,\n} from \"../../schema.js\";\nimport type { Command, OnConflictBehavior, StreamEvent } from \"../../types.js\";\nimport type { ThreadStreamMode } from \"../../types.stream.js\";\nimport { BaseClient } from \"../base.js\";\nimport { ThreadStream } from \"../stream/index.js\";\nimport type {\n ThreadStreamOptions,\n ThreadStreamTransportKind,\n} from \"../stream/types.js\";\nimport { ProtocolSseTransportAdapter } from \"../stream/transport/http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"../stream/transport/websocket.js\";\nimport type { TransportAdapter } from \"../stream/transport.js\";\n\nexport class ThreadsClient<\n TStateType = DefaultValues,\n TUpdateType = TStateType,\n> extends BaseClient {\n /**\n * Get a thread by ID.\n *\n * @param threadId ID of the thread.\n * @returns The thread.\n */\n async get<ValuesType = TStateType>(\n threadId: string,\n options?: { signal?: AbortSignal; include?: string[] }\n ): Promise<Thread<ValuesType>> {\n return this.fetch<Thread<ValuesType>>(`/threads/${threadId}`, {\n params: {\n include: options?.include ?? undefined,\n },\n signal: options?.signal,\n });\n }\n\n /**\n * Create a new thread.\n *\n * @param payload Payload for creating a thread.\n * @returns The created thread.\n */\n async create(payload?: {\n metadata?: Metadata;\n threadId?: string;\n ifExists?: OnConflictBehavior;\n graphId?: string;\n supersteps?: Array<{\n updates: Array<{ values: unknown; command?: Command; asNode: string }>;\n }>;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n signal?: AbortSignal;\n }): Promise<Thread<TStateType>> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread<TStateType>>(`/threads`, {\n method: \"POST\",\n json: {\n metadata: {\n ...payload?.metadata,\n graph_id: payload?.graphId,\n },\n thread_id: payload?.threadId,\n if_exists: payload?.ifExists,\n supersteps: payload?.supersteps?.map((s) => ({\n updates: s.updates.map((u) => ({\n values: u.values,\n command: u.command,\n as_node: u.asNode,\n })),\n })),\n ttl: ttlPayload,\n },\n signal: payload?.signal,\n });\n }\n\n /**\n * Copy an existing thread\n * @param threadId ID of the thread to be copied\n * @returns Newly copied thread\n */\n async copy(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<Thread<TStateType>> {\n return this.fetch<Thread<TStateType>>(`/threads/${threadId}/copy`, {\n method: \"POST\",\n signal: options?.signal,\n });\n }\n\n /**\n * Update a thread.\n *\n * @param threadId ID of the thread.\n * @param payload Payload for updating the thread.\n * @returns The updated thread.\n */\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: false;\n signal?: AbortSignal;\n }\n ): Promise<Thread>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: true;\n signal?: AbortSignal;\n }\n ): Promise<void>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void>;\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread | void>(`/threads/${threadId}`, {\n method: \"PATCH\",\n headers: payload?.returnMinimal\n ? { Prefer: \"return=minimal\" }\n : undefined,\n json: { metadata: payload?.metadata, ttl: ttlPayload },\n signal: payload?.signal,\n });\n }\n\n /**\n * Delete a thread.\n *\n * @param threadId ID of the thread.\n */\n async delete(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n return this.fetch<void>(`/threads/${threadId}`, {\n method: \"DELETE\",\n signal: options?.signal,\n });\n }\n\n /**\n * Prune threads by ID. The 'delete' strategy removes threads entirely.\n * The 'keep_latest' strategy prunes old checkpoints but keeps threads\n * and their latest state.\n *\n * @param threadIds List of thread IDs to prune.\n * @param options Additional options for pruning.\n * @param options.strategy The prune strategy. Defaults to 'delete'.\n * @param options.signal Signal to abort the request.\n * @returns An object containing `pruned_count`.\n */\n async prune(\n threadIds: string[],\n options?: {\n strategy?: \"delete\" | \"keep_latest\";\n signal?: AbortSignal;\n }\n ): Promise<{ pruned_count: number }> {\n return this.fetch<{ pruned_count: number }>(\"/threads/prune\", {\n method: \"POST\",\n json: {\n thread_ids: threadIds,\n strategy: options?.strategy ?? \"delete\",\n },\n signal: options?.signal,\n });\n }\n\n /**\n * List threads\n *\n * @param query Query options\n * @returns List of threads\n */\n async search<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n ids?: string[];\n limit?: number;\n offset?: number;\n status?: ThreadStatus;\n sortBy?: ThreadSortBy;\n sortOrder?: SortOrder;\n select?: ThreadSelectField[];\n values?: ThreadValuesFilter;\n extract?: Record<string, string>;\n signal?: AbortSignal;\n }): Promise<Thread<ValuesType>[]> {\n return this.fetch<Thread<ValuesType>[]>(\"/threads/search\", {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n ids: query?.ids ?? undefined,\n limit: query?.limit ?? 10,\n offset: query?.offset ?? 0,\n status: query?.status,\n sort_by: query?.sortBy,\n sort_order: query?.sortOrder,\n select: query?.select ?? undefined,\n values: query?.values ?? undefined,\n extract: query?.extract ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Count threads matching filters.\n *\n * @param query.metadata Thread metadata to filter on.\n * @param query.values State values to filter on.\n * @param query.status Thread status to filter on.\n * @returns Number of threads matching the criteria.\n */\n async count<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n values?: ValuesType;\n status?: ThreadStatus;\n signal?: AbortSignal;\n }): Promise<number> {\n return this.fetch<number>(`/threads/count`, {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n values: query?.values ?? undefined,\n status: query?.status ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Get state for a thread.\n *\n * @param threadId ID of the thread.\n * @returns Thread state.\n */\n async getState<ValuesType = TStateType>(\n threadId: string,\n checkpoint?: Checkpoint | string,\n options?: { subgraphs?: boolean; signal?: AbortSignal }\n ): Promise<ThreadState<ValuesType>> {\n if (checkpoint != null) {\n if (typeof checkpoint !== \"string\") {\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/checkpoint`,\n {\n method: \"POST\",\n json: { checkpoint, subgraphs: options?.subgraphs },\n signal: options?.signal,\n }\n );\n }\n\n // deprecated\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/${checkpoint}`,\n { params: { subgraphs: options?.subgraphs }, signal: options?.signal }\n );\n }\n\n return this.fetch<ThreadState<ValuesType>>(`/threads/${threadId}/state`, {\n params: { subgraphs: options?.subgraphs },\n signal: options?.signal,\n // Coalesce concurrent identical reads (e.g. two controllers\n // hydrating the same thread on reconnect). Skipped automatically\n // when a caller supplies its own `signal`.\n dedupe: true,\n });\n }\n\n /**\n * Add state to a thread.\n *\n * @param threadId The ID of the thread.\n * @returns\n */\n async updateState<ValuesType = TUpdateType>(\n threadId: string,\n options: {\n values: ValuesType;\n checkpoint?: Checkpoint;\n checkpointId?: string;\n asNode?: string;\n signal?: AbortSignal;\n }\n ): Promise<Pick<Config, \"configurable\">> {\n return this.fetch<Pick<Config, \"configurable\">>(\n `/threads/${threadId}/state`,\n {\n method: \"POST\",\n json: {\n values: options.values,\n checkpoint: options.checkpoint,\n checkpoint_id: options.checkpointId,\n as_node: options?.asNode,\n },\n signal: options?.signal,\n }\n );\n }\n\n /**\n * Patch the metadata of a thread.\n *\n * @param threadIdOrConfig Thread ID or config to patch the state of.\n * @param metadata Metadata to patch the state with.\n */\n async patchState(\n threadIdOrConfig: string | Config,\n metadata: Metadata,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n let threadId: string;\n\n if (typeof threadIdOrConfig !== \"string\") {\n if (typeof threadIdOrConfig.configurable?.thread_id !== \"string\") {\n throw new Error(\n \"Thread ID is required when updating state with a config.\"\n );\n }\n threadId = threadIdOrConfig.configurable.thread_id;\n } else {\n threadId = threadIdOrConfig;\n }\n\n return this.fetch<void>(`/threads/${threadId}/state`, {\n method: \"PATCH\",\n json: { metadata },\n signal: options?.signal,\n });\n }\n\n /**\n * Get all past states for a thread.\n *\n * @param threadId ID of the thread.\n * @param options Additional options.\n * @returns List of thread states.\n */\n async getHistory<ValuesType = TStateType>(\n threadId: string,\n options?: {\n limit?: number;\n before?: Config;\n checkpoint?: Partial<Omit<Checkpoint, \"thread_id\">>;\n metadata?: Metadata;\n signal?: AbortSignal;\n }\n ): Promise<ThreadState<ValuesType>[]> {\n return this.fetch<ThreadState<ValuesType>[]>(\n `/threads/${threadId}/history`,\n {\n method: \"POST\",\n json: {\n limit: options?.limit ?? 10,\n before: options?.before,\n metadata: options?.metadata,\n checkpoint: options?.checkpoint,\n },\n signal: options?.signal,\n // `getHistory` is a read despite using POST — coalesce the\n // hydrate-time discovery seed when two controllers reconnect to\n // the same thread concurrently. Skipped when `signal` is set.\n dedupe: true,\n }\n );\n }\n\n async *joinStream(\n threadId: string,\n options?: {\n lastEventId?: string;\n streamMode?: ThreadStreamMode | ThreadStreamMode[];\n signal?: AbortSignal;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }> {\n yield* this.streamWithRetry({\n endpoint: `/threads/${threadId}/stream`,\n method: \"GET\",\n signal: options?.signal,\n headers: options?.lastEventId\n ? { \"Last-Event-ID\": options.lastEventId }\n : undefined,\n params: options?.streamMode\n ? { stream_mode: options.streamMode }\n : undefined,\n });\n }\n\n /**\n * Open a protocol stream over the thread-centric v2 protocol.\n *\n * Returns a {@link ThreadStream} with lazy getters\n * (`.messages`, `.values`, `.toolCalls`, `.subgraphs`, `.subagents`,\n * `.output`) and `thread.run.start({ input, ... })` for starting runs.\n * Mirrors the in-process `graph.streamEvents(..., { version: \"v3\" })` API.\n *\n * The thread is bound to `options.assistantId` for its lifetime.\n * The wire transport defaults to SSE; pass `transport: \"websocket\"`\n * in options (or configure `streamProtocol: \"v2-websocket\"` on the\n * client) to use a WebSocket instead.\n *\n * @example New thread (UUID generated client-side)\n * ```ts\n * const thread = client.threads.stream({ assistantId: \"my-agent\" });\n * ```\n *\n * @example Attach to an existing thread\n * ```ts\n * const thread = client.threads.stream(threadId, { assistantId: \"my-agent\" });\n * ```\n *\n * @example WebSocket transport\n * ```ts\n * const thread = client.threads.stream({\n * assistantId: \"my-agent\",\n * transport: \"websocket\",\n * });\n * ```\n */\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadId: string,\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadIdOrOptions: string | ThreadStreamOptions,\n maybeOptions?: ThreadStreamOptions\n ): ThreadStream<TExtensions> {\n const { threadId, options } =\n typeof threadIdOrOptions === \"string\"\n ? {\n threadId: threadIdOrOptions,\n options: maybeOptions as ThreadStreamOptions,\n }\n : { threadId: uuidv7(), options: threadIdOrOptions };\n\n // `transport` accepts either a preset string (`\"sse\"` / `\"websocket\"`)\n // or a custom {@link AgentServerAdapter}. A custom adapter replaces\n // the built-in factories entirely — this is the seam that lets users\n // point `useStream` at any agent server (including the thin wrappers\n // produced by `HttpAgentServerAdapter`).\n let transport: TransportAdapter;\n if (options.transport != null && typeof options.transport !== \"string\") {\n transport = options.transport;\n } else {\n const transportKind: ThreadStreamTransportKind =\n options.transport ??\n (this.streamProtocol === \"v2-websocket\" ? \"websocket\" : \"sse\");\n transport =\n transportKind === \"websocket\"\n ? new ProtocolWebSocketTransportAdapter({\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n fetch: options.fetch,\n });\n }\n\n return new ThreadStream<TExtensions>(transport, options);\n }\n}\n"],"mappings":";;;;;;AA2BA,IAAa,gBAAb,cAGU,WAAW;;;;;;;CAOnB,MAAM,IACJ,UACA,SAC6B;AAC7B,SAAO,KAAK,MAA0B,YAAY,YAAY;GAC5D,QAAQ,EACN,SAAS,SAAS,WAAW,KAAA,GAC9B;GACD,QAAQ,SAAS;GAClB,CAAC;;;;;;;;CASJ,MAAM,OAAO,SAUmB;EAC9B,MAAM,aACJ,OAAO,SAAS,QAAQ,WACpB;GAAE,KAAK,QAAQ;GAAK,UAAU;GAAmB,GACjD,SAAS;AAEf,SAAO,KAAK,MAA0B,YAAY;GAChD,QAAQ;GACR,MAAM;IACJ,UAAU;KACR,GAAG,SAAS;KACZ,UAAU,SAAS;KACpB;IACD,WAAW,SAAS;IACpB,WAAW,SAAS;IACpB,YAAY,SAAS,YAAY,KAAK,OAAO,EAC3C,SAAS,EAAE,QAAQ,KAAK,OAAO;KAC7B,QAAQ,EAAE;KACV,SAAS,EAAE;KACX,SAAS,EAAE;KACZ,EAAE,EACJ,EAAE;IACH,KAAK;IAC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J,OAAO,SAAS,SAAS;IACzB,QAAQ,SAAS;IACjB,UAAU,SAAS;IACnB,YAAY,SAAS;IACtB;GACD,QAAQ,SAAS;GAIjB,QAAQ;GACT,CACF;;CAGH,OAAO,WACL,UACA,SAMgE;AAChE,SAAO,KAAK,gBAAgB;GAC1B,UAAU,YAAY,SAAS;GAC/B,QAAQ;GACR,QAAQ,SAAS;GACjB,SAAS,SAAS,cACd,EAAE,iBAAiB,QAAQ,aAAa,GACxC,KAAA;GACJ,QAAQ,SAAS,aACb,EAAE,aAAa,QAAQ,YAAY,GACnC,KAAA;GACL,CAAC;;CAyCJ,OACE,mBACA,cAC2B;EAC3B,MAAM,EAAE,UAAU,YAChB,OAAO,sBAAsB,WACzB;GACE,UAAU;GACV,SAAS;GACV,GACD;GAAE,UAAUA,IAAQ;GAAE,SAAS;GAAmB;EAOxD,IAAI;AACJ,MAAI,QAAQ,aAAa,QAAQ,OAAO,QAAQ,cAAc,SAC5D,aAAY,QAAQ;MAKpB,cAFE,QAAQ,cACP,KAAK,mBAAmB,iBAAiB,cAAc,YAEtC,cACd,IAAI,kCAAkC;GACpC,QAAQ,KAAK;GACb;GACA,gBAAgB,KAAK;GACrB,WAAW,KAAK;GAChB,kBAAkB,QAAQ;GAC3B,CAAC,GACF,IAAI,4BAA4B;GAC9B,QAAQ,KAAK;GACb;GACA,gBAAgB,KAAK;GACrB,WAAW,KAAK;GAChB,OAAO,QAAQ;GAChB,CAAC;AAGV,SAAO,IAAI,aAA0B,WAAW,QAAQ"} | ||
| {"version":3,"file":"index.js","names":["uuidv7"],"sources":["../../../src/client/threads/index.ts"],"sourcesContent":["import { v7 as uuidv7 } from \"uuid\";\n\nimport {\n Checkpoint,\n Config,\n DefaultValues,\n Metadata,\n SortOrder,\n Thread,\n ThreadSelectField,\n ThreadSortBy,\n ThreadState,\n ThreadStatus,\n ThreadValuesFilter,\n} from \"../../schema.js\";\nimport type { Command, OnConflictBehavior, StreamEvent } from \"../../types.js\";\nimport type { ThreadStreamMode } from \"../../types.stream.js\";\nimport { BaseClient } from \"../base.js\";\nimport { ThreadStream } from \"../stream/index.js\";\nimport type {\n ThreadStreamOptions,\n ThreadStreamTransportKind,\n} from \"../stream/types.js\";\nimport { ProtocolSseTransportAdapter } from \"../stream/transport/http.js\";\nimport { ProtocolWebSocketTransportAdapter } from \"../stream/transport/websocket.js\";\nimport type { TransportAdapter } from \"../stream/transport.js\";\n\nexport class ThreadsClient<\n TStateType = DefaultValues,\n TUpdateType = TStateType,\n> extends BaseClient {\n /**\n * Get a thread by ID.\n *\n * @param threadId ID of the thread.\n * @returns The thread.\n */\n async get<ValuesType = TStateType>(\n threadId: string,\n options?: { signal?: AbortSignal; include?: string[] }\n ): Promise<Thread<ValuesType>> {\n return this.fetch<Thread<ValuesType>>(`/threads/${threadId}`, {\n params: {\n include: options?.include ?? undefined,\n },\n signal: options?.signal,\n });\n }\n\n /**\n * Create a new thread.\n *\n * @param payload Payload for creating a thread.\n * @returns The created thread.\n */\n async create(payload?: {\n metadata?: Metadata;\n threadId?: string;\n ifExists?: OnConflictBehavior;\n graphId?: string;\n supersteps?: Array<{\n updates: Array<{ values: unknown; command?: Command; asNode: string }>;\n }>;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n signal?: AbortSignal;\n }): Promise<Thread<TStateType>> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread<TStateType>>(`/threads`, {\n method: \"POST\",\n json: {\n metadata: {\n ...payload?.metadata,\n graph_id: payload?.graphId,\n },\n thread_id: payload?.threadId,\n if_exists: payload?.ifExists,\n supersteps: payload?.supersteps?.map((s) => ({\n updates: s.updates.map((u) => ({\n values: u.values,\n command: u.command,\n as_node: u.asNode,\n })),\n })),\n ttl: ttlPayload,\n },\n signal: payload?.signal,\n });\n }\n\n /**\n * Copy an existing thread\n * @param threadId ID of the thread to be copied\n * @returns Newly copied thread\n */\n async copy(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<Thread<TStateType>> {\n return this.fetch<Thread<TStateType>>(`/threads/${threadId}/copy`, {\n method: \"POST\",\n signal: options?.signal,\n });\n }\n\n /**\n * Update a thread.\n *\n * @param threadId ID of the thread.\n * @param payload Payload for updating the thread.\n * @returns The updated thread.\n */\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: false;\n signal?: AbortSignal;\n }\n ): Promise<Thread>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: true;\n signal?: AbortSignal;\n }\n ): Promise<void>;\n async update(\n threadId: string,\n payload: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void>;\n async update(\n threadId: string,\n payload?: {\n metadata?: Metadata;\n ttl?: number | { ttl: number; strategy?: \"delete\" };\n returnMinimal?: boolean;\n signal?: AbortSignal;\n }\n ): Promise<Thread | void> {\n const ttlPayload =\n typeof payload?.ttl === \"number\"\n ? { ttl: payload.ttl, strategy: \"delete\" as const }\n : payload?.ttl;\n\n return this.fetch<Thread | void>(`/threads/${threadId}`, {\n method: \"PATCH\",\n headers: payload?.returnMinimal\n ? { Prefer: \"return=minimal\" }\n : undefined,\n json: { metadata: payload?.metadata, ttl: ttlPayload },\n signal: payload?.signal,\n });\n }\n\n /**\n * Delete a thread.\n *\n * @param threadId ID of the thread.\n */\n async delete(\n threadId: string,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n return this.fetch<void>(`/threads/${threadId}`, {\n method: \"DELETE\",\n signal: options?.signal,\n });\n }\n\n /**\n * Prune threads by ID. The 'delete' strategy removes threads entirely.\n * The 'keep_latest' strategy prunes old checkpoints but keeps threads\n * and their latest state.\n *\n * @param threadIds List of thread IDs to prune.\n * @param options Additional options for pruning.\n * @param options.strategy The prune strategy. Defaults to 'delete'.\n * @param options.signal Signal to abort the request.\n * @returns An object containing `pruned_count`.\n */\n async prune(\n threadIds: string[],\n options?: {\n strategy?: \"delete\" | \"keep_latest\";\n signal?: AbortSignal;\n }\n ): Promise<{ pruned_count: number }> {\n return this.fetch<{ pruned_count: number }>(\"/threads/prune\", {\n method: \"POST\",\n json: {\n thread_ids: threadIds,\n strategy: options?.strategy ?? \"delete\",\n },\n signal: options?.signal,\n });\n }\n\n /**\n * List threads\n *\n * @param query Query options\n * @returns List of threads\n */\n async search<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n ids?: string[];\n limit?: number;\n offset?: number;\n status?: ThreadStatus;\n sortBy?: ThreadSortBy;\n sortOrder?: SortOrder;\n select?: ThreadSelectField[];\n values?: ThreadValuesFilter;\n extract?: Record<string, string>;\n signal?: AbortSignal;\n }): Promise<Thread<ValuesType>[]> {\n return this.fetch<Thread<ValuesType>[]>(\"/threads/search\", {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n ids: query?.ids ?? undefined,\n limit: query?.limit ?? 10,\n offset: query?.offset ?? 0,\n status: query?.status,\n sort_by: query?.sortBy,\n sort_order: query?.sortOrder,\n select: query?.select ?? undefined,\n values: query?.values ?? undefined,\n extract: query?.extract ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Count threads matching filters.\n *\n * @param query.metadata Thread metadata to filter on.\n * @param query.values State values to filter on.\n * @param query.status Thread status to filter on.\n * @returns Number of threads matching the criteria.\n */\n async count<ValuesType = TStateType>(query?: {\n metadata?: Metadata;\n values?: ValuesType;\n status?: ThreadStatus;\n signal?: AbortSignal;\n }): Promise<number> {\n return this.fetch<number>(`/threads/count`, {\n method: \"POST\",\n json: {\n metadata: query?.metadata ?? undefined,\n values: query?.values ?? undefined,\n status: query?.status ?? undefined,\n },\n signal: query?.signal,\n });\n }\n\n /**\n * Get state for a thread.\n *\n * @param threadId ID of the thread.\n * @returns Thread state.\n */\n async getState<ValuesType = TStateType>(\n threadId: string,\n checkpoint?: Checkpoint | string,\n options?: { subgraphs?: boolean; signal?: AbortSignal }\n ): Promise<ThreadState<ValuesType>> {\n if (checkpoint != null) {\n if (typeof checkpoint !== \"string\") {\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/checkpoint`,\n {\n method: \"POST\",\n json: { checkpoint, subgraphs: options?.subgraphs },\n signal: options?.signal,\n }\n );\n }\n\n // deprecated\n return this.fetch<ThreadState<ValuesType>>(\n `/threads/${threadId}/state/${checkpoint}`,\n { params: { subgraphs: options?.subgraphs }, signal: options?.signal }\n );\n }\n\n return this.fetch<ThreadState<ValuesType>>(`/threads/${threadId}/state`, {\n params: { subgraphs: options?.subgraphs },\n signal: options?.signal,\n // Coalesce concurrent identical reads (e.g. two controllers\n // hydrating the same thread on reconnect). Skipped automatically\n // when a caller supplies its own `signal`.\n dedupe: true,\n });\n }\n\n /**\n * Add state to a thread.\n *\n * @param threadId The ID of the thread.\n * @returns\n */\n async updateState<ValuesType = TUpdateType>(\n threadId: string,\n options: {\n values: ValuesType;\n checkpoint?: Checkpoint;\n checkpointId?: string;\n asNode?: string;\n signal?: AbortSignal;\n }\n ): Promise<Pick<Config, \"configurable\">> {\n return this.fetch<Pick<Config, \"configurable\">>(\n `/threads/${threadId}/state`,\n {\n method: \"POST\",\n json: {\n values: options.values,\n checkpoint: options.checkpoint,\n checkpoint_id: options.checkpointId,\n as_node: options?.asNode,\n },\n signal: options?.signal,\n }\n );\n }\n\n /**\n * Patch the metadata of a thread.\n *\n * @param threadIdOrConfig Thread ID or config to patch the state of.\n * @param metadata Metadata to patch the state with.\n */\n async patchState(\n threadIdOrConfig: string | Config,\n metadata: Metadata,\n options?: { signal?: AbortSignal }\n ): Promise<void> {\n let threadId: string;\n\n if (typeof threadIdOrConfig !== \"string\") {\n if (typeof threadIdOrConfig.configurable?.thread_id !== \"string\") {\n throw new Error(\n \"Thread ID is required when updating state with a config.\"\n );\n }\n threadId = threadIdOrConfig.configurable.thread_id;\n } else {\n threadId = threadIdOrConfig;\n }\n\n return this.fetch<void>(`/threads/${threadId}/state`, {\n method: \"PATCH\",\n json: { metadata },\n signal: options?.signal,\n });\n }\n\n /**\n * Get all past states for a thread.\n *\n * @param threadId ID of the thread.\n * @param options Additional options.\n * @returns List of thread states.\n */\n async getHistory<ValuesType = TStateType>(\n threadId: string,\n options?: {\n limit?: number;\n before?: Config;\n checkpoint?: Partial<Omit<Checkpoint, \"thread_id\">>;\n metadata?: Metadata;\n signal?: AbortSignal;\n }\n ): Promise<ThreadState<ValuesType>[]> {\n return this.fetch<ThreadState<ValuesType>[]>(\n `/threads/${threadId}/history`,\n {\n method: \"POST\",\n json: {\n limit: options?.limit ?? 10,\n before: options?.before,\n metadata: options?.metadata,\n checkpoint: options?.checkpoint,\n },\n signal: options?.signal,\n // `getHistory` is a read despite using POST — coalesce the\n // hydrate-time discovery seed when two controllers reconnect to\n // the same thread concurrently. Skipped when `signal` is set.\n dedupe: true,\n }\n );\n }\n\n async *joinStream(\n threadId: string,\n options?: {\n lastEventId?: string;\n streamMode?: ThreadStreamMode | ThreadStreamMode[];\n signal?: AbortSignal;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): AsyncGenerator<{ id?: string; event: StreamEvent; data: any }> {\n yield* this.streamWithRetry({\n endpoint: `/threads/${threadId}/stream`,\n method: \"GET\",\n signal: options?.signal,\n headers: options?.lastEventId\n ? { \"Last-Event-ID\": options.lastEventId }\n : undefined,\n params: options?.streamMode\n ? { stream_mode: options.streamMode }\n : undefined,\n });\n }\n\n /**\n * Open a protocol stream over the thread-centric v2 protocol.\n *\n * Returns a {@link ThreadStream} with lazy getters\n * (`.messages`, `.values`, `.toolCalls`, `.subgraphs`, `.subagents`,\n * `.output`) and `thread.run.start({ input, ... })` for starting runs.\n * Mirrors the in-process `graph.streamEvents(..., { version: \"v3\" })` API.\n *\n * The thread is bound to `options.assistantId` for its lifetime.\n * The wire transport defaults to SSE; pass `transport: \"websocket\"`\n * in options (or configure `streamProtocol: \"v2-websocket\"` on the\n * client) to use a WebSocket instead.\n *\n * @example New thread (UUID generated client-side)\n * ```ts\n * const thread = client.threads.stream({ assistantId: \"my-agent\" });\n * ```\n *\n * @example Attach to an existing thread\n * ```ts\n * const thread = client.threads.stream(threadId, { assistantId: \"my-agent\" });\n * ```\n *\n * @example WebSocket transport\n * ```ts\n * const thread = client.threads.stream({\n * assistantId: \"my-agent\",\n * transport: \"websocket\",\n * });\n * ```\n */\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadId: string,\n options: ThreadStreamOptions\n ): ThreadStream<TExtensions>;\n stream<TExtensions extends Record<string, unknown> = Record<string, unknown>>(\n threadIdOrOptions: string | ThreadStreamOptions,\n maybeOptions?: ThreadStreamOptions\n ): ThreadStream<TExtensions> {\n const { threadId, options } =\n typeof threadIdOrOptions === \"string\"\n ? {\n threadId: threadIdOrOptions,\n options: maybeOptions as ThreadStreamOptions,\n }\n : { threadId: uuidv7(), options: threadIdOrOptions };\n\n // `transport` accepts either a preset string (`\"sse\"` / `\"websocket\"`)\n // or a custom {@link AgentServerAdapter}. A custom adapter replaces\n // the built-in factories entirely — this is the seam that lets users\n // point `useStream` at any agent server (including the thin wrappers\n // produced by `HttpAgentServerAdapter`).\n // When callers supply `fetch`, use it verbatim (tests, auth shims). Otherwise\n // route protocol HTTP and media URL fetches through AsyncCaller like REST.\n const userFetch = options.fetch;\n const protocolFetch =\n userFetch ?? this.asyncCaller.fetch.bind(this.asyncCaller);\n\n let transport: TransportAdapter;\n if (options.transport != null && typeof options.transport !== \"string\") {\n transport = options.transport;\n } else {\n const transportKind: ThreadStreamTransportKind =\n options.transport ??\n (this.streamProtocol === \"v2-websocket\" ? \"websocket\" : \"sse\");\n const maxReconnectAttempts = options.maxReconnectAttempts ?? 5;\n\n /**\n * Common options for both transports.\n */\n const commonOpts = {\n apiUrl: this.apiUrl,\n threadId,\n defaultHeaders: this.defaultHeaders,\n onRequest: this.onRequest,\n maxReconnectAttempts,\n reconnectDelayMs: options.reconnectDelayMs,\n onReconnect: options.onReconnect,\n };\n\n transport =\n transportKind === \"websocket\"\n ? new ProtocolWebSocketTransportAdapter({\n ...commonOpts,\n webSocketFactory: options.webSocketFactory,\n })\n : new ProtocolSseTransportAdapter({\n ...commonOpts,\n fetch: userFetch,\n asyncCaller: userFetch ? undefined : this.asyncCaller,\n });\n }\n\n return new ThreadStream<TExtensions>(transport, {\n ...options,\n fetch: protocolFetch,\n });\n }\n}\n"],"mappings":";;;;;;AA2BA,IAAa,gBAAb,cAGU,WAAW;;;;;;;CAOnB,MAAM,IACJ,UACA,SAC6B;AAC7B,SAAO,KAAK,MAA0B,YAAY,YAAY;GAC5D,QAAQ,EACN,SAAS,SAAS,WAAW,KAAA,GAC9B;GACD,QAAQ,SAAS;GAClB,CAAC;;;;;;;;CASJ,MAAM,OAAO,SAUmB;EAC9B,MAAM,aACJ,OAAO,SAAS,QAAQ,WACpB;GAAE,KAAK,QAAQ;GAAK,UAAU;GAAmB,GACjD,SAAS;AAEf,SAAO,KAAK,MAA0B,YAAY;GAChD,QAAQ;GACR,MAAM;IACJ,UAAU;KACR,GAAG,SAAS;KACZ,UAAU,SAAS;KACpB;IACD,WAAW,SAAS;IACpB,WAAW,SAAS;IACpB,YAAY,SAAS,YAAY,KAAK,OAAO,EAC3C,SAAS,EAAE,QAAQ,KAAK,OAAO;KAC7B,QAAQ,EAAE;KACV,SAAS,EAAE;KACX,SAAS,EAAE;KACZ,EAAE,EACJ,EAAE;IACH,KAAK;IACN;GACD,QAAQ,SAAS;GAClB,CAAC;;;;;;;CAQJ,MAAM,KACJ,UACA,SAC6B;AAC7B,SAAO,KAAK,MAA0B,YAAY,SAAS,QAAQ;GACjE,QAAQ;GACR,QAAQ,SAAS;GAClB,CAAC;;CAqCJ,MAAM,OACJ,UACA,SAM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AAU,YAAY,SAAS;GAC/B,QAAQ;GACR,QAAQ,SAAS;GACjB,SAAS,SAAS,cACd,EAAE,iBAAiB,QAAQ,aAAa,GACxC,KAAA;GACJ,QAAQ,SAAS,aACb,EAAE,aAAa,QAAQ,YAAY,GACnC,KAAA;GACL,CAAC;;CAyCJ,OACE,mBACA,cAC2B;EAC3B,MAAM,EAAE,UAAU,YAChB,OAAO,sBAAsB,WACzB;GACE,UAAU;GACV,SAAS;GACV,GACD;GAAE,UAAUA,IAAQ;GAAE,SAAS;GAAmB;EASxD,MAAM,YAAY,QAAQ;EAC1B,MAAM,gBACJ,aAAa,KAAK,YAAY,MAAM,KAAK,KAAK,YAAY;EAE5D,IAAI;AACJ,MAAI,QAAQ,aAAa,QAAQ,OAAO,QAAQ,cAAc,SAC5D,aAAY,QAAQ;OACf;GACL,MAAM,gBACJ,QAAQ,cACP,KAAK,mBAAmB,iBAAiB,cAAc;GAC1D,MAAM,uBAAuB,QAAQ,wBAAwB;;;;GAK7D,MAAM,aAAa;IACjB,QAAQ,KAAK;IACb;IACA,gBAAgB,KAAK;IACrB,WAAW,KAAK;IAChB;IACA,kBAAkB,QAAQ;IAC1B,aAAa,QAAQ;IACtB;AAED,eACE,kBAAkB,cACd,IAAI,kCAAkC;IACpC,GAAG;IACH,kBAAkB,QAAQ;IAC3B,CAAC,GACF,IAAI,4BAA4B;IAC9B,GAAG;IACH,OAAO;IACP,aAAa,YAAY,KAAA,IAAY,KAAK;IAC3C,CAAC;;AAGV,SAAO,IAAI,aAA0B,WAAW;GAC9C,GAAG;GACH,OAAO;GACR,CAAC"} |
+1
-1
@@ -10,4 +10,4 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); | ||
| const require_index = require("./client/stream/index.cjs"); | ||
| const require_websocket = require("./client/stream/transport/websocket.cjs"); | ||
| const require_http = require("./client/stream/transport/http.cjs"); | ||
| const require_websocket = require("./client/stream/transport/websocket.cjs"); | ||
| const require_agent_server = require("./client/stream/transport/agent-server.cjs"); | ||
@@ -14,0 +14,0 @@ const require_index$1 = require("./client/index.cjs"); |
+1
-1
@@ -9,4 +9,4 @@ import { overrideFetchImplementation } from "./singletons/fetch.js"; | ||
| import { SubscriptionHandle, ThreadStream } from "./client/stream/index.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "./client/stream/transport/websocket.js"; | ||
| import { ProtocolSseTransportAdapter } from "./client/stream/transport/http.js"; | ||
| import { ProtocolWebSocketTransportAdapter } from "./client/stream/transport/websocket.js"; | ||
| import { HttpAgentServerAdapter } from "./client/stream/transport/agent-server.js"; | ||
@@ -13,0 +13,0 @@ import { Client } from "./client/index.js"; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"controller.d.cts","names":[],"sources":["../../src/stream/controller.ts"],"mappings":";;;;;;;;;;;;;;AA4KA;;cAAa,kBAAA,WAA6B,OAAA;;AAkC1C;;;;;;;;;;;;cAAa,gBAAA,4BACgB,MAAA,8EAEO,MAAA;EAAA;WAEzB,SAAA,EAAW,WAAA,CAAY,YAAA,CAAa,SAAA,EAAW,aAAA;EAAA,SAC/C,aAAA,EAAe,WAAA,CAAY,WAAA;EAAA,SAC3B,aAAA,EAAe,WAAA,CAAY,WAAA;EAAA,SAC3B,mBAAA,EAAqB,WAAA,CAAY,iBAAA;EAAA,SACjC,oBAAA,EAAsB,WAAA,CAAY,kBAAA;EAAA,SAClC,UAAA,EAAY,WAAA,CAAY,uBAAA,CAAwB,SAAA;EAAA,SAChD,QAAA,EAAU,eAAA;EAsH0B;;;;;EAA7C,WAAA,CAAY,OAAA,EAAS,uBAAA,CAAwB,SAAA;EA0tBF;;;;;;;EAAA,IAhnBvC,gBAAA,CAAA,GAAoB,OAAA;EAgyBS;;;;;;;;EAvuB3B,OAAA,CAAQ,QAAA,mBAA2B,OAAA;EAu6BpB;;;;;;;;;;;;;;EArnBf,wBAAA,CAAyB,UAAA,WAAqB,OAAA;EAhlB5B;;;;;;;;EAm1BlB,MAAA,CACJ,KAAA,WACA,OAA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1B,UAAA,CAAA,GAAc,OAAA;EA3Fd;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmKA,OAAA,CACJ,QAAA,WACA,OAAA,GAAU,oBAAA,CAAqB,gBAAA,IAC9B,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAkFG,UAAA,CACJ,aAAA,EAAe,MAAA,mBACf,OAAA,GAAU,uBAAA,CAAwB,gBAAA,IACjC,OAAA;;;;EAyCG,OAAA,CAAA,GAAW,OAAA;;;;;;;;;;;;;;;;EAyBjB,QAAA,CAAA;;;;;;EA4BA,SAAA,CAAA,GAAa,YAAA;;;;;;;;EAWb,eAAA,CACE,QAAA,GAAW,MAAA,EAAQ,YAAA;AAAA"} |
@@ -17,2 +17,3 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); | ||
| const require_channel = require("./projections/channel.cjs"); | ||
| const require_channel_effect = require("./projections/channel-effect.cjs"); | ||
| const require_media$1 = require("./projections/media.cjs"); | ||
@@ -29,2 +30,3 @@ require("./projections/index.cjs"); | ||
| exports.SubgraphDiscovery = require_subgraphs.SubgraphDiscovery; | ||
| exports.acquireChannelEffect = require_channel_effect.acquireChannelEffect; | ||
| exports.assembledMessageToBaseMessage = require_assembled_to_message.assembledMessageToBaseMessage; | ||
@@ -31,0 +33,0 @@ exports.assembledToBaseMessage = require_assembled_to_message.assembledToBaseMessage; |
@@ -21,2 +21,3 @@ import { DefaultToolCall, InferToolOutput, ToolCallFromTool } from "../types.messages.cjs"; | ||
| import { ChannelProjectionOptions, channelProjection } from "./projections/channel.cjs"; | ||
| import { ChannelEffectOptions, acquireChannelEffect } from "./projections/channel-effect.cjs"; | ||
| import { MediaProjectionOptions, audioProjection, filesProjection, imagesProjection, videoProjection } from "./projections/media.cjs"; | ||
@@ -26,2 +27,2 @@ import { AssembledToMessageInput, ExtendedMessageRole, assembledMessageToBaseMessage, assembledToBaseMessage } from "./assembled-to-message.cjs"; | ||
| import { Channel, Event } from "@langchain/protocol"; | ||
| export { type AcquiredProjection, type AgentServerAdapter, type AgentServerOptions, type AgentTypeConfigLike, type AnyMediaHandle, type AssembledToMessageInput, type AssembledToolCall, type AssembledToolCallFromTool, type AudioMedia, type Channel, type ChannelProjectionOptions, ChannelRegistry, type CompiledSubAgentLike, type CustomAdapterOptions, type DeepAgentTypeConfigLike, type DefaultSubagentStates, type DefaultToolCall, type Event, type ExtendedMessageRole, type ExtractAgentConfig, type ExtractDeepAgentConfig, type ExtractSubAgentMiddleware, type FileMedia, type ImageMedia, type InferAgentToolCalls, type InferBag, type InferDeepAgentSubagents, type InferNodeNames, type InferStateType, type InferSubagentByName, type InferSubagentNames, type InferSubagentState, type InferSubagentStates, type InferToolCalls, type InferToolOutput, type IsAgentLike, type IsDeepAgentLike, MediaAssembler, type MediaAssemblerCallbacks, type MediaAssemblerOptions, MediaAssemblyError, type MediaAssemblyErrorKind, type MediaBase, type MediaBlockType, type MediaProjectionOptions, type MessageMetadata, type MessageMetadataMap, NAMESPACE_SEPARATOR, type ProjectionRuntime, type ProjectionSpec, ROOT_PUMP_CHANNELS, type RootEventBus, type RootSnapshot, type RunCompletedInfo, type RunExecutionInfo, type RunExecutionReason, type StoreListener, StreamController, type StreamControllerOptions, type StreamRespondAllOptions, type StreamRespondOptions, type StreamStopOptions, StreamStore, type StreamSubmitOptions, type SubAgentLike, SubagentDiscovery, type SubagentDiscoverySnapshot, type SubagentMap, type SubagentStateMap, type SubagentToolCall, type SubgraphByNodeMap, SubgraphDiscovery, type SubgraphDiscoverySnapshot, type SubgraphMap, type SubmissionQueueEntry, type SubmissionQueueSnapshot, type Target, type ToolCallFromTool, type ToolCallStatus, type TransportAdapter, type UseStreamCommonOptions, type UseStreamOptions, type VideoMedia, type WidenUpdateMessages, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; | ||
| export { type AcquiredProjection, type AgentServerAdapter, type AgentServerOptions, type AgentTypeConfigLike, type AnyMediaHandle, type AssembledToMessageInput, type AssembledToolCall, type AssembledToolCallFromTool, type AudioMedia, type Channel, type ChannelEffectOptions, type ChannelProjectionOptions, ChannelRegistry, type CompiledSubAgentLike, type CustomAdapterOptions, type DeepAgentTypeConfigLike, type DefaultSubagentStates, type DefaultToolCall, type Event, type ExtendedMessageRole, type ExtractAgentConfig, type ExtractDeepAgentConfig, type ExtractSubAgentMiddleware, type FileMedia, type ImageMedia, type InferAgentToolCalls, type InferBag, type InferDeepAgentSubagents, type InferNodeNames, type InferStateType, type InferSubagentByName, type InferSubagentNames, type InferSubagentState, type InferSubagentStates, type InferToolCalls, type InferToolOutput, type IsAgentLike, type IsDeepAgentLike, MediaAssembler, type MediaAssemblerCallbacks, type MediaAssemblerOptions, MediaAssemblyError, type MediaAssemblyErrorKind, type MediaBase, type MediaBlockType, type MediaProjectionOptions, type MessageMetadata, type MessageMetadataMap, NAMESPACE_SEPARATOR, type ProjectionRuntime, type ProjectionSpec, ROOT_PUMP_CHANNELS, type RootEventBus, type RootSnapshot, type RunCompletedInfo, type RunExecutionInfo, type RunExecutionReason, type StoreListener, StreamController, type StreamControllerOptions, type StreamRespondAllOptions, type StreamRespondOptions, type StreamStopOptions, StreamStore, type StreamSubmitOptions, type SubAgentLike, SubagentDiscovery, type SubagentDiscoverySnapshot, type SubagentMap, type SubagentStateMap, type SubagentToolCall, type SubgraphByNodeMap, SubgraphDiscovery, type SubgraphDiscoverySnapshot, type SubgraphMap, type SubmissionQueueEntry, type SubmissionQueueSnapshot, type Target, type ToolCallFromTool, type ToolCallStatus, type TransportAdapter, type UseStreamCommonOptions, type UseStreamOptions, type VideoMedia, type WidenUpdateMessages, acquireChannelEffect, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; |
@@ -21,2 +21,3 @@ import { DefaultToolCall, InferToolOutput, ToolCallFromTool } from "../types.messages.js"; | ||
| import { ChannelProjectionOptions, channelProjection } from "./projections/channel.js"; | ||
| import { ChannelEffectOptions, acquireChannelEffect } from "./projections/channel-effect.js"; | ||
| import { MediaProjectionOptions, audioProjection, filesProjection, imagesProjection, videoProjection } from "./projections/media.js"; | ||
@@ -26,2 +27,2 @@ import { AssembledToMessageInput, ExtendedMessageRole, assembledMessageToBaseMessage, assembledToBaseMessage } from "./assembled-to-message.js"; | ||
| import { Channel, Event } from "@langchain/protocol"; | ||
| export { type AcquiredProjection, type AgentServerAdapter, type AgentServerOptions, type AgentTypeConfigLike, type AnyMediaHandle, type AssembledToMessageInput, type AssembledToolCall, type AssembledToolCallFromTool, type AudioMedia, type Channel, type ChannelProjectionOptions, ChannelRegistry, type CompiledSubAgentLike, type CustomAdapterOptions, type DeepAgentTypeConfigLike, type DefaultSubagentStates, type DefaultToolCall, type Event, type ExtendedMessageRole, type ExtractAgentConfig, type ExtractDeepAgentConfig, type ExtractSubAgentMiddleware, type FileMedia, type ImageMedia, type InferAgentToolCalls, type InferBag, type InferDeepAgentSubagents, type InferNodeNames, type InferStateType, type InferSubagentByName, type InferSubagentNames, type InferSubagentState, type InferSubagentStates, type InferToolCalls, type InferToolOutput, type IsAgentLike, type IsDeepAgentLike, MediaAssembler, type MediaAssemblerCallbacks, type MediaAssemblerOptions, MediaAssemblyError, type MediaAssemblyErrorKind, type MediaBase, type MediaBlockType, type MediaProjectionOptions, type MessageMetadata, type MessageMetadataMap, NAMESPACE_SEPARATOR, type ProjectionRuntime, type ProjectionSpec, ROOT_PUMP_CHANNELS, type RootEventBus, type RootSnapshot, type RunCompletedInfo, type RunExecutionInfo, type RunExecutionReason, type StoreListener, StreamController, type StreamControllerOptions, type StreamRespondAllOptions, type StreamRespondOptions, type StreamStopOptions, StreamStore, type StreamSubmitOptions, type SubAgentLike, SubagentDiscovery, type SubagentDiscoverySnapshot, type SubagentMap, type SubagentStateMap, type SubagentToolCall, type SubgraphByNodeMap, SubgraphDiscovery, type SubgraphDiscoverySnapshot, type SubgraphMap, type SubmissionQueueEntry, type SubmissionQueueSnapshot, type Target, type ToolCallFromTool, type ToolCallStatus, type TransportAdapter, type UseStreamCommonOptions, type UseStreamOptions, type VideoMedia, type WidenUpdateMessages, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; | ||
| export { type AcquiredProjection, type AgentServerAdapter, type AgentServerOptions, type AgentTypeConfigLike, type AnyMediaHandle, type AssembledToMessageInput, type AssembledToolCall, type AssembledToolCallFromTool, type AudioMedia, type Channel, type ChannelEffectOptions, type ChannelProjectionOptions, ChannelRegistry, type CompiledSubAgentLike, type CustomAdapterOptions, type DeepAgentTypeConfigLike, type DefaultSubagentStates, type DefaultToolCall, type Event, type ExtendedMessageRole, type ExtractAgentConfig, type ExtractDeepAgentConfig, type ExtractSubAgentMiddleware, type FileMedia, type ImageMedia, type InferAgentToolCalls, type InferBag, type InferDeepAgentSubagents, type InferNodeNames, type InferStateType, type InferSubagentByName, type InferSubagentNames, type InferSubagentState, type InferSubagentStates, type InferToolCalls, type InferToolOutput, type IsAgentLike, type IsDeepAgentLike, MediaAssembler, type MediaAssemblerCallbacks, type MediaAssemblerOptions, MediaAssemblyError, type MediaAssemblyErrorKind, type MediaBase, type MediaBlockType, type MediaProjectionOptions, type MessageMetadata, type MessageMetadataMap, NAMESPACE_SEPARATOR, type ProjectionRuntime, type ProjectionSpec, ROOT_PUMP_CHANNELS, type RootEventBus, type RootSnapshot, type RunCompletedInfo, type RunExecutionInfo, type RunExecutionReason, type StoreListener, StreamController, type StreamControllerOptions, type StreamRespondAllOptions, type StreamRespondOptions, type StreamStopOptions, StreamStore, type StreamSubmitOptions, type SubAgentLike, SubagentDiscovery, type SubagentDiscoverySnapshot, type SubagentMap, type SubagentStateMap, type SubagentToolCall, type SubgraphByNodeMap, SubgraphDiscovery, type SubgraphDiscoverySnapshot, type SubgraphMap, type SubmissionQueueEntry, type SubmissionQueueSnapshot, type Target, type ToolCallFromTool, type ToolCallStatus, type TransportAdapter, type UseStreamCommonOptions, type UseStreamOptions, type VideoMedia, type WidenUpdateMessages, acquireChannelEffect, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; |
@@ -16,4 +16,5 @@ import { parseToolOutput, parseToolPayload } from "../client/stream/handles/tools.js"; | ||
| import { channelProjection } from "./projections/channel.js"; | ||
| import { acquireChannelEffect } from "./projections/channel-effect.js"; | ||
| import { audioProjection, filesProjection, imagesProjection, videoProjection } from "./projections/media.js"; | ||
| import "./projections/index.js"; | ||
| export { ChannelRegistry, MediaAssembler, MediaAssemblyError, NAMESPACE_SEPARATOR, ROOT_PUMP_CHANNELS, StreamController, StreamStore, SubagentDiscovery, SubgraphDiscovery, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; | ||
| export { ChannelRegistry, MediaAssembler, MediaAssemblyError, NAMESPACE_SEPARATOR, ROOT_PUMP_CHANNELS, StreamController, StreamStore, SubagentDiscovery, SubgraphDiscovery, acquireChannelEffect, assembledMessageToBaseMessage, assembledToBaseMessage, audioProjection, channelProjection, extensionProjection, filesProjection, imagesProjection, messagesProjection, parseToolOutput, parseToolPayload, toolCallsProjection, valuesProjection, videoProjection }; |
@@ -6,2 +6,3 @@ require("./messages.cjs"); | ||
| require("./channel.cjs"); | ||
| require("./channel-effect.cjs"); | ||
| require("./media.cjs"); |
@@ -6,2 +6,3 @@ import { messagesProjection } from "./messages.js"; | ||
| import { ChannelProjectionOptions, channelProjection } from "./channel.js"; | ||
| import { ChannelEffectOptions, acquireChannelEffect } from "./channel-effect.js"; | ||
| import { MediaProjectionOptions, audioProjection, filesProjection, imagesProjection, videoProjection } from "./media.js"; |
@@ -6,3 +6,4 @@ import "./messages.js"; | ||
| import "./channel.js"; | ||
| import "./channel-effect.js"; | ||
| import "./media.js"; | ||
| export {}; |
@@ -83,2 +83,33 @@ const require_messages = require("../client/stream/messages.cjs"); | ||
| /** | ||
| * Message ids seeded as complete-and-final from an idle thread's | ||
| * `getState()` snapshot. An idle thread defers its root SSE pump, and | ||
| * the first `submit()` brings it up — at which point the transport | ||
| * replays the finished run from `seq=0`. Unlike the `values` channel | ||
| * (guarded by {@link #maxStep}), `messages`-channel deltas carry no | ||
| * step, so that replay would otherwise rebuild each already-complete | ||
| * message from an empty `message-start` and re-stream the whole turn | ||
| * token-by-token, clobbering the seeded tail (a visible "messages | ||
| * replay" on the first submit). Deltas for a sealed id are dropped in | ||
| * {@link handleMessage}. The seal is lifted once a checkpoint advances | ||
| * strictly past {@link #sealStep} (see {@link applyValues}) or on | ||
| * thread rebind ({@link reset}). New ids from the next run are never | ||
| * sealed, so they stream normally. | ||
| */ | ||
| #sealedMessageIds = /* @__PURE__ */ new Set(); | ||
| /** | ||
| * High-water {@link #maxStep} captured when {@link sealMessageIds} ran, | ||
| * i.e. the seed checkpoint's step (or `undefined` when `getState()` | ||
| * carried no `metadata.step`). It is the boundary between the replayed | ||
| * idle history (steps `<= #sealStep`, emitted by the deferred pump's | ||
| * `seq=0` replay) and the new run (steps `> #sealStep`); only a | ||
| * checkpoint strictly past it lifts the seal. Without this boundary the | ||
| * replayed old-run checkpoints — which themselves carry increasing | ||
| * steps — would advance {@link #maxStep} and lift the seal mid-replay, | ||
| * reopening the clobber. When the seed step is unknown the boundary | ||
| * stays `undefined` and the seal holds until {@link reset}; the | ||
| * `values` channel (which ignores the seal) still reconciles any | ||
| * genuine change to a sealed id, only its streamed deltas are dropped. | ||
| */ | ||
| #sealStep = void 0; | ||
| /** | ||
| * @param params.messagesKey - Key inside `values` that holds the | ||
@@ -106,4 +137,26 @@ * message array. | ||
| this.#maxStep = void 0; | ||
| this.#sealedMessageIds.clear(); | ||
| this.#sealStep = void 0; | ||
| } | ||
| /** | ||
| * Seal message ids so the streamed `messages` channel cannot downgrade | ||
| * them to partial re-streams. Called by {@link StreamController.hydrate} | ||
| * after seeding an idle thread, whose deferred pump replays the finished | ||
| * run from `seq=0` on the first submit. | ||
| * | ||
| * Captures the current {@link #maxStep} as the lift boundary | ||
| * ({@link #sealStep}). The seal is applied immediately after the seed's | ||
| * `getState()` snapshot is reconciled, so `#maxStep` here is the seed | ||
| * step (or `undefined` when `getState()` carried no `metadata.step`). | ||
| * The seal is lifted once a checkpoint advances strictly past that | ||
| * boundary (see {@link applyValues}) or on thread rebind | ||
| * ({@link reset}). | ||
| * | ||
| * @param ids - Complete message ids from the idle `getState()` seed. | ||
| */ | ||
| sealMessageIds(ids) { | ||
| for (const id of ids) this.#sealedMessageIds.add(id); | ||
| if (this.#sealStep == null) this.#sealStep = this.#maxStep; | ||
| } | ||
| /** | ||
| * Record a `namespace → tool_call_id` mapping captured from a root | ||
@@ -156,2 +209,3 @@ * `tool-started` event. | ||
| if (id == null) return; | ||
| if (this.#sealedMessageIds.has(id)) return; | ||
| const captured = this.#roles.get(id) ?? { role: "ai" }; | ||
@@ -201,2 +255,3 @@ const base = require_assembled_to_message.assembledMessageToBaseMessage(update.message, captured.role, { toolCallId: captured.toolCallId }); | ||
| if (step != null && (this.#maxStep == null || step > this.#maxStep)) this.#maxStep = step; | ||
| if (this.#sealedMessageIds.size > 0 && step != null && this.#sealStep != null && step > this.#sealStep) this.#sealedMessageIds.clear(); | ||
| if (nextMessages.length === 0) { | ||
@@ -203,0 +258,0 @@ if (stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)) return; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"root-message-projection.cjs","names":["#messagesKey","#store","MessageAssembler","#roles","#indexById","#toolCallIdByNamespace","#assembler","#valuesMessageIds","#pendingMessages","#pendingValues","#flushScheduled","#maxStep","namespaceKey","assembledMessageToBaseMessage","messagesEqual","#scheduleFlush","reconcileMessagesFromValues","shouldPreferValuesMessageForToolCalls","buildMessageIndex","#flushPending"],"sources":["../../src/stream/root-message-projection.ts"],"sourcesContent":["/**\n * Root-namespace message projection.\n *\n * # What this module is\n *\n * The {@link RootMessageProjection} is the piece of the\n * {@link StreamController} that owns \"what messages does the root\n * namespace currently contain?\". It assembles streamed message deltas\n * via {@link MessageAssembler}, reconciles them against authoritative\n * `values.messages` snapshots from the server, and writes the merged\n * list back into the controller's root snapshot store.\n *\n * # Two streams of truth\n *\n * Root messages arrive on two channels and need to merge cleanly:\n *\n * - **`messages` channel.** Token-level deltas that build messages\n * incrementally. The {@link MessageAssembler} keeps partial\n * messages by id and emits an updated `BaseMessage` per delta.\n * - **`values` channel.** Periodic full-state snapshots that include\n * the authoritative messages array. Used for ordering, removals,\n * and forks (where the streamed messages may pre-date the new\n * timeline).\n *\n * The reconciliation rules (delegated to\n * {@link reconcileMessagesFromValues}) preserve in-flight streamed\n * content while letting values dictate ordering and removals.\n *\n * # Tool-message namespace correlation\n *\n * Tool messages arrive on `messages-start` events with `role: \"tool\"`\n * but the start event doesn't always include a `tool_call_id`. We\n * recover it via three fallbacks:\n *\n * 1. The start event itself, when the server includes it.\n * 2. The legacy `<id>-tool-<call_id>` message id format.\n * 3. The most recent `tool-started` event recorded under the same\n * namespace via {@link recordToolCallNamespace}.\n *\n * Without this correlation, tool messages render with empty\n * `tool_call_id` and downstream UIs can't pair them with the\n * originating tool call.\n *\n * # Store-write batching\n *\n * Every {@link handleMessage} / {@link applyValues} call updates the\n * in-projection bookkeeping (assembler state, id index, role cache)\n * synchronously, then stages the new `messages` / `values` into a\n * pending buffer and schedules a `setTimeout(0)` flush. A single\n * coalesced `store.setState` runs at the next macrotask boundary.\n *\n * The motivation is the long-replay freeze: a thread with hundreds\n * of messages replays through the `messages` channel on refresh or\n * mid-run join. Those events drain through the controller's\n * `for await` pump as a long microtask chain. Per-event\n * `store.setState` notifies `useSyncExternalStore` per event, and\n * after enough notifications React's `nestedUpdateCount` guard trips\n * with \"Maximum update depth exceeded\", permanently freezing the UI\n * on the first few messages. Coalescing to one notification per\n * macrotask lets React's scheduler commit between flushes.\n *\n * # Lifecycle\n *\n * - `handleMessage(event)` — apply a `messages` event delta.\n * - `applyValues(values, msgs)` — merge a `values` snapshot.\n * - `recordToolCallNamespace(ns, id)` — capture `namespace → tool_call_id`\n * so subsequent tool message starts can recover the id.\n * - `reset()` — clear all state on thread rebind.\n */\nimport type {\n MessagesEvent,\n MessageRole,\n MessageStartData,\n} from \"@langchain/protocol\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport { MessageAssembler } from \"../client/stream/messages.js\";\nimport {\n assembledMessageToBaseMessage,\n type ExtendedMessageRole,\n} from \"./assembled-to-message.js\";\nimport type { StreamStore } from \"./store.js\";\nimport type { RootSnapshot } from \"./types.js\";\nimport { namespaceKey } from \"./namespace.js\";\nimport {\n buildMessageIndex,\n messagesEqual,\n reconcileMessagesFromValues,\n shouldPreferValuesMessageForToolCalls,\n} from \"./message-reconciliation.js\";\n\n/**\n * Root-namespace message projection. Owns the merge between the\n * `messages` (streamed deltas) and `values` (authoritative\n * snapshots) channels for the root namespace.\n *\n * @typeParam StateType - Root state shape; the messages array is read\n * from `values[messagesKey]`.\n * @typeParam InterruptType - Shape of root protocol interrupts (forwarded\n * into `RootSnapshot` updates).\n */\nexport class RootMessageProjection<\n StateType extends object,\n InterruptType = unknown,\n> {\n /**\n * Key inside `values` that holds the message array. Defaults to\n * `\"messages\"` in the controller; configurable for state graphs\n * that surface messages under a different slot.\n */\n readonly #messagesKey: string;\n\n /** Root snapshot store written to on every merge. */\n readonly #store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n\n /**\n * Stateful chunk assembler for in-flight messages. Reset (via a\n * fresh instance) on every {@link reset} so a new thread starts\n * with no half-built messages from the previous one.\n */\n #assembler = new MessageAssembler();\n\n /**\n * `messageId → role/toolCallId` captured from `message-start` events.\n * The assembler's intermediate output drops these fields, so we cache\n * them at start-time and reapply when projecting to a `BaseMessage`.\n */\n readonly #roles = new Map<\n string,\n { role: ExtendedMessageRole; toolCallId?: string }\n >();\n\n /**\n * `messageId → position in #store.messages` for fast in-place\n * updates as deltas arrive. Rebuilt on every full reconciliation\n * driven by a `values` event.\n */\n readonly #indexById = new Map<string, number>();\n\n /**\n * Ids observed in the most recent `values.messages` snapshot.\n * Reconciliation uses this to detect server-side removals: a\n * previously-seen id missing from the next snapshot means it was\n * removed by the server (and should drop from the projection).\n */\n #valuesMessageIds = new Set<string>();\n\n /**\n * `namespaceKey → tool_call_id` captured from root `tool-started`\n * events. Used as a fallback when a tool-role `message-start` is\n * missing its `tool_call_id` field.\n */\n readonly #toolCallIdByNamespace = new Map<string, string>();\n\n /**\n * Coalescing buffer for store writes. {@link handleMessage} and\n * {@link applyValues} stage their computed `messages` / `values`\n * here instead of calling `store.setState` per event. A single\n * `setTimeout(0)` flush commits them in one `setState`, so a\n * burst of SSE events draining as a microtask chain becomes one\n * store notification at the next macrotask boundary.\n *\n * `null` means \"no staged write\" — once a flush settles, the\n * slots are cleared so the next call starts from the latest\n * committed store snapshot.\n */\n #pendingMessages: BaseMessage[] | null = null;\n #pendingValues: StateType | null = null;\n #flushScheduled = false;\n\n /**\n * Highest checkpoint `step` whose `values` snapshot has been applied.\n * Seeded by {@link StreamController.hydrate} from `getState()` and\n * advanced by live `values` events. A snapshot arriving with a lower\n * step is an older checkpoint replayed by the content pump on\n * reconnect; it is reconciled in add-only mode so it cannot remove\n * the seeded message tail (the final assistant turn). `undefined`\n * until the first step-bearing snapshot, where the legacy\n * remove-on-absence behavior is preserved.\n */\n #maxStep: number | undefined = undefined;\n\n /**\n * @param params.messagesKey - Key inside `values` that holds the\n * message array.\n * @param params.store - Root snapshot store to mutate.\n */\n constructor(params: {\n messagesKey: string;\n store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n }) {\n this.#messagesKey = params.messagesKey;\n this.#store = params.store;\n }\n\n /**\n * Drop all per-thread state. Called by the controller on thread\n * rebind / dispose so a swap doesn't surface stale messages.\n */\n reset(): void {\n this.#assembler = new MessageAssembler();\n this.#roles.clear();\n this.#indexById.clear();\n this.#valuesMessageIds = new Set();\n this.#toolCallIdByNamespace.clear();\n // Drop any unflushed pending writes — they were computed against\n // the previous thread's baseline and committing them after a\n // rebind would bleed stale messages into the new thread.\n this.#pendingMessages = null;\n this.#pendingValues = null;\n this.#flushScheduled = false;\n this.#maxStep = undefined;\n }\n\n /**\n * Record a `namespace → tool_call_id` mapping captured from a root\n * `tool-started` event.\n *\n * The companion tool-role `message-start` event may not carry a\n * `tool_call_id`, so we fall back to the most recent value recorded\n * here for the same namespace.\n *\n * @param namespace - Event namespace from the `tool-started` event.\n * @param toolCallId - Tool call id from the same event.\n */\n recordToolCallNamespace(\n namespace: readonly string[],\n toolCallId: string\n ): void {\n this.#toolCallIdByNamespace.set(namespaceKey(namespace), toolCallId);\n }\n\n /**\n * Apply a `messages` channel event to the projection.\n *\n * Captures role/tool metadata on `message-start`, feeds the chunk\n * to the assembler, projects the assembled output to a\n * {@link BaseMessage}, and either appends or in-place updates the\n * pending messages buffer based on whether the id was seen before.\n *\n * @param event - The `messages` channel event to consume.\n */\n handleMessage(event: MessagesEvent): void {\n const data = event.params.data;\n if (data.event === \"message-start\") {\n const startData = data as MessageStartData;\n const role = (startData.role ?? \"ai\") as MessageRole;\n const extendedRole =\n (startData as { role?: ExtendedMessageRole }).role ?? role;\n let toolCallId = (startData as { tool_call_id?: string }).tool_call_id;\n // Tool messages need a tool_call_id to render. Fall back through:\n // 1. legacy `<id>-tool-<call_id>` message id format\n // 2. namespace-recorded tool_call_id (from #recordToolCallNamespace)\n if (extendedRole === \"tool\" && toolCallId == null) {\n const messageId = startData.id;\n if (messageId != null) {\n const match = /-tool-(.+)$/.exec(messageId);\n if (match != null) toolCallId = match[1];\n }\n if (toolCallId == null) {\n toolCallId = this.#toolCallIdByNamespace.get(\n namespaceKey(event.params.namespace)\n );\n }\n }\n if (startData.id != null) {\n this.#roles.set(startData.id, {\n role: extendedRole,\n toolCallId,\n });\n }\n }\n\n const update = this.#assembler.consume(event);\n if (update == null) return;\n const id = update.message.id;\n if (id == null) return;\n const captured = this.#roles.get(id) ?? { role: \"ai\" as const };\n const base = assembledMessageToBaseMessage(update.message, captured.role, {\n toolCallId: captured.toolCallId,\n });\n\n // Compute against the pending baseline if we have one (so an\n // earlier handleMessage in the same tick is the input to this\n // one), else against the latest committed store snapshot.\n // `#indexById` is the synchronous source of truth for \"where is\n // each id in the current messages list\" — every code path below\n // keeps it in sync before returning.\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const existingIdx = this.#indexById.get(id);\n let messages: BaseMessage[];\n if (existingIdx == null) {\n this.#indexById.set(id, baselineMessages.length);\n messages = [...baselineMessages, base];\n } else if (messagesEqual(baselineMessages[existingIdx], base)) {\n // Identical re-emission — skip the store write to keep\n // snapshot identity stable.\n return;\n } else {\n messages = baselineMessages.slice();\n messages[existingIdx] = base;\n }\n\n // Mirror the new messages list into `values[messagesKey]` so\n // direct `values` reads (used by some hooks and by the eventual\n // `values` reconciliation) stay in sync.\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const values = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n messages\n );\n this.#pendingMessages = messages;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Reconcile a full `values` snapshot into the projection.\n *\n * Delegates the merge to {@link reconcileMessagesFromValues}:\n * values stays authoritative for ordering and removals, while\n * streamed in-flight messages keep their content until the server\n * echoes them back. Empty messages just refresh the values blob.\n *\n * Rebuilds {@link #indexById} after the merge so subsequent delta\n * applications target the new positions.\n *\n * @param nextValues - Full values snapshot from the `values` event.\n * @param nextMessages - The messages array extracted from\n * `values[messagesKey]` and coerced to `BaseMessage` instances.\n * @param opts.step - Checkpoint superstep for this snapshot, when\n * known. A snapshot whose step is below the highest applied step is\n * treated as a stale reconnect replay and reconciled add-only.\n */\n applyValues(\n nextValues: StateType,\n nextMessages: BaseMessage[],\n opts?: { step?: number }\n ): void {\n const baselineSnapshot = this.#store.getSnapshot();\n const baselineMessages = this.#pendingMessages ?? baselineSnapshot.messages;\n const baselineValues = this.#pendingValues ?? baselineSnapshot.values;\n\n const step = opts?.step;\n // Stale only when we have both a prior high-water step and a lower\n // incoming step. A missing step preserves the legacy semantics.\n const addOnly =\n step != null && this.#maxStep != null && step < this.#maxStep;\n if (step != null && (this.#maxStep == null || step > this.#maxStep)) {\n this.#maxStep = step;\n }\n\n if (nextMessages.length === 0) {\n if (\n stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)\n ) {\n return;\n }\n // Mirror the current `messages` list back into the values slot\n // so the staged snapshot stays consistent with the (separately\n // tracked) messages array.\n this.#pendingValues = syncMessagesIntoValues(\n nextValues,\n this.#messagesKey,\n baselineMessages\n );\n this.#scheduleFlush();\n return;\n }\n\n const reconciliation = reconcileMessagesFromValues({\n valueMessages: nextMessages,\n currentMessages: baselineMessages,\n currentIndexById: this.#indexById,\n previousValueMessageIds: this.#valuesMessageIds,\n preferValuesMessage: shouldPreferValuesMessageForToolCalls,\n addOnly,\n });\n // A stale replay snapshot must not shrink the authoritative id set:\n // keep the (larger) seeded set so a genuinely-newer removal is still\n // detected once the timeline advances past the seed.\n if (!addOnly) this.#valuesMessageIds = reconciliation.valueMessageIds;\n const messages = reconciliation.messages as BaseMessage[];\n const values = {\n ...(nextValues as Record<string, unknown>),\n [this.#messagesKey]: messages,\n } as StateType;\n if (\n messages === baselineMessages &&\n stateValuesShallowEqual(baselineValues, values, this.#messagesKey)\n ) {\n return;\n }\n\n // Reconciliation may reorder, drop, or substitute messages, so\n // rebuild the id → index map to match the new array.\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(messages)) {\n this.#indexById.set(id, idx);\n }\n this.#pendingMessages = messages;\n this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Append messages applied optimistically by a local `submit()`,\n * keyed by id so the eventual server echo reconciles cleanly.\n *\n * Unlike {@link applyValues}, the supplied messages are *not* treated\n * as an authoritative ordered snapshot: they are appended to the end\n * of the current projection (or replaced in place when the id already\n * exists), preserving prior history ordering. When the server later\n * emits a `values` snapshot containing the same ids,\n * {@link applyValues} → {@link reconcileMessagesFromValues} takes over\n * (server ordering wins, the echoed message replaces the optimistic\n * one).\n *\n * Non-message input keys are shallow-merged into `values` via\n * `extraValues`; they are dropped/overwritten automatically by the\n * first server `values` event (which rebuilds `values` from the\n * server snapshot), or rolled back via {@link restoreValueKeys} when\n * the run fails before any echo.\n *\n * @param messages - Optimistic messages (already coerced to\n * `BaseMessage` instances, each carrying a stable id).\n * @param extraValues - Non-message input keys to shallow-merge into\n * `values`.\n */\n appendOptimistic(\n messages: BaseMessage[],\n extraValues?: Record<string, unknown>\n ): void {\n let working = this.#pendingMessages ?? this.#store.getSnapshot().messages;\n let mutated = false;\n for (const message of messages) {\n const id = message.id;\n if (id == null) continue;\n const existingIdx = this.#indexById.get(id);\n if (existingIdx == null) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n this.#indexById.set(id, working.length);\n working.push(message);\n } else if (!messagesEqual(working[existingIdx], message)) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n working[existingIdx] = message;\n }\n }\n\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n let values = baselineValues;\n if (extraValues != null && Object.keys(extraValues).length > 0) {\n values = { ...(baselineValues as object), ...extraValues } as StateType;\n }\n values = syncMessagesIntoValues(values, this.#messagesKey, working);\n if (!mutated && values === baselineValues) return;\n this.#pendingMessages = working;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Drop optimistic messages by id without disturbing the rest of the\n * projection. Used by {@link StreamController.hydrate} to remove\n * never-persisted optimistic messages (`pending` / `failed`) so a\n * reload converges to server truth.\n *\n * @param ids - Message ids to remove.\n */\n dropOptimisticMessages(ids: ReadonlySet<string>): void {\n if (ids.size === 0) return;\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const next = baselineMessages.filter((m) => m.id == null || !ids.has(m.id));\n if (next.length === baselineMessages.length) return;\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(next)) {\n this.#indexById.set(id, idx);\n }\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n this.#pendingMessages = next;\n this.#pendingValues = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n next\n );\n this.#scheduleFlush();\n }\n\n /**\n * Restore (or delete) `values` keys that were optimistically merged\n * by {@link appendOptimistic} but never echoed by the server — i.e.\n * roll back non-message optimistic state when the run fails before\n * any `values` event lands. Messages are left untouched (kept on\n * failure per the optimistic contract).\n *\n * @param restore - Per-key pre-submit snapshot: when `hadKey` is\n * false the key is deleted, otherwise it is reset to `prevValue`.\n */\n restoreValueKeys(\n restore: ReadonlyArray<{\n key: string;\n hadKey: boolean;\n prevValue: unknown;\n }>\n ): void {\n if (restore.length === 0) return;\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const next = { ...(baselineValues as Record<string, unknown>) };\n let changed = false;\n for (const { key, hadKey, prevValue } of restore) {\n if (key === this.#messagesKey) continue;\n if (hadKey) {\n if (!Object.is(next[key], prevValue)) {\n next[key] = prevValue;\n changed = true;\n }\n } else if (Object.prototype.hasOwnProperty.call(next, key)) {\n delete next[key];\n changed = true;\n }\n }\n if (!changed) return;\n this.#pendingValues = next as StateType;\n this.#scheduleFlush();\n }\n\n /**\n * Schedule a coalesced flush on the next macrotask. Idempotent\n * within a tick — multiple `handleMessage` / `applyValues` calls\n * before the flush fires collapse into one store write.\n *\n * `setTimeout(0)` is a macrotask: it runs after the current\n * microtask chain drains, so a burst of SSE events processed by\n * the controller's `for await` pump becomes one `store.setState`\n * (and therefore one `useSyncExternalStore` notification).\n */\n #scheduleFlush = (): void => {\n if (this.#flushScheduled) return;\n this.#flushScheduled = true;\n setTimeout(this.#flushPending, 0);\n };\n\n /**\n * Drain `#pendingMessages` / `#pendingValues` to the store in a\n * single `setState` call.\n */\n #flushPending = (): void => {\n this.#flushScheduled = false;\n const messages = this.#pendingMessages;\n const values = this.#pendingValues;\n this.#pendingMessages = null;\n this.#pendingValues = null;\n if (messages == null && values == null) return;\n this.#store.setState((s) => {\n // Other rootStore mutators (controller-driven `isLoading`,\n // `interrupts`, `toolCalls`, etc.) do not touch `s.messages`\n // / `s.values`, so a last-write-wins commit on those two\n // fields is safe.\n if (messages == null) {\n return values == null ? s : { ...s, values };\n }\n if (values == null) return { ...s, messages };\n return { ...s, messages, values };\n });\n };\n}\n\n/**\n * Mirror a freshly-updated message list into `values[messagesKey]`.\n *\n * Returns the same `values` reference when the list is already\n * equal-by-content so the caller can keep the existing snapshot\n * identity (and avoid spurious `setSnapshot` notifications).\n */\nfunction syncMessagesIntoValues<StateType extends object>(\n values: StateType,\n messagesKey: string,\n messages: BaseMessage[]\n): StateType {\n const record = values as Record<string, unknown>;\n const current = record[messagesKey];\n if (Array.isArray(current) && messagesEqualList(current, messages)) {\n return values;\n }\n return {\n ...record,\n [messagesKey]: messages,\n } as StateType;\n}\n\n/**\n * True when two `BaseMessage` arrays carry the same per-message\n * content (using {@link messagesEqual}).\n */\nfunction messagesEqualList(\n previous: readonly BaseMessage[],\n next: readonly BaseMessage[]\n): boolean {\n if (previous === next) return true;\n if (previous.length !== next.length) return false;\n for (let i = 0; i < previous.length; i += 1) {\n if (!messagesEqual(previous[i], next[i])) return false;\n }\n return true;\n}\n\n/**\n * Shallow-equal for `values` objects, *ignoring* the messages slot.\n *\n * The messages array is compared separately by the caller (via\n * {@link messagesEqualList}) because both arrays contain class\n * instances whose JSON representation is not stable across reads.\n */\nfunction stateValuesShallowEqual(\n previous: object,\n next: object,\n messagesKey: string\n): boolean {\n if (previous === next) return true;\n const previousRecord = previous as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n const previousKeys = Object.keys(previousRecord);\n const nextKeys = Object.keys(nextRecord);\n if (previousKeys.length !== nextKeys.length) return false;\n for (const key of previousKeys) {\n if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) return false;\n const previousValue = previousRecord[key];\n const nextValue = nextRecord[key];\n if (\n key === messagesKey &&\n Array.isArray(previousValue) &&\n Array.isArray(nextValue)\n ) {\n continue;\n }\n if (!Object.is(previousValue, nextValue)) return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoGA,IAAa,wBAAb,MAGE;;;;;;CAMA;;CAGA;;;;;;CAOA,aAAa,IAAIE,iBAAAA,kBAAkB;;;;;;CAOnC,yBAAkB,IAAI,KAGnB;;;;;;CAOH,6BAAsB,IAAI,KAAqB;;;;;;;CAQ/C,oCAAoB,IAAI,KAAa;;;;;;CAOrC,yCAAkC,IAAI,KAAqB;;;;;;;;;;;;;CAc3D,mBAAyC;CACzC,iBAAmC;CACnC,kBAAkB;;;;;;;;;;;CAYlB,WAA+B,KAAA;;;;;;CAO/B,YAAY,QAGT;AACD,QAAA,cAAoB,OAAO;AAC3B,QAAA,QAAc,OAAO;;;;;;CAOvB,QAAc;AACZ,QAAA,YAAkB,IAAIA,iBAAAA,kBAAkB;AACxC,QAAA,MAAY,OAAO;AACnB,QAAA,UAAgB,OAAO;AACvB,QAAA,mCAAyB,IAAI,KAAK;AAClC,QAAA,sBAA4B,OAAO;AAInC,QAAA,kBAAwB;AACxB,QAAA,gBAAsB;AACtB,QAAA,iBAAuB;AACvB,QAAA,UAAgB,KAAA;;;;;;;;;;;;;CAclB,wBACE,WACA,YACM;AACN,QAAA,sBAA4B,IAAIU,kBAAAA,aAAa,UAAU,EAAE,WAAW;;;;;;;;;;;;CAatE,cAAc,OAA4B;EACxC,MAAM,OAAO,MAAM,OAAO;AAC1B,MAAI,KAAK,U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WAAW,KAAK,OAAQ,QAAO;AAC5C,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,EACxC,KAAI,CAACJ,+BAAAA,cAAc,SAAS,IAAI,KAAK,GAAG,CAAE,QAAO;AAEnD,QAAO;;;;;;;;;AAUT,SAAS,wBACP,UACA,MACA,aACS;AACT,KAAI,aAAa,KAAM,QAAO;CAC9B,MAAM,iBAAiB;CACvB,MAAM,aAAa;CACnB,MAAM,eAAe,OAAO,KAAK,eAAe;CAChD,MAAM,WAAW,OAAO,KAAK,WAAW;AACxC,KAAI,aAAa,WAAW,SAAS,OAAQ,QAAO;AACpD,MAAK,MAAM,OAAO,cAAc;AAC9B,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,YAAY,IAAI,CAAE,QAAO;EACnE,MAAM,gBAAgB,eAAe;EACrC,MAAM,YAAY,WAAW;AAC7B,MACE,QAAQ,eACR,MAAM,QAAQ,cAAc,IAC5B,MAAM,QAAQ,UAAU,CAExB;AAEF,MAAI,CAAC,OAAO,GAAG,eAAe,UAAU,CAAE,QAAO;;AAEnD,QAAO"} | ||
| {"version":3,"file":"root-message-projection.cjs","names":["#messagesKey","#store","MessageAssembler","#roles","#indexById","#toolCallIdByNamespace","#sealedMessageIds","#assembler","#valuesMessageIds","#pendingMessages","#pendingValues","#flushScheduled","#maxStep","#sealStep","namespaceKey","assembledMessageToBaseMessage","messagesEqual","#scheduleFlush","reconcileMessagesFromValues","shouldPreferValuesMessageForToolCalls","buildMessageIndex","#flushPending"],"sources":["../../src/stream/root-message-projection.ts"],"sourcesContent":["/**\n * Root-namespace message projection.\n *\n * # What this module is\n *\n * The {@link RootMessageProjection} is the piece of the\n * {@link StreamController} that owns \"what messages does the root\n * namespace currently contain?\". It assembles streamed message deltas\n * via {@link MessageAssembler}, reconciles them against authoritative\n * `values.messages` snapshots from the server, and writes the merged\n * list back into the controller's root snapshot store.\n *\n * # Two streams of truth\n *\n * Root messages arrive on two channels and need to merge cleanly:\n *\n * - **`messages` channel.** Token-level deltas that build messages\n * incrementally. The {@link MessageAssembler} keeps partial\n * messages by id and emits an updated `BaseMessage` per delta.\n * - **`values` channel.** Periodic full-state snapshots that include\n * the authoritative messages array. Used for ordering, removals,\n * and forks (where the streamed messages may pre-date the new\n * timeline).\n *\n * The reconciliation rules (delegated to\n * {@link reconcileMessagesFromValues}) preserve in-flight streamed\n * content while letting values dictate ordering and removals.\n *\n * # Tool-message namespace correlation\n *\n * Tool messages arrive on `messages-start` events with `role: \"tool\"`\n * but the start event doesn't always include a `tool_call_id`. We\n * recover it via three fallbacks:\n *\n * 1. The start event itself, when the server includes it.\n * 2. The legacy `<id>-tool-<call_id>` message id format.\n * 3. The most recent `tool-started` event recorded under the same\n * namespace via {@link recordToolCallNamespace}.\n *\n * Without this correlation, tool messages render with empty\n * `tool_call_id` and downstream UIs can't pair them with the\n * originating tool call.\n *\n * # Store-write batching\n *\n * Every {@link handleMessage} / {@link applyValues} call updates the\n * in-projection bookkeeping (assembler state, id index, role cache)\n * synchronously, then stages the new `messages` / `values` into a\n * pending buffer and schedules a `setTimeout(0)` flush. A single\n * coalesced `store.setState` runs at the next macrotask boundary.\n *\n * The motivation is the long-replay freeze: a thread with hundreds\n * of messages replays through the `messages` channel on refresh or\n * mid-run join. Those events drain through the controller's\n * `for await` pump as a long microtask chain. Per-event\n * `store.setState` notifies `useSyncExternalStore` per event, and\n * after enough notifications React's `nestedUpdateCount` guard trips\n * with \"Maximum update depth exceeded\", permanently freezing the UI\n * on the first few messages. Coalescing to one notification per\n * macrotask lets React's scheduler commit between flushes.\n *\n * # Lifecycle\n *\n * - `handleMessage(event)` — apply a `messages` event delta.\n * - `applyValues(values, msgs)` — merge a `values` snapshot.\n * - `recordToolCallNamespace(ns, id)` — capture `namespace → tool_call_id`\n * so subsequent tool message starts can recover the id.\n * - `reset()` — clear all state on thread rebind.\n */\nimport type {\n MessagesEvent,\n MessageRole,\n MessageStartData,\n} from \"@langchain/protocol\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport { MessageAssembler } from \"../client/stream/messages.js\";\nimport {\n assembledMessageToBaseMessage,\n type ExtendedMessageRole,\n} from \"./assembled-to-message.js\";\nimport type { StreamStore } from \"./store.js\";\nimport type { RootSnapshot } from \"./types.js\";\nimport { namespaceKey } from \"./namespace.js\";\nimport {\n buildMessageIndex,\n messagesEqual,\n reconcileMessagesFromValues,\n shouldPreferValuesMessageForToolCalls,\n} from \"./message-reconciliation.js\";\n\n/**\n * Root-namespace message projection. Owns the merge between the\n * `messages` (streamed deltas) and `values` (authoritative\n * snapshots) channels for the root namespace.\n *\n * @typeParam StateType - Root state shape; the messages array is read\n * from `values[messagesKey]`.\n * @typeParam InterruptType - Shape of root protocol interrupts (forwarded\n * into `RootSnapshot` updates).\n */\nexport class RootMessageProjection<\n StateType extends object,\n InterruptType = unknown,\n> {\n /**\n * Key inside `values` that holds the message array. Defaults to\n * `\"messages\"` in the controller; configurable for state graphs\n * that surface messages under a different slot.\n */\n readonly #messagesKey: string;\n\n /** Root snapshot store written to on every merge. */\n readonly #store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n\n /**\n * Stateful chunk assembler for in-flight messages. Reset (via a\n * fresh instance) on every {@link reset} so a new thread starts\n * with no half-built messages from the previous one.\n */\n #assembler = new MessageAssembler();\n\n /**\n * `messageId → role/toolCallId` captured from `message-start` events.\n * The assembler's intermediate output drops these fields, so we cache\n * them at start-time and reapply when projecting to a `BaseMessage`.\n */\n readonly #roles = new Map<\n string,\n { role: ExtendedMessageRole; toolCallId?: string }\n >();\n\n /**\n * `messageId → position in #store.messages` for fast in-place\n * updates as deltas arrive. Rebuilt on every full reconciliation\n * driven by a `values` event.\n */\n readonly #indexById = new Map<string, number>();\n\n /**\n * Ids observed in the most recent `values.messages` snapshot.\n * Reconciliation uses this to detect server-side removals: a\n * previously-seen id missing from the next snapshot means it was\n * removed by the server (and should drop from the projection).\n */\n #valuesMessageIds = new Set<string>();\n\n /**\n * `namespaceKey → tool_call_id` captured from root `tool-started`\n * events. Used as a fallback when a tool-role `message-start` is\n * missing its `tool_call_id` field.\n */\n readonly #toolCallIdByNamespace = new Map<string, string>();\n\n /**\n * Coalescing buffer for store writes. {@link handleMessage} and\n * {@link applyValues} stage their computed `messages` / `values`\n * here instead of calling `store.setState` per event. A single\n * `setTimeout(0)` flush commits them in one `setState`, so a\n * burst of SSE events draining as a microtask chain becomes one\n * store notification at the next macrotask boundary.\n *\n * `null` means \"no staged write\" — once a flush settles, the\n * slots are cleared so the next call starts from the latest\n * committed store snapshot.\n */\n #pendingMessages: BaseMessage[] | null = null;\n #pendingValues: StateType | null = null;\n #flushScheduled = false;\n\n /**\n * Highest checkpoint `step` whose `values` snapshot has been applied.\n * Seeded by {@link StreamController.hydrate} from `getState()` and\n * advanced by live `values` events. A snapshot arriving with a lower\n * step is an older checkpoint replayed by the content pump on\n * reconnect; it is reconciled in add-only mode so it cannot remove\n * the seeded message tail (the final assistant turn). `undefined`\n * until the first step-bearing snapshot, where the legacy\n * remove-on-absence behavior is preserved.\n */\n #maxStep: number | undefined = undefined;\n\n /**\n * Message ids seeded as complete-and-final from an idle thread's\n * `getState()` snapshot. An idle thread defers its root SSE pump, and\n * the first `submit()` brings it up — at which point the transport\n * replays the finished run from `seq=0`. Unlike the `values` channel\n * (guarded by {@link #maxStep}), `messages`-channel deltas carry no\n * step, so that replay would otherwise rebuild each already-complete\n * message from an empty `message-start` and re-stream the whole turn\n * token-by-token, clobbering the seeded tail (a visible \"messages\n * replay\" on the first submit). Deltas for a sealed id are dropped in\n * {@link handleMessage}. The seal is lifted once a checkpoint advances\n * strictly past {@link #sealStep} (see {@link applyValues}) or on\n * thread rebind ({@link reset}). New ids from the next run are never\n * sealed, so they stream normally.\n */\n readonly #sealedMessageIds = new Set<string>();\n\n /**\n * High-water {@link #maxStep} captured when {@link sealMessageIds} ran,\n * i.e. the seed checkpoint's step (or `undefined` when `getState()`\n * carried no `metadata.step`). It is the boundary between the replayed\n * idle history (steps `<= #sealStep`, emitted by the deferred pump's\n * `seq=0` replay) and the new run (steps `> #sealStep`); only a\n * checkpoint strictly past it lifts the seal. Without this boundary the\n * replayed old-run checkpoints — which themselves carry increasing\n * steps — would advance {@link #maxStep} and lift the seal mid-replay,\n * reopening the clobber. When the seed step is unknown the boundary\n * stays `undefined` and the seal holds until {@link reset}; the\n * `values` channel (which ignores the seal) still reconciles any\n * genuine change to a sealed id, only its streamed deltas are dropped.\n */\n #sealStep: number | undefined = undefined;\n\n /**\n * @param params.messagesKey - Key inside `values` that holds the\n * message array.\n * @param params.store - Root snapshot store to mutate.\n */\n constructor(params: {\n messagesKey: string;\n store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n }) {\n this.#messagesKey = params.messagesKey;\n this.#store = params.store;\n }\n\n /**\n * Drop all per-thread state. Called by the controller on thread\n * rebind / dispose so a swap doesn't surface stale messages.\n */\n reset(): void {\n this.#assembler = new MessageAssembler();\n this.#roles.clear();\n this.#indexById.clear();\n this.#valuesMessageIds = new Set();\n this.#toolCallIdByNamespace.clear();\n // Drop any unflushed pending writes — they were computed against\n // the previous thread's baseline and committing them after a\n // rebind would bleed stale messages into the new thread.\n this.#pendingMessages = null;\n this.#pendingValues = null;\n this.#flushScheduled = false;\n this.#maxStep = undefined;\n this.#sealedMessageIds.clear();\n this.#sealStep = undefined;\n }\n\n /**\n * Seal message ids so the streamed `messages` channel cannot downgrade\n * them to partial re-streams. Called by {@link StreamController.hydrate}\n * after seeding an idle thread, whose deferred pump replays the finished\n * run from `seq=0` on the first submit.\n *\n * Captures the current {@link #maxStep} as the lift boundary\n * ({@link #sealStep}). The seal is applied immediately after the seed's\n * `getState()` snapshot is reconciled, so `#maxStep` here is the seed\n * step (or `undefined` when `getState()` carried no `metadata.step`).\n * The seal is lifted once a checkpoint advances strictly past that\n * boundary (see {@link applyValues}) or on thread rebind\n * ({@link reset}).\n *\n * @param ids - Complete message ids from the idle `getState()` seed.\n */\n sealMessageIds(ids: Iterable<string>): void {\n for (const id of ids) this.#sealedMessageIds.add(id);\n if (this.#sealStep == null) this.#sealStep = this.#maxStep;\n }\n\n /**\n * Record a `namespace → tool_call_id` mapping captured from a root\n * `tool-started` event.\n *\n * The companion tool-role `message-start` event may not carry a\n * `tool_call_id`, so we fall back to the most recent value recorded\n * here for the same namespace.\n *\n * @param namespace - Event namespace from the `tool-started` event.\n * @param toolCallId - Tool call id from the same event.\n */\n recordToolCallNamespace(\n namespace: readonly string[],\n toolCallId: string\n ): void {\n this.#toolCallIdByNamespace.set(namespaceKey(namespace), toolCallId);\n }\n\n /**\n * Apply a `messages` channel event to the projection.\n *\n * Captures role/tool metadata on `message-start`, feeds the chunk\n * to the assembler, projects the assembled output to a\n * {@link BaseMessage}, and either appends or in-place updates the\n * pending messages buffer based on whether the id was seen before.\n *\n * @param event - The `messages` channel event to consume.\n */\n handleMessage(event: MessagesEvent): void {\n const data = event.params.data;\n if (data.event === \"message-start\") {\n const startData = data as MessageStartData;\n const role = (startData.role ?? \"ai\") as MessageRole;\n const extendedRole =\n (startData as { role?: ExtendedMessageRole }).role ?? role;\n let toolCallId = (startData as { tool_call_id?: string }).tool_call_id;\n // Tool messages need a tool_call_id to render. Fall back through:\n // 1. legacy `<id>-tool-<call_id>` message id format\n // 2. namespace-recorded tool_call_id (from #recordToolCallNamespace)\n if (extendedRole === \"tool\" && toolCallId == null) {\n const messageId = startData.id;\n if (messageId != null) {\n const match = /-tool-(.+)$/.exec(messageId);\n if (match != null) toolCallId = match[1];\n }\n if (toolCallId == null) {\n toolCallId = this.#toolCallIdByNamespace.get(\n namespaceKey(event.params.namespace)\n );\n }\n }\n if (startData.id != null) {\n this.#roles.set(startData.id, {\n role: extendedRole,\n toolCallId,\n });\n }\n }\n\n const update = this.#assembler.consume(event);\n if (update == null) return;\n const id = update.message.id;\n if (id == null) return;\n // A sealed id belongs to a message seeded complete from an idle\n // thread's `getState()`; the deferred pump's `seq=0` replay would\n // otherwise rebuild it from an empty start and re-stream the whole\n // turn. Drop the replayed delta — the authoritative seed already\n // holds the final content (see {@link #sealedMessageIds}).\n if (this.#sealedMessageIds.has(id)) return;\n const captured = this.#roles.get(id) ?? { role: \"ai\" as const };\n const base = assembledMessageToBaseMessage(update.message, captured.role, {\n toolCallId: captured.toolCallId,\n });\n\n // Compute against the pending baseline if we have one (so an\n // earlier handleMessage in the same tick is the input to this\n // one), else against the latest committed store snapshot.\n // `#indexById` is the synchronous source of truth for \"where is\n // each id in the current messages list\" — every code path below\n // keeps it in sync before returning.\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const existingIdx = this.#indexById.get(id);\n let messages: BaseMessage[];\n if (existingIdx == null) {\n this.#indexById.set(id, baselineMessages.length);\n messages = [...baselineMessages, base];\n } else if (messagesEqual(baselineMessages[existingIdx], base)) {\n // Identical re-emission — skip the store write to keep\n // snapshot identity stable.\n return;\n } else {\n messages = baselineMessages.slice();\n messages[existingIdx] = base;\n }\n\n // Mirror the new messages list into `values[messagesKey]` so\n // direct `values` reads (used by some hooks and by the eventual\n // `values` reconciliation) stay in sync.\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const values = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n messages\n );\n this.#pendingMessages = messages;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Reconcile a full `values` snapshot into the projection.\n *\n * Delegates the merge to {@link reconcileMessagesFromValues}:\n * values stays authoritative for ordering and removals, while\n * streamed in-flight messages keep their content until the server\n * echoes them back. Empty messages just refresh the values blob.\n *\n * Rebuilds {@link #indexById} after the merge so subsequent delta\n * applications target the new positions.\n *\n * @param nextValues - Full values snapshot from the `values` event.\n * @param nextMessages - The messages array extracted from\n * `values[messagesKey]` and coerced to `BaseMessage` instances.\n * @param opts.step - Checkpoint superstep for this snapshot, when\n * known. A snapshot whose step is below the highest applied step is\n * treated as a stale reconnect replay and reconciled add-only.\n */\n applyValues(\n nextValues: StateType,\n nextMessages: BaseMessage[],\n opts?: { step?: number }\n ): void {\n const baselineSnapshot = this.#store.getSnapshot();\n const baselineMessages = this.#pendingMessages ?? baselineSnapshot.messages;\n const baselineValues = this.#pendingValues ?? baselineSnapshot.values;\n\n const step = opts?.step;\n // Stale only when we have both a prior high-water step and a lower\n // incoming step. A missing step preserves the legacy semantics.\n const addOnly =\n step != null && this.#maxStep != null && step < this.#maxStep;\n if (step != null && (this.#maxStep == null || step > this.#maxStep)) {\n this.#maxStep = step;\n }\n // Lift the replay seal only when a checkpoint advances strictly past\n // the step captured when the ids were sealed (the seed step). That\n // boundary separates the replayed idle history (steps <= #sealStep,\n // emitted by the deferred pump's seq=0 replay) from the new run\n // (steps > #sealStep), so crossing it means seeded ids may now take\n // genuine streamed updates. Replayed old-run checkpoints advance\n // #maxStep but never reach past #sealStep, so they can't lift it. A\n // `null` boundary (the seed step was unknown) keeps the seal until\n // reset() — we can't tell replay from live, and the values channel\n // still reconciles a sealed id even while its streamed deltas drop.\n if (\n this.#sealedMessageIds.size > 0 &&\n step != null &&\n this.#sealStep != null &&\n step > this.#sealStep\n ) {\n this.#sealedMessageIds.clear();\n }\n\n if (nextMessages.length === 0) {\n if (\n stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)\n ) {\n return;\n }\n // Mirror the current `messages` list back into the values slot\n // so the staged snapshot stays consistent with the (separately\n // tracked) messages array.\n this.#pendingValues = syncMessagesIntoValues(\n nextValues,\n this.#messagesKey,\n baselineMessages\n );\n this.#scheduleFlush();\n return;\n }\n\n const reconciliation = reconcileMessagesFromValues({\n valueMessages: nextMessages,\n currentMessages: baselineMessages,\n currentIndexById: this.#indexById,\n previousValueMessageIds: this.#valuesMessageIds,\n preferValuesMessage: shouldPreferValuesMessageForToolCalls,\n addOnly,\n });\n // A stale replay snapshot must not shrink the authoritative id set:\n // keep the (larger) seeded set so a genuinely-newer removal is still\n // detected once the timeline advances past the seed.\n if (!addOnly) this.#valuesMessageIds = reconciliation.valueMessageIds;\n const messages = reconciliation.messages as BaseMessage[];\n const values = {\n ...(nextValues as Record<string, unknown>),\n [this.#messagesKey]: messages,\n } as StateType;\n if (\n messages === baselineMessages &&\n stateValuesShallowEqual(baselineValues, values, this.#messagesKey)\n ) {\n return;\n }\n\n // Reconciliation may reorder, drop, or substitute messages, so\n // rebuild the id → index map to match the new array.\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(messages)) {\n this.#indexById.set(id, idx);\n }\n this.#pendingMessages = messages;\n this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Append messages applied optimistically by a local `submit()`,\n * keyed by id so the eventual server echo reconciles cleanly.\n *\n * Unlike {@link applyValues}, the supplied messages are *not* treated\n * as an authoritative ordered snapshot: they are appended to the end\n * of the current projection (or replaced in place when the id already\n * exists), preserving prior history ordering. When the server later\n * emits a `values` snapshot containing the same ids,\n * {@link applyValues} → {@link reconcileMessagesFromValues} takes over\n * (server ordering wins, the echoed message replaces the optimistic\n * one).\n *\n * Non-message input keys are shallow-merged into `values` via\n * `extraValues`; they are dropped/overwritten automatically by the\n * first server `values` event (which rebuilds `values` from the\n * server snapshot), or rolled back via {@link restoreValueKeys} when\n * the run fails before any echo.\n *\n * @param messages - Optimistic messages (already coerced to\n * `BaseMessage` instances, each carrying a stable id).\n * @param extraValues - Non-message input keys to shallow-merge into\n * `values`.\n */\n appendOptimistic(\n messages: BaseMessage[],\n extraValues?: Record<string, unknown>\n ): void {\n let working = this.#pendingMessages ?? this.#store.getSnapshot().messages;\n let mutated = false;\n for (const message of messages) {\n const id = message.id;\n if (id == null) continue;\n const existingIdx = this.#indexById.get(id);\n if (existingIdx == null) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n this.#indexById.set(id, working.length);\n working.push(message);\n } else if (!messagesEqual(working[existingIdx], message)) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n working[existingIdx] = message;\n }\n }\n\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n let values = baselineValues;\n if (extraValues != null && Object.keys(extraValues).length > 0) {\n values = { ...(baselineValues as object), ...extraValues } as StateType;\n }\n values = syncMessagesIntoValues(values, this.#messagesKey, working);\n if (!mutated && values === baselineValues) return;\n this.#pendingMessages = working;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Drop optimistic messages by id without disturbing the rest of the\n * projection. Used by {@link StreamController.hydrate} to remove\n * never-persisted optimistic messages (`pending` / `failed`) so a\n * reload converges to server truth.\n *\n * @param ids - Message ids to remove.\n */\n dropOptimisticMessages(ids: ReadonlySet<string>): void {\n if (ids.size === 0) return;\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const next = baselineMessages.filter((m) => m.id == null || !ids.has(m.id));\n if (next.length === baselineMessages.length) return;\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(next)) {\n this.#indexById.set(id, idx);\n }\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n this.#pendingMessages = next;\n this.#pendingValues = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n next\n );\n this.#scheduleFlush();\n }\n\n /**\n * Restore (or delete) `values` keys that were optimistically merged\n * by {@link appendOptimistic} but never echoed by the server — i.e.\n * roll back non-message optimistic state when the run fails before\n * any `values` event lands. Messages are left untouched (kept on\n * failure per the optimistic contract).\n *\n * @param restore - Per-key pre-submit snapshot: when `hadKey` is\n * false the key is deleted, otherwise it is reset to `prevValue`.\n */\n restoreValueKeys(\n restore: ReadonlyArray<{\n key: string;\n hadKey: boolean;\n prevValue: unknown;\n }>\n ): void {\n if (restore.length === 0) return;\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const next = { ...(baselineValues as Record<string, unknown>) };\n let changed = false;\n for (const { key, hadKey, prevValue } of restore) {\n if (key === this.#messagesKey) continue;\n if (hadKey) {\n if (!Object.is(next[key], prevValue)) {\n next[key] = prevValue;\n changed = true;\n }\n } else if (Object.prototype.hasOwnProperty.call(next, key)) {\n delete next[key];\n changed = true;\n }\n }\n if (!changed) return;\n this.#pendingValues = next as StateType;\n this.#scheduleFlush();\n }\n\n /**\n * Schedule a coalesced flush on the next macrotask. Idempotent\n * within a tick — multiple `handleMessage` / `applyValues` calls\n * before the flush fires collapse into one store write.\n *\n * `setTimeout(0)` is a macrotask: it runs after the current\n * microtask chain drains, so a burst of SSE events processed by\n * the controller's `for await` pump becomes one `store.setState`\n * (and therefore one `useSyncExternalStore` notification).\n */\n #scheduleFlush = (): void => {\n if (this.#flushScheduled) return;\n this.#flushScheduled = true;\n setTimeout(this.#flushPending, 0);\n };\n\n /**\n * Drain `#pendingMessages` / `#pendingValues` to the store in a\n * single `setState` call.\n */\n #flushPending = (): void => {\n this.#flushScheduled = false;\n const messages = this.#pendingMessages;\n const values = this.#pendingValues;\n this.#pendingMessages = null;\n this.#pendingValues = null;\n if (messages == null && values == null) return;\n this.#store.setState((s) => {\n // Other rootStore mutators (controller-driven `isLoading`,\n // `interrupts`, `toolCalls`, etc.) do not touch `s.messages`\n // / `s.values`, so a last-write-wins commit on those two\n // fields is safe.\n if (messages == null) {\n return values == null ? s : { ...s, values };\n }\n if (values == null) return { ...s, messages };\n return { ...s, messages, values };\n });\n };\n}\n\n/**\n * Mirror a freshly-updated message list into `values[messagesKey]`.\n *\n * Returns the same `values` reference when the list is already\n * equal-by-content so the caller can keep the existing snapshot\n * identity (and avoid spurious `setSnapshot` notifications).\n */\nfunction syncMessagesIntoValues<StateType extends object>(\n values: StateType,\n messagesKey: string,\n messages: BaseMessage[]\n): StateType {\n const record = values as Record<string, unknown>;\n const current = record[messagesKey];\n if (Array.isArray(current) && messagesEqualList(current, messages)) {\n return values;\n }\n return {\n ...record,\n [messagesKey]: messages,\n } as StateType;\n}\n\n/**\n * True when two `BaseMessage` arrays carry the same per-message\n * content (using {@link messagesEqual}).\n */\nfunction messagesEqualList(\n previous: readonly BaseMessage[],\n next: readonly BaseMessage[]\n): boolean {\n if (previous === next) return true;\n if (previous.length !== next.length) return false;\n for (let i = 0; i < previous.length; i += 1) {\n if (!messagesEqual(previous[i], next[i])) return false;\n }\n return true;\n}\n\n/**\n * Shallow-equal for `values` objects, *ignoring* the messages slot.\n *\n * The messages array is compared separately by the caller (via\n * {@link messagesEqualList}) because both arrays contain class\n * instances whose JSON representation is not stable across reads.\n */\nfunction stateValuesShallowEqual(\n previous: object,\n next: object,\n messagesKey: string\n): boolean {\n if (previous === next) return true;\n const previousRecord = previous as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n const previousKeys = Object.keys(previousRecord);\n const nextKeys = Object.keys(nextRecord);\n if (previousKeys.length !== nextKeys.length) return false;\n for (const key of previousKeys) {\n if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) return false;\n const previousValue = previousRecord[key];\n const nextValue = nextRecord[key];\n if (\n key === messagesKey &&\n Array.isArray(previousValue) &&\n Array.isArray(nextValue)\n ) {\n continue;\n }\n if (!Object.is(previousValue, nextValue)) return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoGA,IAAa,wBAAb,MAGE;;;;;;CAMA;;CAGA;;;;;;CAOA,aAAa,IAAIE,iBAAAA,kBAAkB;;;;;;CAOnC,yBAAkB,IAAI,KAGnB;;;;;;CAOH,6BAAsB,IAAI,KAAqB;;;;;;;CAQ/C,oCAAoB,IAAI,KAAa;;;;;;CAOrC,yCAAkC,IAAI,KAAqB;;;;;;;;;;;;;CAc3D,mBAAyC;CACzC,iBAAmC;CACnC,kBAAkB;;;;;;;;;;;CAYlB,WAA+B,KAAA;;;;;;;;;;;;;;;;CAiB/B,oCAA6B,IAAI,KAAa;;;;;;;;;;;;;;;CAgB9C,YAAgC,KAAA;;;;;;CAOhC,YAAY,QAGT;AACD,QAAA,cAAoB,OAAO;AAC3B,QAAA,QAAc,OAAO;;;;;;CAOvB,QAAc;AACZ,QAAA,YAAkB,IAAIA,iBAAAA,kBAAkB;AACxC,QAAA,MAAY,OAAO;AACnB,QAAA,UAAgB,OAAO;A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,QAAQ,eACR,MAAM,QAAQ,cAAc,IAC5B,MAAM,QAAQ,UAAU,CAExB;AAEF,MAAI,CAAC,OAAO,GAAG,eAAe,UAAU,CAAE,QAAO;;AAEnD,QAAO"} |
@@ -83,2 +83,33 @@ import { MessageAssembler } from "../client/stream/messages.js"; | ||
| /** | ||
| * Message ids seeded as complete-and-final from an idle thread's | ||
| * `getState()` snapshot. An idle thread defers its root SSE pump, and | ||
| * the first `submit()` brings it up — at which point the transport | ||
| * replays the finished run from `seq=0`. Unlike the `values` channel | ||
| * (guarded by {@link #maxStep}), `messages`-channel deltas carry no | ||
| * step, so that replay would otherwise rebuild each already-complete | ||
| * message from an empty `message-start` and re-stream the whole turn | ||
| * token-by-token, clobbering the seeded tail (a visible "messages | ||
| * replay" on the first submit). Deltas for a sealed id are dropped in | ||
| * {@link handleMessage}. The seal is lifted once a checkpoint advances | ||
| * strictly past {@link #sealStep} (see {@link applyValues}) or on | ||
| * thread rebind ({@link reset}). New ids from the next run are never | ||
| * sealed, so they stream normally. | ||
| */ | ||
| #sealedMessageIds = /* @__PURE__ */ new Set(); | ||
| /** | ||
| * High-water {@link #maxStep} captured when {@link sealMessageIds} ran, | ||
| * i.e. the seed checkpoint's step (or `undefined` when `getState()` | ||
| * carried no `metadata.step`). It is the boundary between the replayed | ||
| * idle history (steps `<= #sealStep`, emitted by the deferred pump's | ||
| * `seq=0` replay) and the new run (steps `> #sealStep`); only a | ||
| * checkpoint strictly past it lifts the seal. Without this boundary the | ||
| * replayed old-run checkpoints — which themselves carry increasing | ||
| * steps — would advance {@link #maxStep} and lift the seal mid-replay, | ||
| * reopening the clobber. When the seed step is unknown the boundary | ||
| * stays `undefined` and the seal holds until {@link reset}; the | ||
| * `values` channel (which ignores the seal) still reconciles any | ||
| * genuine change to a sealed id, only its streamed deltas are dropped. | ||
| */ | ||
| #sealStep = void 0; | ||
| /** | ||
| * @param params.messagesKey - Key inside `values` that holds the | ||
@@ -106,4 +137,26 @@ * message array. | ||
| this.#maxStep = void 0; | ||
| this.#sealedMessageIds.clear(); | ||
| this.#sealStep = void 0; | ||
| } | ||
| /** | ||
| * Seal message ids so the streamed `messages` channel cannot downgrade | ||
| * them to partial re-streams. Called by {@link StreamController.hydrate} | ||
| * after seeding an idle thread, whose deferred pump replays the finished | ||
| * run from `seq=0` on the first submit. | ||
| * | ||
| * Captures the current {@link #maxStep} as the lift boundary | ||
| * ({@link #sealStep}). The seal is applied immediately after the seed's | ||
| * `getState()` snapshot is reconciled, so `#maxStep` here is the seed | ||
| * step (or `undefined` when `getState()` carried no `metadata.step`). | ||
| * The seal is lifted once a checkpoint advances strictly past that | ||
| * boundary (see {@link applyValues}) or on thread rebind | ||
| * ({@link reset}). | ||
| * | ||
| * @param ids - Complete message ids from the idle `getState()` seed. | ||
| */ | ||
| sealMessageIds(ids) { | ||
| for (const id of ids) this.#sealedMessageIds.add(id); | ||
| if (this.#sealStep == null) this.#sealStep = this.#maxStep; | ||
| } | ||
| /** | ||
| * Record a `namespace → tool_call_id` mapping captured from a root | ||
@@ -156,2 +209,3 @@ * `tool-started` event. | ||
| if (id == null) return; | ||
| if (this.#sealedMessageIds.has(id)) return; | ||
| const captured = this.#roles.get(id) ?? { role: "ai" }; | ||
@@ -201,2 +255,3 @@ const base = assembledMessageToBaseMessage(update.message, captured.role, { toolCallId: captured.toolCallId }); | ||
| if (step != null && (this.#maxStep == null || step > this.#maxStep)) this.#maxStep = step; | ||
| if (this.#sealedMessageIds.size > 0 && step != null && this.#sealStep != null && step > this.#sealStep) this.#sealedMessageIds.clear(); | ||
| if (nextMessages.length === 0) { | ||
@@ -203,0 +258,0 @@ if (stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)) return; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"root-message-projection.js","names":["#messagesKey","#store","#roles","#indexById","#toolCallIdByNamespace","#assembler","#valuesMessageIds","#pendingMessages","#pendingValues","#flushScheduled","#maxStep","#scheduleFlush","#flushPending"],"sources":["../../src/stream/root-message-projection.ts"],"sourcesContent":["/**\n * Root-namespace message projection.\n *\n * # What this module is\n *\n * The {@link RootMessageProjection} is the piece of the\n * {@link StreamController} that owns \"what messages does the root\n * namespace currently contain?\". It assembles streamed message deltas\n * via {@link MessageAssembler}, reconciles them against authoritative\n * `values.messages` snapshots from the server, and writes the merged\n * list back into the controller's root snapshot store.\n *\n * # Two streams of truth\n *\n * Root messages arrive on two channels and need to merge cleanly:\n *\n * - **`messages` channel.** Token-level deltas that build messages\n * incrementally. The {@link MessageAssembler} keeps partial\n * messages by id and emits an updated `BaseMessage` per delta.\n * - **`values` channel.** Periodic full-state snapshots that include\n * the authoritative messages array. Used for ordering, removals,\n * and forks (where the streamed messages may pre-date the new\n * timeline).\n *\n * The reconciliation rules (delegated to\n * {@link reconcileMessagesFromValues}) preserve in-flight streamed\n * content while letting values dictate ordering and removals.\n *\n * # Tool-message namespace correlation\n *\n * Tool messages arrive on `messages-start` events with `role: \"tool\"`\n * but the start event doesn't always include a `tool_call_id`. We\n * recover it via three fallbacks:\n *\n * 1. The start event itself, when the server includes it.\n * 2. The legacy `<id>-tool-<call_id>` message id format.\n * 3. The most recent `tool-started` event recorded under the same\n * namespace via {@link recordToolCallNamespace}.\n *\n * Without this correlation, tool messages render with empty\n * `tool_call_id` and downstream UIs can't pair them with the\n * originating tool call.\n *\n * # Store-write batching\n *\n * Every {@link handleMessage} / {@link applyValues} call updates the\n * in-projection bookkeeping (assembler state, id index, role cache)\n * synchronously, then stages the new `messages` / `values` into a\n * pending buffer and schedules a `setTimeout(0)` flush. A single\n * coalesced `store.setState` runs at the next macrotask boundary.\n *\n * The motivation is the long-replay freeze: a thread with hundreds\n * of messages replays through the `messages` channel on refresh or\n * mid-run join. Those events drain through the controller's\n * `for await` pump as a long microtask chain. Per-event\n * `store.setState` notifies `useSyncExternalStore` per event, and\n * after enough notifications React's `nestedUpdateCount` guard trips\n * with \"Maximum update depth exceeded\", permanently freezing the UI\n * on the first few messages. Coalescing to one notification per\n * macrotask lets React's scheduler commit between flushes.\n *\n * # Lifecycle\n *\n * - `handleMessage(event)` — apply a `messages` event delta.\n * - `applyValues(values, msgs)` — merge a `values` snapshot.\n * - `recordToolCallNamespace(ns, id)` — capture `namespace → tool_call_id`\n * so subsequent tool message starts can recover the id.\n * - `reset()` — clear all state on thread rebind.\n */\nimport type {\n MessagesEvent,\n MessageRole,\n MessageStartData,\n} from \"@langchain/protocol\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport { MessageAssembler } from \"../client/stream/messages.js\";\nimport {\n assembledMessageToBaseMessage,\n type ExtendedMessageRole,\n} from \"./assembled-to-message.js\";\nimport type { StreamStore } from \"./store.js\";\nimport type { RootSnapshot } from \"./types.js\";\nimport { namespaceKey } from \"./namespace.js\";\nimport {\n buildMessageIndex,\n messagesEqual,\n reconcileMessagesFromValues,\n shouldPreferValuesMessageForToolCalls,\n} from \"./message-reconciliation.js\";\n\n/**\n * Root-namespace message projection. Owns the merge between the\n * `messages` (streamed deltas) and `values` (authoritative\n * snapshots) channels for the root namespace.\n *\n * @typeParam StateType - Root state shape; the messages array is read\n * from `values[messagesKey]`.\n * @typeParam InterruptType - Shape of root protocol interrupts (forwarded\n * into `RootSnapshot` updates).\n */\nexport class RootMessageProjection<\n StateType extends object,\n InterruptType = unknown,\n> {\n /**\n * Key inside `values` that holds the message array. Defaults to\n * `\"messages\"` in the controller; configurable for state graphs\n * that surface messages under a different slot.\n */\n readonly #messagesKey: string;\n\n /** Root snapshot store written to on every merge. */\n readonly #store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n\n /**\n * Stateful chunk assembler for in-flight messages. Reset (via a\n * fresh instance) on every {@link reset} so a new thread starts\n * with no half-built messages from the previous one.\n */\n #assembler = new MessageAssembler();\n\n /**\n * `messageId → role/toolCallId` captured from `message-start` events.\n * The assembler's intermediate output drops these fields, so we cache\n * them at start-time and reapply when projecting to a `BaseMessage`.\n */\n readonly #roles = new Map<\n string,\n { role: ExtendedMessageRole; toolCallId?: string }\n >();\n\n /**\n * `messageId → position in #store.messages` for fast in-place\n * updates as deltas arrive. Rebuilt on every full reconciliation\n * driven by a `values` event.\n */\n readonly #indexById = new Map<string, number>();\n\n /**\n * Ids observed in the most recent `values.messages` snapshot.\n * Reconciliation uses this to detect server-side removals: a\n * previously-seen id missing from the next snapshot means it was\n * removed by the server (and should drop from the projection).\n */\n #valuesMessageIds = new Set<string>();\n\n /**\n * `namespaceKey → tool_call_id` captured from root `tool-started`\n * events. Used as a fallback when a tool-role `message-start` is\n * missing its `tool_call_id` field.\n */\n readonly #toolCallIdByNamespace = new Map<string, string>();\n\n /**\n * Coalescing buffer for store writes. {@link handleMessage} and\n * {@link applyValues} stage their computed `messages` / `values`\n * here instead of calling `store.setState` per event. A single\n * `setTimeout(0)` flush commits them in one `setState`, so a\n * burst of SSE events draining as a microtask chain becomes one\n * store notification at the next macrotask boundary.\n *\n * `null` means \"no staged write\" — once a flush settles, the\n * slots are cleared so the next call starts from the latest\n * committed store snapshot.\n */\n #pendingMessages: BaseMessage[] | null = null;\n #pendingValues: StateType | null = null;\n #flushScheduled = false;\n\n /**\n * Highest checkpoint `step` whose `values` snapshot has been applied.\n * Seeded by {@link StreamController.hydrate} from `getState()` and\n * advanced by live `values` events. A snapshot arriving with a lower\n * step is an older checkpoint replayed by the content pump on\n * reconnect; it is reconciled in add-only mode so it cannot remove\n * the seeded message tail (the final assistant turn). `undefined`\n * until the first step-bearing snapshot, where the legacy\n * remove-on-absence behavior is preserved.\n */\n #maxStep: number | undefined = undefined;\n\n /**\n * @param params.messagesKey - Key inside `values` that holds the\n * message array.\n * @param params.store - Root snapshot store to mutate.\n */\n constructor(params: {\n messagesKey: string;\n store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n }) {\n this.#messagesKey = params.messagesKey;\n this.#store = params.store;\n }\n\n /**\n * Drop all per-thread state. Called by the controller on thread\n * rebind / dispose so a swap doesn't surface stale messages.\n */\n reset(): void {\n this.#assembler = new MessageAssembler();\n this.#roles.clear();\n this.#indexById.clear();\n this.#valuesMessageIds = new Set();\n this.#toolCallIdByNamespace.clear();\n // Drop any unflushed pending writes — they were computed against\n // the previous thread's baseline and committing them after a\n // rebind would bleed stale messages into the new thread.\n this.#pendingMessages = null;\n this.#pendingValues = null;\n this.#flushScheduled = false;\n this.#maxStep = undefined;\n }\n\n /**\n * Record a `namespace → tool_call_id` mapping captured from a root\n * `tool-started` event.\n *\n * The companion tool-role `message-start` event may not carry a\n * `tool_call_id`, so we fall back to the most recent value recorded\n * here for the same namespace.\n *\n * @param namespace - Event namespace from the `tool-started` event.\n * @param toolCallId - Tool call id from the same event.\n */\n recordToolCallNamespace(\n namespace: readonly string[],\n toolCallId: string\n ): void {\n this.#toolCallIdByNamespace.set(namespaceKey(namespace), toolCallId);\n }\n\n /**\n * Apply a `messages` channel event to the projection.\n *\n * Captures role/tool metadata on `message-start`, feeds the chunk\n * to the assembler, projects the assembled output to a\n * {@link BaseMessage}, and either appends or in-place updates the\n * pending messages buffer based on whether the id was seen before.\n *\n * @param event - The `messages` channel event to consume.\n */\n handleMessage(event: MessagesEvent): void {\n const data = event.params.data;\n if (data.event === \"message-start\") {\n const startData = data as MessageStartData;\n const role = (startData.role ?? \"ai\") as MessageRole;\n const extendedRole =\n (startData as { role?: ExtendedMessageRole }).role ?? role;\n let toolCallId = (startData as { tool_call_id?: string }).tool_call_id;\n // Tool messages need a tool_call_id to render. Fall back through:\n // 1. legacy `<id>-tool-<call_id>` message id format\n // 2. namespace-recorded tool_call_id (from #recordToolCallNamespace)\n if (extendedRole === \"tool\" && toolCallId == null) {\n const messageId = startData.id;\n if (messageId != null) {\n const match = /-tool-(.+)$/.exec(messageId);\n if (match != null) toolCallId = match[1];\n }\n if (toolCallId == null) {\n toolCallId = this.#toolCallIdByNamespace.get(\n namespaceKey(event.params.namespace)\n );\n }\n }\n if (startData.id != null) {\n this.#roles.set(startData.id, {\n role: extendedRole,\n toolCallId,\n });\n }\n }\n\n const update = this.#assembler.consume(event);\n if (update == null) return;\n const id = update.message.id;\n if (id == null) return;\n const captured = this.#roles.get(id) ?? { role: \"ai\" as const };\n const base = assembledMessageToBaseMessage(update.message, captured.role, {\n toolCallId: captured.toolCallId,\n });\n\n // Compute against the pending baseline if we have one (so an\n // earlier handleMessage in the same tick is the input to this\n // one), else against the latest committed store snapshot.\n // `#indexById` is the synchronous source of truth for \"where is\n // each id in the current messages list\" — every code path below\n // keeps it in sync before returning.\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const existingIdx = this.#indexById.get(id);\n let messages: BaseMessage[];\n if (existingIdx == null) {\n this.#indexById.set(id, baselineMessages.length);\n messages = [...baselineMessages, base];\n } else if (messagesEqual(baselineMessages[existingIdx], base)) {\n // Identical re-emission — skip the store write to keep\n // snapshot identity stable.\n return;\n } else {\n messages = baselineMessages.slice();\n messages[existingIdx] = base;\n }\n\n // Mirror the new messages list into `values[messagesKey]` so\n // direct `values` reads (used by some hooks and by the eventual\n // `values` reconciliation) stay in sync.\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const values = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n messages\n );\n this.#pendingMessages = messages;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Reconcile a full `values` snapshot into the projection.\n *\n * Delegates the merge to {@link reconcileMessagesFromValues}:\n * values stays authoritative for ordering and removals, while\n * streamed in-flight messages keep their content until the server\n * echoes them back. Empty messages just refresh the values blob.\n *\n * Rebuilds {@link #indexById} after the merge so subsequent delta\n * applications target the new positions.\n *\n * @param nextValues - Full values snapshot from the `values` event.\n * @param nextMessages - The messages array extracted from\n * `values[messagesKey]` and coerced to `BaseMessage` instances.\n * @param opts.step - Checkpoint superstep for this snapshot, when\n * known. A snapshot whose step is below the highest applied step is\n * treated as a stale reconnect replay and reconciled add-only.\n */\n applyValues(\n nextValues: StateType,\n nextMessages: BaseMessage[],\n opts?: { step?: number }\n ): void {\n const baselineSnapshot = this.#store.getSnapshot();\n const baselineMessages = this.#pendingMessages ?? baselineSnapshot.messages;\n const baselineValues = this.#pendingValues ?? baselineSnapshot.values;\n\n const step = opts?.step;\n // Stale only when we have both a prior high-water step and a lower\n // incoming step. A missing step preserves the legacy semantics.\n const addOnly =\n step != null && this.#maxStep != null && step < this.#maxStep;\n if (step != null && (this.#maxStep == null || step > this.#maxStep)) {\n this.#maxStep = step;\n }\n\n if (nextMessages.length === 0) {\n if (\n stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)\n ) {\n return;\n }\n // Mirror the current `messages` list back into the values slot\n // so the staged snapshot stays consistent with the (separately\n // tracked) messages array.\n this.#pendingValues = syncMessagesIntoValues(\n nextValues,\n this.#messagesKey,\n baselineMessages\n );\n this.#scheduleFlush();\n return;\n }\n\n const reconciliation = reconcileMessagesFromValues({\n valueMessages: nextMessages,\n currentMessages: baselineMessages,\n currentIndexById: this.#indexById,\n previousValueMessageIds: this.#valuesMessageIds,\n preferValuesMessage: shouldPreferValuesMessageForToolCalls,\n addOnly,\n });\n // A stale replay snapshot must not shrink the authoritative id set:\n // keep the (larger) seeded set so a genuinely-newer removal is still\n // detected once the timeline advances past the seed.\n if (!addOnly) this.#valuesMessageIds = reconciliation.valueMessageIds;\n const messages = reconciliation.messages as BaseMessage[];\n const values = {\n ...(nextValues as Record<string, unknown>),\n [this.#messagesKey]: messages,\n } as StateType;\n if (\n messages === baselineMessages &&\n stateValuesShallowEqual(baselineValues, values, this.#messagesKey)\n ) {\n return;\n }\n\n // Reconciliation may reorder, drop, or substitute messages, so\n // rebuild the id → index map to match the new array.\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(messages)) {\n this.#indexById.set(id, idx);\n }\n this.#pendingMessages = messages;\n this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Append messages applied optimistically by a local `submit()`,\n * keyed by id so the eventual server echo reconciles cleanly.\n *\n * Unlike {@link applyValues}, the supplied messages are *not* treated\n * as an authoritative ordered snapshot: they are appended to the end\n * of the current projection (or replaced in place when the id already\n * exists), preserving prior history ordering. When the server later\n * emits a `values` snapshot containing the same ids,\n * {@link applyValues} → {@link reconcileMessagesFromValues} takes over\n * (server ordering wins, the echoed message replaces the optimistic\n * one).\n *\n * Non-message input keys are shallow-merged into `values` via\n * `extraValues`; they are dropped/overwritten automatically by the\n * first server `values` event (which rebuilds `values` from the\n * server snapshot), or rolled back via {@link restoreValueKeys} when\n * the run fails before any echo.\n *\n * @param messages - Optimistic messages (already coerced to\n * `BaseMessage` instances, each carrying a stable id).\n * @param extraValues - Non-message input keys to shallow-merge into\n * `values`.\n */\n appendOptimistic(\n messages: BaseMessage[],\n extraValues?: Record<string, unknown>\n ): void {\n let working = this.#pendingMessages ?? this.#store.getSnapshot().messages;\n let mutated = false;\n for (const message of messages) {\n const id = message.id;\n if (id == null) continue;\n const existingIdx = this.#indexById.get(id);\n if (existingIdx == null) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n this.#indexById.set(id, working.length);\n working.push(message);\n } else if (!messagesEqual(working[existingIdx], message)) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n working[existingIdx] = message;\n }\n }\n\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n let values = baselineValues;\n if (extraValues != null && Object.keys(extraValues).length > 0) {\n values = { ...(baselineValues as object), ...extraValues } as StateType;\n }\n values = syncMessagesIntoValues(values, this.#messagesKey, working);\n if (!mutated && values === baselineValues) return;\n this.#pendingMessages = working;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Drop optimistic messages by id without disturbing the rest of the\n * projection. Used by {@link StreamController.hydrate} to remove\n * never-persisted optimistic messages (`pending` / `failed`) so a\n * reload converges to server truth.\n *\n * @param ids - Message ids to remove.\n */\n dropOptimisticMessages(ids: ReadonlySet<string>): void {\n if (ids.size === 0) return;\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const next = baselineMessages.filter((m) => m.id == null || !ids.has(m.id));\n if (next.length === baselineMessages.length) return;\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(next)) {\n this.#indexById.set(id, idx);\n }\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n this.#pendingMessages = next;\n this.#pendingValues = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n next\n );\n this.#scheduleFlush();\n }\n\n /**\n * Restore (or delete) `values` keys that were optimistically merged\n * by {@link appendOptimistic} but never echoed by the server — i.e.\n * roll back non-message optimistic state when the run fails before\n * any `values` event lands. Messages are left untouched (kept on\n * failure per the optimistic contract).\n *\n * @param restore - Per-key pre-submit snapshot: when `hadKey` is\n * false the key is deleted, otherwise it is reset to `prevValue`.\n */\n restoreValueKeys(\n restore: ReadonlyArray<{\n key: string;\n hadKey: boolean;\n prevValue: unknown;\n }>\n ): void {\n if (restore.length === 0) return;\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const next = { ...(baselineValues as Record<string, unknown>) };\n let changed = false;\n for (const { key, hadKey, prevValue } of restore) {\n if (key === this.#messagesKey) continue;\n if (hadKey) {\n if (!Object.is(next[key], prevValue)) {\n next[key] = prevValue;\n changed = true;\n }\n } else if (Object.prototype.hasOwnProperty.call(next, key)) {\n delete next[key];\n changed = true;\n }\n }\n if (!changed) return;\n this.#pendingValues = next as StateType;\n this.#scheduleFlush();\n }\n\n /**\n * Schedule a coalesced flush on the next macrotask. Idempotent\n * within a tick — multiple `handleMessage` / `applyValues` calls\n * before the flush fires collapse into one store write.\n *\n * `setTimeout(0)` is a macrotask: it runs after the current\n * microtask chain drains, so a burst of SSE events processed by\n * the controller's `for await` pump becomes one `store.setState`\n * (and therefore one `useSyncExternalStore` notification).\n */\n #scheduleFlush = (): void => {\n if (this.#flushScheduled) return;\n this.#flushScheduled = true;\n setTimeout(this.#flushPending, 0);\n };\n\n /**\n * Drain `#pendingMessages` / `#pendingValues` to the store in a\n * single `setState` call.\n */\n #flushPending = (): void => {\n this.#flushScheduled = false;\n const messages = this.#pendingMessages;\n const values = this.#pendingValues;\n this.#pendingMessages = null;\n this.#pendingValues = null;\n if (messages == null && values == null) return;\n this.#store.setState((s) => {\n // Other rootStore mutators (controller-driven `isLoading`,\n // `interrupts`, `toolCalls`, etc.) do not touch `s.messages`\n // / `s.values`, so a last-write-wins commit on those two\n // fields is safe.\n if (messages == null) {\n return values == null ? s : { ...s, values };\n }\n if (values == null) return { ...s, messages };\n return { ...s, messages, values };\n });\n };\n}\n\n/**\n * Mirror a freshly-updated message list into `values[messagesKey]`.\n *\n * Returns the same `values` reference when the list is already\n * equal-by-content so the caller can keep the existing snapshot\n * identity (and avoid spurious `setSnapshot` notifications).\n */\nfunction syncMessagesIntoValues<StateType extends object>(\n values: StateType,\n messagesKey: string,\n messages: BaseMessage[]\n): StateType {\n const record = values as Record<string, unknown>;\n const current = record[messagesKey];\n if (Array.isArray(current) && messagesEqualList(current, messages)) {\n return values;\n }\n return {\n ...record,\n [messagesKey]: messages,\n } as StateType;\n}\n\n/**\n * True when two `BaseMessage` arrays carry the same per-message\n * content (using {@link messagesEqual}).\n */\nfunction messagesEqualList(\n previous: readonly BaseMessage[],\n next: readonly BaseMessage[]\n): boolean {\n if (previous === next) return true;\n if (previous.length !== next.length) return false;\n for (let i = 0; i < previous.length; i += 1) {\n if (!messagesEqual(previous[i], next[i])) return false;\n }\n return true;\n}\n\n/**\n * Shallow-equal for `values` objects, *ignoring* the messages slot.\n *\n * The messages array is compared separately by the caller (via\n * {@link messagesEqualList}) because both arrays contain class\n * instances whose JSON representation is not stable across reads.\n */\nfunction stateValuesShallowEqual(\n previous: object,\n next: object,\n messagesKey: string\n): boolean {\n if (previous === next) return true;\n const previousRecord = previous as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n const previousKeys = Object.keys(previousRecord);\n const nextKeys = Object.keys(nextRecord);\n if (previousKeys.length !== nextKeys.length) return false;\n for (const key of previousKeys) {\n if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) return false;\n const previousValue = previousRecord[key];\n const nextValue = nextRecord[key];\n if (\n key === messagesKey &&\n Array.isArray(previousValue) &&\n Array.isArray(nextValue)\n ) {\n continue;\n }\n if (!Object.is(previousValue, nextValue)) return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoGA,IAAa,wBAAb,MAGE;;;;;;CAMA;;CAGA;;;;;;CAOA,aAAa,IAAI,kBAAkB;;;;;;CAOnC,yBAAkB,IAAI,KAGnB;;;;;;CAOH,6BAAsB,IAAI,KAAqB;;;;;;;CAQ/C,oCAAoB,IAAI,KAAa;;;;;;CAOrC,yCAAkC,IAAI,KAAqB;;;;;;;;;;;;;CAc3D,mBAAyC;CACzC,iBAAmC;CACnC,kBAAkB;;;;;;;;;;;CAYlB,WAA+B,KAAA;;;;;;CAO/B,YAAY,QAGT;AACD,QAAA,cAAoB,OAAO;AAC3B,QAAA,QAAc,OAAO;;;;;;CAOvB,QAAc;AACZ,QAAA,YAAkB,IAAI,kBAAkB;AACxC,QAAA,MAAY,OAAO;AACnB,QAAA,UAAgB,OAAO;AACvB,QAAA,mCAAyB,IAAI,KAAK;AAClC,QAAA,sBAA4B,OAAO;AAInC,QAAA,kBAAwB;AACxB,QAAA,gBAAsB;AACtB,QAAA,iBAAuB;AACvB,QAAA,UAAgB,KAAA;;;;;;;;;;;;;CAclB,wBACE,WACA,YACM;AACN,QAAA,sBAA4B,IAAI,aAAa,UAAU,EAAE,WAAW;;;;;;;;;;;;CAatE,cAAc,OAA4B;EACxC,MAAM,OAAO,MAAM,OAAO;AAC1B,MAAI,KAAK,UAAU,iBAAiB;GAClC,MAAM,YAAY;GAClB,MAAM,OAAQ,UAAU,QAAQ;GAChC,MAAM,eACH,UAA6C,QAAQ;GACxD,IAAI,aAAc,UAAwC;AAI1D,OAAI,iBAAiB,UAAU,cAAc,MAAM;IACjD,MAAM,YAAY,UAAU;AAC5B,QAAI,aAAa,MAAM;KACrB,MAAM,QAAQ,c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ChD,MAAM,WAAW,OAAO,KAAK,WAAW;AACxC,KAAI,aAAa,WAAW,SAAS,OAAQ,QAAO;AACpD,MAAK,MAAM,OAAO,cAAc;AAC9B,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,YAAY,IAAI,CAAE,QAAO;EACnE,MAAM,gBAAgB,eAAe;EACrC,MAAM,YAAY,WAAW;AAC7B,MACE,QAAQ,eACR,MAAM,QAAQ,cAAc,IAC5B,MAAM,QAAQ,UAAU,CAExB;AAEF,MAAI,CAAC,OAAO,GAAG,eAAe,UAAU,CAAE,QAAO;;AAEnD,QAAO"} | ||
| {"version":3,"file":"root-message-projection.js","names":["#messagesKey","#store","#roles","#indexById","#toolCallIdByNamespace","#sealedMessageIds","#assembler","#valuesMessageIds","#pendingMessages","#pendingValues","#flushScheduled","#maxStep","#sealStep","#scheduleFlush","#flushPending"],"sources":["../../src/stream/root-message-projection.ts"],"sourcesContent":["/**\n * Root-namespace message projection.\n *\n * # What this module is\n *\n * The {@link RootMessageProjection} is the piece of the\n * {@link StreamController} that owns \"what messages does the root\n * namespace currently contain?\". It assembles streamed message deltas\n * via {@link MessageAssembler}, reconciles them against authoritative\n * `values.messages` snapshots from the server, and writes the merged\n * list back into the controller's root snapshot store.\n *\n * # Two streams of truth\n *\n * Root messages arrive on two channels and need to merge cleanly:\n *\n * - **`messages` channel.** Token-level deltas that build messages\n * incrementally. The {@link MessageAssembler} keeps partial\n * messages by id and emits an updated `BaseMessage` per delta.\n * - **`values` channel.** Periodic full-state snapshots that include\n * the authoritative messages array. Used for ordering, removals,\n * and forks (where the streamed messages may pre-date the new\n * timeline).\n *\n * The reconciliation rules (delegated to\n * {@link reconcileMessagesFromValues}) preserve in-flight streamed\n * content while letting values dictate ordering and removals.\n *\n * # Tool-message namespace correlation\n *\n * Tool messages arrive on `messages-start` events with `role: \"tool\"`\n * but the start event doesn't always include a `tool_call_id`. We\n * recover it via three fallbacks:\n *\n * 1. The start event itself, when the server includes it.\n * 2. The legacy `<id>-tool-<call_id>` message id format.\n * 3. The most recent `tool-started` event recorded under the same\n * namespace via {@link recordToolCallNamespace}.\n *\n * Without this correlation, tool messages render with empty\n * `tool_call_id` and downstream UIs can't pair them with the\n * originating tool call.\n *\n * # Store-write batching\n *\n * Every {@link handleMessage} / {@link applyValues} call updates the\n * in-projection bookkeeping (assembler state, id index, role cache)\n * synchronously, then stages the new `messages` / `values` into a\n * pending buffer and schedules a `setTimeout(0)` flush. A single\n * coalesced `store.setState` runs at the next macrotask boundary.\n *\n * The motivation is the long-replay freeze: a thread with hundreds\n * of messages replays through the `messages` channel on refresh or\n * mid-run join. Those events drain through the controller's\n * `for await` pump as a long microtask chain. Per-event\n * `store.setState` notifies `useSyncExternalStore` per event, and\n * after enough notifications React's `nestedUpdateCount` guard trips\n * with \"Maximum update depth exceeded\", permanently freezing the UI\n * on the first few messages. Coalescing to one notification per\n * macrotask lets React's scheduler commit between flushes.\n *\n * # Lifecycle\n *\n * - `handleMessage(event)` — apply a `messages` event delta.\n * - `applyValues(values, msgs)` — merge a `values` snapshot.\n * - `recordToolCallNamespace(ns, id)` — capture `namespace → tool_call_id`\n * so subsequent tool message starts can recover the id.\n * - `reset()` — clear all state on thread rebind.\n */\nimport type {\n MessagesEvent,\n MessageRole,\n MessageStartData,\n} from \"@langchain/protocol\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport { MessageAssembler } from \"../client/stream/messages.js\";\nimport {\n assembledMessageToBaseMessage,\n type ExtendedMessageRole,\n} from \"./assembled-to-message.js\";\nimport type { StreamStore } from \"./store.js\";\nimport type { RootSnapshot } from \"./types.js\";\nimport { namespaceKey } from \"./namespace.js\";\nimport {\n buildMessageIndex,\n messagesEqual,\n reconcileMessagesFromValues,\n shouldPreferValuesMessageForToolCalls,\n} from \"./message-reconciliation.js\";\n\n/**\n * Root-namespace message projection. Owns the merge between the\n * `messages` (streamed deltas) and `values` (authoritative\n * snapshots) channels for the root namespace.\n *\n * @typeParam StateType - Root state shape; the messages array is read\n * from `values[messagesKey]`.\n * @typeParam InterruptType - Shape of root protocol interrupts (forwarded\n * into `RootSnapshot` updates).\n */\nexport class RootMessageProjection<\n StateType extends object,\n InterruptType = unknown,\n> {\n /**\n * Key inside `values` that holds the message array. Defaults to\n * `\"messages\"` in the controller; configurable for state graphs\n * that surface messages under a different slot.\n */\n readonly #messagesKey: string;\n\n /** Root snapshot store written to on every merge. */\n readonly #store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n\n /**\n * Stateful chunk assembler for in-flight messages. Reset (via a\n * fresh instance) on every {@link reset} so a new thread starts\n * with no half-built messages from the previous one.\n */\n #assembler = new MessageAssembler();\n\n /**\n * `messageId → role/toolCallId` captured from `message-start` events.\n * The assembler's intermediate output drops these fields, so we cache\n * them at start-time and reapply when projecting to a `BaseMessage`.\n */\n readonly #roles = new Map<\n string,\n { role: ExtendedMessageRole; toolCallId?: string }\n >();\n\n /**\n * `messageId → position in #store.messages` for fast in-place\n * updates as deltas arrive. Rebuilt on every full reconciliation\n * driven by a `values` event.\n */\n readonly #indexById = new Map<string, number>();\n\n /**\n * Ids observed in the most recent `values.messages` snapshot.\n * Reconciliation uses this to detect server-side removals: a\n * previously-seen id missing from the next snapshot means it was\n * removed by the server (and should drop from the projection).\n */\n #valuesMessageIds = new Set<string>();\n\n /**\n * `namespaceKey → tool_call_id` captured from root `tool-started`\n * events. Used as a fallback when a tool-role `message-start` is\n * missing its `tool_call_id` field.\n */\n readonly #toolCallIdByNamespace = new Map<string, string>();\n\n /**\n * Coalescing buffer for store writes. {@link handleMessage} and\n * {@link applyValues} stage their computed `messages` / `values`\n * here instead of calling `store.setState` per event. A single\n * `setTimeout(0)` flush commits them in one `setState`, so a\n * burst of SSE events draining as a microtask chain becomes one\n * store notification at the next macrotask boundary.\n *\n * `null` means \"no staged write\" — once a flush settles, the\n * slots are cleared so the next call starts from the latest\n * committed store snapshot.\n */\n #pendingMessages: BaseMessage[] | null = null;\n #pendingValues: StateType | null = null;\n #flushScheduled = false;\n\n /**\n * Highest checkpoint `step` whose `values` snapshot has been applied.\n * Seeded by {@link StreamController.hydrate} from `getState()` and\n * advanced by live `values` events. A snapshot arriving with a lower\n * step is an older checkpoint replayed by the content pump on\n * reconnect; it is reconciled in add-only mode so it cannot remove\n * the seeded message tail (the final assistant turn). `undefined`\n * until the first step-bearing snapshot, where the legacy\n * remove-on-absence behavior is preserved.\n */\n #maxStep: number | undefined = undefined;\n\n /**\n * Message ids seeded as complete-and-final from an idle thread's\n * `getState()` snapshot. An idle thread defers its root SSE pump, and\n * the first `submit()` brings it up — at which point the transport\n * replays the finished run from `seq=0`. Unlike the `values` channel\n * (guarded by {@link #maxStep}), `messages`-channel deltas carry no\n * step, so that replay would otherwise rebuild each already-complete\n * message from an empty `message-start` and re-stream the whole turn\n * token-by-token, clobbering the seeded tail (a visible \"messages\n * replay\" on the first submit). Deltas for a sealed id are dropped in\n * {@link handleMessage}. The seal is lifted once a checkpoint advances\n * strictly past {@link #sealStep} (see {@link applyValues}) or on\n * thread rebind ({@link reset}). New ids from the next run are never\n * sealed, so they stream normally.\n */\n readonly #sealedMessageIds = new Set<string>();\n\n /**\n * High-water {@link #maxStep} captured when {@link sealMessageIds} ran,\n * i.e. the seed checkpoint's step (or `undefined` when `getState()`\n * carried no `metadata.step`). It is the boundary between the replayed\n * idle history (steps `<= #sealStep`, emitted by the deferred pump's\n * `seq=0` replay) and the new run (steps `> #sealStep`); only a\n * checkpoint strictly past it lifts the seal. Without this boundary the\n * replayed old-run checkpoints — which themselves carry increasing\n * steps — would advance {@link #maxStep} and lift the seal mid-replay,\n * reopening the clobber. When the seed step is unknown the boundary\n * stays `undefined` and the seal holds until {@link reset}; the\n * `values` channel (which ignores the seal) still reconciles any\n * genuine change to a sealed id, only its streamed deltas are dropped.\n */\n #sealStep: number | undefined = undefined;\n\n /**\n * @param params.messagesKey - Key inside `values` that holds the\n * message array.\n * @param params.store - Root snapshot store to mutate.\n */\n constructor(params: {\n messagesKey: string;\n store: StreamStore<RootSnapshot<StateType, InterruptType>>;\n }) {\n this.#messagesKey = params.messagesKey;\n this.#store = params.store;\n }\n\n /**\n * Drop all per-thread state. Called by the controller on thread\n * rebind / dispose so a swap doesn't surface stale messages.\n */\n reset(): void {\n this.#assembler = new MessageAssembler();\n this.#roles.clear();\n this.#indexById.clear();\n this.#valuesMessageIds = new Set();\n this.#toolCallIdByNamespace.clear();\n // Drop any unflushed pending writes — they were computed against\n // the previous thread's baseline and committing them after a\n // rebind would bleed stale messages into the new thread.\n this.#pendingMessages = null;\n this.#pendingValues = null;\n this.#flushScheduled = false;\n this.#maxStep = undefined;\n this.#sealedMessageIds.clear();\n this.#sealStep = undefined;\n }\n\n /**\n * Seal message ids so the streamed `messages` channel cannot downgrade\n * them to partial re-streams. Called by {@link StreamController.hydrate}\n * after seeding an idle thread, whose deferred pump replays the finished\n * run from `seq=0` on the first submit.\n *\n * Captures the current {@link #maxStep} as the lift boundary\n * ({@link #sealStep}). The seal is applied immediately after the seed's\n * `getState()` snapshot is reconciled, so `#maxStep` here is the seed\n * step (or `undefined` when `getState()` carried no `metadata.step`).\n * The seal is lifted once a checkpoint advances strictly past that\n * boundary (see {@link applyValues}) or on thread rebind\n * ({@link reset}).\n *\n * @param ids - Complete message ids from the idle `getState()` seed.\n */\n sealMessageIds(ids: Iterable<string>): void {\n for (const id of ids) this.#sealedMessageIds.add(id);\n if (this.#sealStep == null) this.#sealStep = this.#maxStep;\n }\n\n /**\n * Record a `namespace → tool_call_id` mapping captured from a root\n * `tool-started` event.\n *\n * The companion tool-role `message-start` event may not carry a\n * `tool_call_id`, so we fall back to the most recent value recorded\n * here for the same namespace.\n *\n * @param namespace - Event namespace from the `tool-started` event.\n * @param toolCallId - Tool call id from the same event.\n */\n recordToolCallNamespace(\n namespace: readonly string[],\n toolCallId: string\n ): void {\n this.#toolCallIdByNamespace.set(namespaceKey(namespace), toolCallId);\n }\n\n /**\n * Apply a `messages` channel event to the projection.\n *\n * Captures role/tool metadata on `message-start`, feeds the chunk\n * to the assembler, projects the assembled output to a\n * {@link BaseMessage}, and either appends or in-place updates the\n * pending messages buffer based on whether the id was seen before.\n *\n * @param event - The `messages` channel event to consume.\n */\n handleMessage(event: MessagesEvent): void {\n const data = event.params.data;\n if (data.event === \"message-start\") {\n const startData = data as MessageStartData;\n const role = (startData.role ?? \"ai\") as MessageRole;\n const extendedRole =\n (startData as { role?: ExtendedMessageRole }).role ?? role;\n let toolCallId = (startData as { tool_call_id?: string }).tool_call_id;\n // Tool messages need a tool_call_id to render. Fall back through:\n // 1. legacy `<id>-tool-<call_id>` message id format\n // 2. namespace-recorded tool_call_id (from #recordToolCallNamespace)\n if (extendedRole === \"tool\" && toolCallId == null) {\n const messageId = startData.id;\n if (messageId != null) {\n const match = /-tool-(.+)$/.exec(messageId);\n if (match != null) toolCallId = match[1];\n }\n if (toolCallId == null) {\n toolCallId = this.#toolCallIdByNamespace.get(\n namespaceKey(event.params.namespace)\n );\n }\n }\n if (startData.id != null) {\n this.#roles.set(startData.id, {\n role: extendedRole,\n toolCallId,\n });\n }\n }\n\n const update = this.#assembler.consume(event);\n if (update == null) return;\n const id = update.message.id;\n if (id == null) return;\n // A sealed id belongs to a message seeded complete from an idle\n // thread's `getState()`; the deferred pump's `seq=0` replay would\n // otherwise rebuild it from an empty start and re-stream the whole\n // turn. Drop the replayed delta — the authoritative seed already\n // holds the final content (see {@link #sealedMessageIds}).\n if (this.#sealedMessageIds.has(id)) return;\n const captured = this.#roles.get(id) ?? { role: \"ai\" as const };\n const base = assembledMessageToBaseMessage(update.message, captured.role, {\n toolCallId: captured.toolCallId,\n });\n\n // Compute against the pending baseline if we have one (so an\n // earlier handleMessage in the same tick is the input to this\n // one), else against the latest committed store snapshot.\n // `#indexById` is the synchronous source of truth for \"where is\n // each id in the current messages list\" — every code path below\n // keeps it in sync before returning.\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const existingIdx = this.#indexById.get(id);\n let messages: BaseMessage[];\n if (existingIdx == null) {\n this.#indexById.set(id, baselineMessages.length);\n messages = [...baselineMessages, base];\n } else if (messagesEqual(baselineMessages[existingIdx], base)) {\n // Identical re-emission — skip the store write to keep\n // snapshot identity stable.\n return;\n } else {\n messages = baselineMessages.slice();\n messages[existingIdx] = base;\n }\n\n // Mirror the new messages list into `values[messagesKey]` so\n // direct `values` reads (used by some hooks and by the eventual\n // `values` reconciliation) stay in sync.\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const values = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n messages\n );\n this.#pendingMessages = messages;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Reconcile a full `values` snapshot into the projection.\n *\n * Delegates the merge to {@link reconcileMessagesFromValues}:\n * values stays authoritative for ordering and removals, while\n * streamed in-flight messages keep their content until the server\n * echoes them back. Empty messages just refresh the values blob.\n *\n * Rebuilds {@link #indexById} after the merge so subsequent delta\n * applications target the new positions.\n *\n * @param nextValues - Full values snapshot from the `values` event.\n * @param nextMessages - The messages array extracted from\n * `values[messagesKey]` and coerced to `BaseMessage` instances.\n * @param opts.step - Checkpoint superstep for this snapshot, when\n * known. A snapshot whose step is below the highest applied step is\n * treated as a stale reconnect replay and reconciled add-only.\n */\n applyValues(\n nextValues: StateType,\n nextMessages: BaseMessage[],\n opts?: { step?: number }\n ): void {\n const baselineSnapshot = this.#store.getSnapshot();\n const baselineMessages = this.#pendingMessages ?? baselineSnapshot.messages;\n const baselineValues = this.#pendingValues ?? baselineSnapshot.values;\n\n const step = opts?.step;\n // Stale only when we have both a prior high-water step and a lower\n // incoming step. A missing step preserves the legacy semantics.\n const addOnly =\n step != null && this.#maxStep != null && step < this.#maxStep;\n if (step != null && (this.#maxStep == null || step > this.#maxStep)) {\n this.#maxStep = step;\n }\n // Lift the replay seal only when a checkpoint advances strictly past\n // the step captured when the ids were sealed (the seed step). That\n // boundary separates the replayed idle history (steps <= #sealStep,\n // emitted by the deferred pump's seq=0 replay) from the new run\n // (steps > #sealStep), so crossing it means seeded ids may now take\n // genuine streamed updates. Replayed old-run checkpoints advance\n // #maxStep but never reach past #sealStep, so they can't lift it. A\n // `null` boundary (the seed step was unknown) keeps the seal until\n // reset() — we can't tell replay from live, and the values channel\n // still reconciles a sealed id even while its streamed deltas drop.\n if (\n this.#sealedMessageIds.size > 0 &&\n step != null &&\n this.#sealStep != null &&\n step > this.#sealStep\n ) {\n this.#sealedMessageIds.clear();\n }\n\n if (nextMessages.length === 0) {\n if (\n stateValuesShallowEqual(baselineValues, nextValues, this.#messagesKey)\n ) {\n return;\n }\n // Mirror the current `messages` list back into the values slot\n // so the staged snapshot stays consistent with the (separately\n // tracked) messages array.\n this.#pendingValues = syncMessagesIntoValues(\n nextValues,\n this.#messagesKey,\n baselineMessages\n );\n this.#scheduleFlush();\n return;\n }\n\n const reconciliation = reconcileMessagesFromValues({\n valueMessages: nextMessages,\n currentMessages: baselineMessages,\n currentIndexById: this.#indexById,\n previousValueMessageIds: this.#valuesMessageIds,\n preferValuesMessage: shouldPreferValuesMessageForToolCalls,\n addOnly,\n });\n // A stale replay snapshot must not shrink the authoritative id set:\n // keep the (larger) seeded set so a genuinely-newer removal is still\n // detected once the timeline advances past the seed.\n if (!addOnly) this.#valuesMessageIds = reconciliation.valueMessageIds;\n const messages = reconciliation.messages as BaseMessage[];\n const values = {\n ...(nextValues as Record<string, unknown>),\n [this.#messagesKey]: messages,\n } as StateType;\n if (\n messages === baselineMessages &&\n stateValuesShallowEqual(baselineValues, values, this.#messagesKey)\n ) {\n return;\n }\n\n // Reconciliation may reorder, drop, or substitute messages, so\n // rebuild the id → index map to match the new array.\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(messages)) {\n this.#indexById.set(id, idx);\n }\n this.#pendingMessages = messages;\n this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Append messages applied optimistically by a local `submit()`,\n * keyed by id so the eventual server echo reconciles cleanly.\n *\n * Unlike {@link applyValues}, the supplied messages are *not* treated\n * as an authoritative ordered snapshot: they are appended to the end\n * of the current projection (or replaced in place when the id already\n * exists), preserving prior history ordering. When the server later\n * emits a `values` snapshot containing the same ids,\n * {@link applyValues} → {@link reconcileMessagesFromValues} takes over\n * (server ordering wins, the echoed message replaces the optimistic\n * one).\n *\n * Non-message input keys are shallow-merged into `values` via\n * `extraValues`; they are dropped/overwritten automatically by the\n * first server `values` event (which rebuilds `values` from the\n * server snapshot), or rolled back via {@link restoreValueKeys} when\n * the run fails before any echo.\n *\n * @param messages - Optimistic messages (already coerced to\n * `BaseMessage` instances, each carrying a stable id).\n * @param extraValues - Non-message input keys to shallow-merge into\n * `values`.\n */\n appendOptimistic(\n messages: BaseMessage[],\n extraValues?: Record<string, unknown>\n ): void {\n let working = this.#pendingMessages ?? this.#store.getSnapshot().messages;\n let mutated = false;\n for (const message of messages) {\n const id = message.id;\n if (id == null) continue;\n const existingIdx = this.#indexById.get(id);\n if (existingIdx == null) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n this.#indexById.set(id, working.length);\n working.push(message);\n } else if (!messagesEqual(working[existingIdx], message)) {\n if (!mutated) {\n working = working.slice();\n mutated = true;\n }\n working[existingIdx] = message;\n }\n }\n\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n let values = baselineValues;\n if (extraValues != null && Object.keys(extraValues).length > 0) {\n values = { ...(baselineValues as object), ...extraValues } as StateType;\n }\n values = syncMessagesIntoValues(values, this.#messagesKey, working);\n if (!mutated && values === baselineValues) return;\n this.#pendingMessages = working;\n if (values !== baselineValues) this.#pendingValues = values;\n this.#scheduleFlush();\n }\n\n /**\n * Drop optimistic messages by id without disturbing the rest of the\n * projection. Used by {@link StreamController.hydrate} to remove\n * never-persisted optimistic messages (`pending` / `failed`) so a\n * reload converges to server truth.\n *\n * @param ids - Message ids to remove.\n */\n dropOptimisticMessages(ids: ReadonlySet<string>): void {\n if (ids.size === 0) return;\n const baselineMessages =\n this.#pendingMessages ?? this.#store.getSnapshot().messages;\n const next = baselineMessages.filter((m) => m.id == null || !ids.has(m.id));\n if (next.length === baselineMessages.length) return;\n this.#indexById.clear();\n for (const [id, idx] of buildMessageIndex(next)) {\n this.#indexById.set(id, idx);\n }\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n this.#pendingMessages = next;\n this.#pendingValues = syncMessagesIntoValues(\n baselineValues,\n this.#messagesKey,\n next\n );\n this.#scheduleFlush();\n }\n\n /**\n * Restore (or delete) `values` keys that were optimistically merged\n * by {@link appendOptimistic} but never echoed by the server — i.e.\n * roll back non-message optimistic state when the run fails before\n * any `values` event lands. Messages are left untouched (kept on\n * failure per the optimistic contract).\n *\n * @param restore - Per-key pre-submit snapshot: when `hadKey` is\n * false the key is deleted, otherwise it is reset to `prevValue`.\n */\n restoreValueKeys(\n restore: ReadonlyArray<{\n key: string;\n hadKey: boolean;\n prevValue: unknown;\n }>\n ): void {\n if (restore.length === 0) return;\n const baselineValues =\n this.#pendingValues ?? this.#store.getSnapshot().values;\n const next = { ...(baselineValues as Record<string, unknown>) };\n let changed = false;\n for (const { key, hadKey, prevValue } of restore) {\n if (key === this.#messagesKey) continue;\n if (hadKey) {\n if (!Object.is(next[key], prevValue)) {\n next[key] = prevValue;\n changed = true;\n }\n } else if (Object.prototype.hasOwnProperty.call(next, key)) {\n delete next[key];\n changed = true;\n }\n }\n if (!changed) return;\n this.#pendingValues = next as StateType;\n this.#scheduleFlush();\n }\n\n /**\n * Schedule a coalesced flush on the next macrotask. Idempotent\n * within a tick — multiple `handleMessage` / `applyValues` calls\n * before the flush fires collapse into one store write.\n *\n * `setTimeout(0)` is a macrotask: it runs after the current\n * microtask chain drains, so a burst of SSE events processed by\n * the controller's `for await` pump becomes one `store.setState`\n * (and therefore one `useSyncExternalStore` notification).\n */\n #scheduleFlush = (): void => {\n if (this.#flushScheduled) return;\n this.#flushScheduled = true;\n setTimeout(this.#flushPending, 0);\n };\n\n /**\n * Drain `#pendingMessages` / `#pendingValues` to the store in a\n * single `setState` call.\n */\n #flushPending = (): void => {\n this.#flushScheduled = false;\n const messages = this.#pendingMessages;\n const values = this.#pendingValues;\n this.#pendingMessages = null;\n this.#pendingValues = null;\n if (messages == null && values == null) return;\n this.#store.setState((s) => {\n // Other rootStore mutators (controller-driven `isLoading`,\n // `interrupts`, `toolCalls`, etc.) do not touch `s.messages`\n // / `s.values`, so a last-write-wins commit on those two\n // fields is safe.\n if (messages == null) {\n return values == null ? s : { ...s, values };\n }\n if (values == null) return { ...s, messages };\n return { ...s, messages, values };\n });\n };\n}\n\n/**\n * Mirror a freshly-updated message list into `values[messagesKey]`.\n *\n * Returns the same `values` reference when the list is already\n * equal-by-content so the caller can keep the existing snapshot\n * identity (and avoid spurious `setSnapshot` notifications).\n */\nfunction syncMessagesIntoValues<StateType extends object>(\n values: StateType,\n messagesKey: string,\n messages: BaseMessage[]\n): StateType {\n const record = values as Record<string, unknown>;\n const current = record[messagesKey];\n if (Array.isArray(current) && messagesEqualList(current, messages)) {\n return values;\n }\n return {\n ...record,\n [messagesKey]: messages,\n } as StateType;\n}\n\n/**\n * True when two `BaseMessage` arrays carry the same per-message\n * content (using {@link messagesEqual}).\n */\nfunction messagesEqualList(\n previous: readonly BaseMessage[],\n next: readonly BaseMessage[]\n): boolean {\n if (previous === next) return true;\n if (previous.length !== next.length) return false;\n for (let i = 0; i < previous.length; i += 1) {\n if (!messagesEqual(previous[i], next[i])) return false;\n }\n return true;\n}\n\n/**\n * Shallow-equal for `values` objects, *ignoring* the messages slot.\n *\n * The messages array is compared separately by the caller (via\n * {@link messagesEqualList}) because both arrays contain class\n * instances whose JSON representation is not stable across reads.\n */\nfunction stateValuesShallowEqual(\n previous: object,\n next: object,\n messagesKey: string\n): boolean {\n if (previous === next) return true;\n const previousRecord = previous as Record<string, unknown>;\n const nextRecord = next as Record<string, unknown>;\n const previousKeys = Object.keys(previousRecord);\n const nextKeys = Object.keys(nextRecord);\n if (previousKeys.length !== nextKeys.length) return false;\n for (const key of previousKeys) {\n if (!Object.prototype.hasOwnProperty.call(nextRecord, key)) return false;\n const previousValue = previousRecord[key];\n const nextValue = nextRecord[key];\n if (\n key === messagesKey &&\n Array.isArray(previousValue) &&\n Array.isArray(nextValue)\n ) {\n continue;\n }\n if (!Object.is(previousValue, nextValue)) return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoGA,IAAa,wBAAb,MAGE;;;;;;CAMA;;CAGA;;;;;;CAOA,aAAa,IAAI,kBAAkB;;;;;;CAOnC,yBAAkB,IAAI,KAGnB;;;;;;CAOH,6BAAsB,IAAI,KAAqB;;;;;;;CAQ/C,oCAAoB,IAAI,KAAa;;;;;;CAOrC,yCAAkC,IAAI,KAAqB;;;;;;;;;;;;;CAc3D,mBAAyC;CACzC,iBAAmC;CACnC,kBAAkB;;;;;;;;;;;CAYlB,WAA+B,KAAA;;;;;;;;;;;;;;;;CAiB/B,oCAA6B,IAAI,KAAa;;;;;;;;;;;;;;;CAgB9C,YAAgC,KAAA;;;;;;CAOhC,YAAY,QAGT;AACD,QAAA,cAAoB,OAAO;AAC3B,QAAA,QAAc,OAAO;;;;;;CAOvB,QAAc;AACZ,QAAA,YAAkB,IAAI,kBAAkB;AACxC,QAAA,MAAY,OAAO;AACnB,QAAA,UAAgB,OAAO;AACvB,QAAA,mCAAyB,IAAI,KAAK;AAClC,QAAA,sBAA4B,OAAO;AAInC,QAAA,kBAAwB;AACxB,QAAA,gBAAsB;AACtB,QAAA,iBAAuB;AACvB,QAAA,UAAgB,KAAA;AAChB,QAAA,iBAAuB,OAAO;AAC9B,QAAA,WAAiB,KAAA;;;;;;;;;;;;;;;;;;CAmBnB,eAAe,KAA6B;AAC1C,OAAK,MAAM,MAAM,IAAK,OAAA,iBAAuB,IAAI,GAAG;AACpD,MAAI,MAAA,YAAkB,KAAM,OAAA,WAAiB,MAAA;;;;;;;;;;;;;CAc/C,wBACE,WACA,YACM;AACN,QAAA,sBAA4B,IAAI,aAAa,UAAU,EAAE,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Q,QAAQ,IAAI,kBAAkB,SAAS,SAAS,CAChE,QAAO;AAET,QAAO;EACL,GAAG;GACF,cAAc;EAChB;;;;;;AAOH,SAAS,kBACP,UACA,MACS;AACT,KAAI,aAAa,KAAM,QAAO;AAC9B,KAAI,SAAS,WAAW,KAAK,OAAQ,QAAO;AAC5C,MAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK,EACxC,KAAI,CAAC,cAAc,SAAS,IAAI,KAAK,GAAG,CAAE,QAAO;AAEnD,QAAO;;;;;;;;;AAUT,SAAS,wBACP,UACA,MACA,aACS;AACT,KAAI,aAAa,KAAM,QAAO;CAC9B,MAAM,iBAAiB;CACvB,MAAM,aAAa;CACnB,MAAM,eAAe,OAAO,KAAK,eAAe;CAChD,MAAM,WAAW,OAAO,KAAK,WAAW;AACxC,KAAI,aAAa,WAAW,SAAS,OAAQ,QAAO;AACpD,MAAK,MAAM,OAAO,cAAc;AAC9B,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,YAAY,IAAI,CAAE,QAAO;EACnE,MAAM,gBAAgB,eAAe;EACrC,MAAM,YAAY,WAAW;AAC7B,MACE,QAAQ,eACR,MAAM,QAAQ,cAAc,IAC5B,MAAM,QAAQ,UAAU,CAExB;AAEF,MAAI,CAAC,OAAO,GAAG,eAAe,UAAU,CAAE,QAAO;;AAEnD,QAAO"} |
@@ -26,3 +26,3 @@ import { ThreadState } from "../schema.cjs"; | ||
| branchByCheckpoint: BranchByCheckpoint; | ||
| threadHead: any; | ||
| threadHead: ThreadState<any> | undefined; | ||
| }; | ||
@@ -29,0 +29,0 @@ declare function getMessagesMetadataMap<StateType extends Record<string, unknown>>(options: { |
@@ -26,3 +26,3 @@ import { ThreadState } from "../schema.js"; | ||
| branchByCheckpoint: BranchByCheckpoint; | ||
| threadHead: any; | ||
| threadHead: ThreadState<any> | undefined; | ||
| }; | ||
@@ -29,0 +29,0 @@ declare function getMessagesMetadataMap<StateType extends Record<string, unknown>>(options: { |
@@ -111,3 +111,3 @@ import { Interrupt, ThreadState } from "../schema.cjs"; | ||
| }; | ||
| threadHead: any; | ||
| threadHead: ThreadState<any> | undefined; | ||
| }; | ||
@@ -114,0 +114,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"orchestrator.d.cts","names":[],"sources":["../../src/ui/orchestrator.ts"],"mappings":";;;;;;;;;;;;;;;;;AA0GA;UAAiB,qBAAA;EACf,SAAA,IAAa,MAAA;EACb,cAAA;EACA,cAAA;AAAA;;;;;AAaF;;;;;;cAAa,kBAAA,mBACO,MAAA,oBAA0B,MAAA,+BAChC,WAAA,GAAc,WAAA;EAAA;WAEjB,MAAA,EAAQ,aAAA,CAAc,SAAA,EAAW,GAAA;EAAA,SAEjC,cAAA,EAAgB,mBAAA;EAAA,SAEhB,WAAA,EAAa,kBAAA,CACpB,SAAA,EACA,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA;EAAA,SAOtC,YAAA;EAPO;;;;;;;;EA+ChB,WAAA,CACE,OAAA,EAAS,gBAAA,CAAiB,SAAA,EAAW,GAAA,GACrC,SAAA,EAAW,qBAAA;EA0JsB;;;;;;;EAlGnC,SAAA,CAAU,QAAA;EAwQc;;;;;;EA3PxB,WAAA,CAAA;EA+R4B;;;EAAA,IA5QxB,QAAA,CAAA;EAwSa;;;;;;EA9RjB,WAAA,CAAY,KAAA;EAuWT;;;;;EAAA,IA/SC,WAAA,CAAA,GAAe,eAAA,CAAgB,SAAA;EAkUnB;;;;EAxRhB,YAAA,CAAa,QAAA;EA2UU;;;;EAAA,IAjUnB,MAAA,CAAA;EAqV2B;;;;;EA5U/B,SAAA,CAAU,KAAA;EAwYgB;;;;;EAAA,IA7XtB,aAAA,CAAA;gBAxE8B,QAAA;;;;;;;;;;EAgxBvB;;;;;EAAA,IArrBP,aAAA,CAAA,GAAiB,SAAA;EA/SuB;;;;EAAA,IA2TxC,YAAA,CAAA;EAxTK;;;;EAAA,IAyUL,YAAA,CAAA,GAAgB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;MACA,KAAA,EAAO,WAAA;MACP,IAAA;IAAA;EAAA,IAGH,OAAA;;;;;;;;;;;EAiFH,YAAA,CACE,MAAA,EAAQ,SAAA,EACR,aAAA,GAAgB,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA,KAAK,OAAA;;;;;EAoLpE,UAAA,CAAA;;;;;;;;;;;;EAeM,MAAA,CACJ,MAAA,EAAQ,SAAA,EACR,aAAA,GAAgB,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA,KAC5D,OAAA,CAAQ,UAAA,aAAuB,YAAA;;;;;;;;;EAqElC,YAAA,CAAa,WAAA;;;;;EA8Bb,YAAA,CAAA;;;;;MAiBI,eAAA,CAAA;;;;;;EASJ,OAAA,CAAA;AAAA"} |
@@ -111,3 +111,3 @@ import { Interrupt, ThreadState } from "../schema.js"; | ||
| }; | ||
| threadHead: any; | ||
| threadHead: ThreadState<any> | undefined; | ||
| }; | ||
@@ -114,0 +114,0 @@ /** |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"orchestrator.d.ts","names":[],"sources":["../../src/ui/orchestrator.ts"],"mappings":";;;;;;;;;;;;;;;;;;UA0GiB,qBAAA;EACf,SAAA,IAAa,MAAA;EACb,cAAA;EACA,cAAA;AAAA;;;;;;AAaF;;;;;cAAa,kBAAA,mBACO,MAAA,oBAA0B,MAAA,+BAChC,WAAA,GAAc,WAAA;EAAA;WAEjB,MAAA,EAAQ,aAAA,CAAc,SAAA,EAAW,GAAA;EAAA,SAEjC,cAAA,EAAgB,mBAAA;EAAA,SAEhB,WAAA,EAAa,kBAAA,CACpB,SAAA,EACA,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA;EAAA,SAOtC,YAAA;EARP;;;;;;;;EAgDF,WAAA,CACE,OAAA,EAAS,gBAAA,CAAiB,SAAA,EAAW,GAAA,GACrC,SAAA,EAAW,qBAAA;EAAA;;;;;;;EAwDb,SAAA,CAAU,QAAA;EAgQM;;;;;;EAnP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,eAAA;EAmF9B;;;;;;EAzEA,kBAAA,CAAmB,IAAA,WAAY,uBAAA,CAAA,MAAA,mBAAA,eAAA;EAwG3B;;;;;;;EA7FJ,qBAAA,CAAsB,SAAA,WAAiB,uBAAA,CAAA,MAAA,mBAAA,eAAA;EAoLvC;;;;;;EA1KA,4BAAA,CAAA,GAAgC,eAAA;EA4K9B;;;;;;EArIF,eAAA,CAAA,GAAmB,KAAA,EAAO,UAAA;EA0UM;;;;;EA7ThC,IAAA,CAAA;EA8TkC;;;;;;;;;EApS5B,UAAA,CACJ,KAAA,UACA,WAAA,WACA,WAAA;IACE,UAAA,GAAa,UAAA,GAAa,UAAA;IAC1B,MAAA,IAAU,KAAA;MACR,EAAA;MACA,KAAA,EAAO,WAAA;MACP,IAAA;IAAA;EAAA,IAGH,OAAA;;;;;;;;;;;EAiFH,YAAA,CACE,MAAA,EAAQ,SAAA,EACR,aAAA,GAAgB,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA,KAAK,OAAA;;;;;EAoLpE,UAAA,CAAA;;;;;;;;;;;;EAeM,MAAA,CACJ,MAAA,EAAQ,SAAA,EACR,aAAA,GAAgB,aAAA,CAAc,SAAA,EAAW,mBAAA,CAAoB,GAAA,KAC5D,OAAA,CAAQ,UAAA,aAAuB,YAAA;;;;;;;;;EAqElC,YAAA,CAAa,WAAA;;;;;EA8Bb,YAAA,CAAA;;;;;MAiBI,eAAA,CAAA;;;;;;EASJ,OAAA,CAAA;AAAA"} |
@@ -7,3 +7,2 @@ //#region src/utils/stream.d.ts | ||
| declare class IterableReadableStream<T> extends ReadableStream<T> implements IterableReadableStreamInterface<T> { | ||
| [Symbol.asyncDispose]: () => Promise<void>; | ||
| reader: ReadableStreamDefaultReader<T>; | ||
@@ -14,2 +13,3 @@ ensureReader(): void; | ||
| throw(e: any): Promise<IteratorResult<T>>; | ||
| [Symbol.asyncDispose](): Promise<void>; | ||
| [Symbol.asyncIterator](): this; | ||
@@ -16,0 +16,0 @@ static fromReadableStream<T>(stream: ReadableStream<T>): IterableReadableStream<T>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"stream.d.cts","names":[],"sources":["../../src/utils/stream.ts"],"mappings":";KAGK,+BAAA,MAAqC,cAAA,CAAe,CAAA,IAAK,aAAA,CAAc,CAAA;;;;cAyL/D,sBAAA,YACH,cAAA,CAAe,CAAA,aACZ,+BAAA,CAAgC,CAAA;EAAA,CAwDpC,MAAA,CAAO,YAAA,SAAa,OAAA;EAtDpB,MAAA,EAAQ,2BAAA,CAA4B,CAAA;EAE3C,YAAA,CAAA;EAMM,IAAA,CAAA,GAAQ,OAAA,CAAQ,cAAA,CAAe,CAAA;EAsB/B,MAAA,CAAA,GAAU,OAAA,CAAQ,cAAA,CAAe,CAAA;EAYjC,KAAA,CAAM,CAAA,QAAS,OAAA,CAAQ,cAAA,CAAe,CAAA;EAAA,CAgB3C,MAAA,CAAO,aAAA;EAAA,OAID,kBAAA,GAAA,CAAsB,MAAA,EAAQ,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;EAAA,OAyB/C,kBAAA,GAAA,CAAsB,SAAA,EAAW,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;AAAA"} | ||
| {"version":3,"file":"stream.d.cts","names":[],"sources":["../../src/utils/stream.ts"],"mappings":";KAGK,+BAAA,MAAqC,cAAA,CAAe,CAAA,IAAK,aAAA,CAAc,CAAA;;;;cAyL/D,sBAAA,YACH,cAAA,CAAe,CAAA,aACZ,+BAAA,CAAgC,CAAA;EAEpC,MAAA,EAAQ,2BAAA,CAA4B,CAAA;EAE3C,YAAA,CAAA;EAMM,IAAA,CAAA,GAAQ,OAAA,CAAQ,cAAA,CAAe,CAAA;EAsB/B,MAAA,CAAA,GAAU,OAAA,CAAQ,cAAA,CAAe,CAAA;EAYjC,KAAA,CAAM,CAAA,QAAS,OAAA,CAAQ,cAAA,CAAe,CAAA;EAAA,CAYrC,MAAA,CAAO,YAAA,KAAa,OAAA;EAAA,CAI1B,MAAA,CAAO,aAAA;EAAA,OAID,kBAAA,GAAA,CAAsB,MAAA,EAAQ,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;EAAA,OAyB/C,kBAAA,GAAA,CAAsB,SAAA,EAAW,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;AAAA"} |
@@ -7,3 +7,2 @@ //#region src/utils/stream.d.ts | ||
| declare class IterableReadableStream<T> extends ReadableStream<T> implements IterableReadableStreamInterface<T> { | ||
| [Symbol.asyncDispose]: () => Promise<void>; | ||
| reader: ReadableStreamDefaultReader<T>; | ||
@@ -14,2 +13,3 @@ ensureReader(): void; | ||
| throw(e: any): Promise<IteratorResult<T>>; | ||
| [Symbol.asyncDispose](): Promise<void>; | ||
| [Symbol.asyncIterator](): this; | ||
@@ -16,0 +16,0 @@ static fromReadableStream<T>(stream: ReadableStream<T>): IterableReadableStream<T>; |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"stream.d.ts","names":[],"sources":["../../src/utils/stream.ts"],"mappings":";KAGK,+BAAA,MAAqC,cAAA,CAAe,CAAA,IAAK,aAAA,CAAc,CAAA;;;;cAyL/D,sBAAA,YACH,cAAA,CAAe,CAAA,aACZ,+BAAA,CAAgC,CAAA;EAAA,CAwDpC,MAAA,CAAO,YAAA,SAAa,OAAA;EAtDpB,MAAA,EAAQ,2BAAA,CAA4B,CAAA;EAE3C,YAAA,CAAA;EAMM,IAAA,CAAA,GAAQ,OAAA,CAAQ,cAAA,CAAe,CAAA;EAsB/B,MAAA,CAAA,GAAU,OAAA,CAAQ,cAAA,CAAe,CAAA;EAYjC,KAAA,CAAM,CAAA,QAAS,OAAA,CAAQ,cAAA,CAAe,CAAA;EAAA,CAgB3C,MAAA,CAAO,aAAA;EAAA,OAID,kBAAA,GAAA,CAAsB,MAAA,EAAQ,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;EAAA,OAyB/C,kBAAA,GAAA,CAAsB,SAAA,EAAW,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;AAAA"} | ||
| {"version":3,"file":"stream.d.ts","names":[],"sources":["../../src/utils/stream.ts"],"mappings":";KAGK,+BAAA,MAAqC,cAAA,CAAe,CAAA,IAAK,aAAA,CAAc,CAAA;;;;cAyL/D,sBAAA,YACH,cAAA,CAAe,CAAA,aACZ,+BAAA,CAAgC,CAAA;EAEpC,MAAA,EAAQ,2BAAA,CAA4B,CAAA;EAE3C,YAAA,CAAA;EAMM,IAAA,CAAA,GAAQ,OAAA,CAAQ,cAAA,CAAe,CAAA;EAsB/B,MAAA,CAAA,GAAU,OAAA,CAAQ,cAAA,CAAe,CAAA;EAYjC,KAAA,CAAM,CAAA,QAAS,OAAA,CAAQ,cAAA,CAAe,CAAA;EAAA,CAYrC,MAAA,CAAO,YAAA,KAAa,OAAA;EAAA,CAI1B,MAAA,CAAO,aAAA;EAAA,OAID,kBAAA,GAAA,CAAsB,MAAA,EAAQ,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;EAAA,OAyB/C,kBAAA,GAAA,CAAsB,SAAA,EAAW,cAAA,CAAe,CAAA,IAAE,sBAAA,CAAA,CAAA;AAAA"} |
+5
-2
| { | ||
| "name": "@langchain/langgraph-sdk", | ||
| "version": "1.9.20", | ||
| "version": "1.9.21", | ||
| "description": "Client library for interacting with the LangGraph API", | ||
@@ -27,2 +27,3 @@ "type": "module", | ||
| "@types/uuid": "^9.0.1", | ||
| "@types/ws": "^8.18.1", | ||
| "deepagents": "^1.8.3", | ||
@@ -36,2 +37,3 @@ "langchain": "^1.4.4", | ||
| "vue": "^3.5.35", | ||
| "ws": "^8.18.3", | ||
| "zod": "^4.3.5" | ||
@@ -194,4 +196,5 @@ }, | ||
| "lint:eslint": "NODE_OPTIONS=--max-old-space-size=4096 eslint --cache --ext .ts,.js,.jsx,.tsx src/", | ||
| "test": "vitest run" | ||
| "test": "vitest run", | ||
| "test:int": "vitest run --mode int" | ||
| } | ||
| } |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
4400101
2.12%687
1.18%41004
1.88%18
12.5%246
2.5%