@langchain/react 1.0.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/use-stream.cjs +5 -3
- package/dist/use-stream.cjs.map +1 -1
- package/dist/use-stream.d.cts +66 -1
- package/dist/use-stream.d.cts.map +1 -1
- package/dist/use-stream.d.ts +66 -1
- package/dist/use-stream.d.ts.map +1 -1
- package/dist/use-stream.js +5 -3
- package/dist/use-stream.js.map +1 -1
- package/package.json +2 -2
package/dist/use-stream.cjs
CHANGED
|
@@ -110,11 +110,13 @@ function useStream(options) {
|
|
|
110
110
|
(0, react.useEffect)(() => {
|
|
111
111
|
if (!tools?.length) return;
|
|
112
112
|
const valuesBag = rootValuesForTools;
|
|
113
|
-
const
|
|
114
|
-
|
|
113
|
+
const protocolInterrupts = rootInterruptsForTools;
|
|
114
|
+
const valuesInterrupts = Array.isArray(valuesBag?.__interrupt__) ? valuesBag.__interrupt__ : [];
|
|
115
|
+
const headlessInterrupts = protocolInterrupts.length > 0 ? protocolInterrupts : valuesInterrupts;
|
|
116
|
+
if (headlessInterrupts.length === 0) return;
|
|
115
117
|
(0, _langchain_langgraph_sdk.flushPendingHeadlessToolInterrupts)({
|
|
116
118
|
...valuesBag,
|
|
117
|
-
__interrupt__:
|
|
119
|
+
__interrupt__: headlessInterrupts
|
|
118
120
|
}, tools, handledToolsRef.current, {
|
|
119
121
|
onTool,
|
|
120
122
|
defer: (run) => {
|
package/dist/use-stream.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-stream.cjs","names":["ClientCtor","StreamController"],"sources":["../src/use-stream.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n filterOutHeadlessToolInterrupts,\n flushPendingHeadlessToolInterrupts,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Client as ClientCtor,\n type ClientConfig,\n type ThreadStream,\n} from \"@langchain/langgraph-sdk/client\";\nimport {\n StreamController,\n type AgentServerAdapter,\n type AgentServerOptions as StreamAgentServerOptions,\n type ChannelRegistry,\n type CustomAdapterOptions as StreamCustomAdapterOptions,\n type InferStateType,\n type InferSubagentStates,\n type InferToolCalls,\n type RootSnapshot,\n type RunCompletedInfo,\n type RunExecutionInfo,\n type StreamSubmitOptions,\n type SubagentDiscoverySnapshot,\n type SubagentMap,\n type SubgraphByNodeMap,\n type SubgraphDiscoverySnapshot,\n type SubgraphMap,\n type UseStreamOptions as StreamUseStreamOptions,\n type WidenUpdateMessages,\n} from \"@langchain/langgraph-sdk/stream\";\n\nexport type AgentServerOptions<StateType extends object> =\n StreamAgentServerOptions<StateType>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n StreamCustomAdapterOptions<StateType>;\n\nexport type UseStreamOptions<\n StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<StateType>;\n\n/**\n * Private field on the hook return that carries the\n * {@link StreamController} reference. Selector hooks (`useMessages`,\n * `useToolCalls`, …) read this to reach the shared\n * {@link ChannelRegistry}. Typed as a symbol-keyed field to discourage\n * end-user access — use the selector hooks instead.\n *\n * Exported as a unique symbol so type narrowing works across\n * `useMessages(stream, target)` call sites.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n \"@langchain/react/controller\"\n);\n\nexport interface UseStreamReturn<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n StateType extends object = InferStateType<T>,\n SubagentStates = InferSubagentStates<T>,\n> {\n // ----- always-on root projections -----\n /**\n * The most recent `values`-channel snapshot emitted at the root\n * namespace — i.e. the thread-level state as the server sees it\n * after each superstep. Updated on every root `values` event, not\n * on token-level deltas: if you render `values.messages` directly\n * you'll see full turns appear at once instead of streaming\n * token-by-token. Use {@link messages} (or `useMessages`) for the\n * token-streamed view.\n *\n * Equivalent to calling `useValues(stream)`.\n */\n readonly values: StateType;\n /**\n * Type-only: the resolved state shape. Exposed so consumers can\n * derive companion hook argument types (`useValues<typeof stream>`)\n * without plumbing `T` through their component hierarchy.\n *\n * @internal\n */\n readonly \"~stateType\"?: StateType;\n /**\n * The root message projection. Assembled from two sources and\n * merged in real time:\n *\n * 1. `messages`-channel deltas — token-level streaming events\n * (`message-start`, `content-block-delta`, `message-finish`)\n * emitted by the runtime. These drive live, token-by-token\n * updates.\n * 2. `values.messages` snapshots — the authoritative ordering\n * and any messages the agent produces without token streaming\n * (human turns, tool results, echoes from subagents).\n *\n * If the backend only emits `values` events (no `messages`\n * channel), every message will appear fully-formed on each\n * values update rather than streaming. This is a backend/runtime\n * concern — the React layer faithfully renders whatever the\n * server sends.\n *\n * Equivalent to calling `useMessages(stream)` with no target.\n */\n readonly messages: BaseMessage[];\n readonly toolCalls: InferToolCalls<T>[];\n readonly interrupts: Interrupt<InterruptType>[];\n readonly interrupt: Interrupt<InterruptType> | undefined;\n readonly isLoading: boolean;\n readonly isThreadLoading: boolean;\n /**\n * Promise that settles when the current thread's initial hydration\n * completes. Exposed so Suspense wrappers can `throw` it until the\n * first {@link StreamController.hydrate} call resolves (or rejects)\n * for the active thread. A fresh promise is installed on every\n * `switchThread`/`threadId` change.\n */\n readonly hydrationPromise: Promise<void>;\n readonly error: unknown;\n readonly threadId: string | null;\n\n // ----- always-on discovery -----\n /**\n * Subagents discovered on the root run. For DeepAgent-typed\n * streams the key set is narrowed to the subagent names declared\n * on the agent brand (`keyof InferSubagentStates<T>`).\n */\n readonly subagents: ReadonlyMap<\n keyof SubagentStates & string extends never\n ? string\n : keyof SubagentStates & string,\n SubagentDiscoverySnapshot\n >;\n /**\n * Subgraphs discovered on the root run.\n *\n * A namespace is classified as a subgraph iff at least one\n * strictly-deeper namespace has been observed with it as a prefix.\n * This is inferred from the lifecycle event stream — plain function\n * nodes (`orchestrator`, `writer` in the nested-stategraph example)\n * never appear here even though the server emits namespaced\n * lifecycle events for them. Promotion is monotonic and retroactive;\n * an entry appears as soon as the first descendant event lands.\n */\n readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n /**\n * Subgraphs indexed by the graph node that produced them\n * (`addNode(\"visualizer_0\", …)`). Each value is an array because\n * parallel fan-outs and loops can spawn multiple invocations of\n * the same node; arrays preserve insertion order. Updates in\n * lock-step with {@link subgraphs}.\n */\n readonly subgraphsByNode: ReadonlyMap<\n string,\n readonly SubgraphDiscoverySnapshot[]\n >;\n\n // ----- imperatives -----\n /**\n * Dispatch a new run on the bound thread.\n *\n * `input` is typed as `Partial<StateType>` so IDE autocompletion\n * surfaces the state keys declared on the root hook. Pass `null`\n * (or omit fields) when resuming an interrupt via `options.command.resume`\n * — the server accepts a null payload in that case.\n */\n submit(\n input: WidenUpdateMessages<Partial<StateType>> | null | undefined,\n options?: StreamSubmitOptions<StateType, ConfigurableType>\n ): Promise<void>;\n stop(): Promise<void>;\n respond(\n response: unknown,\n target?: { interruptId: string; namespace?: string[] }\n ): Promise<void>;\n\n // ----- identity -----\n readonly client: Client;\n readonly assistantId: string;\n\n /** v2 escape hatch — returns the bound {@link ThreadStream}. */\n getThread(): ThreadStream | undefined;\n\n /** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */\n readonly [STREAM_CONTROLLER]: StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >;\n}\n\n/**\n * Erased stream handle useful as a parameter type for helpers and\n * wrapper components that pass a `stream` through to selector hooks\n * (`useMessages`, `useChannel`, …) without reading `values` directly.\n * Any fully-typed `UseStreamReturn<S, I, C>` is\n * assignable to `AnyStream` because the generic slots are `any`\n * (bivariant), which avoids the `CompiledStateGraph` → `Record<string,\n * unknown>` assignment friction you hit when using the bare\n * `UseStreamReturn` default.\n *\n * @example\n * ```tsx\n * function SubgraphCard({ stream, subgraph }: {\n * stream: AnyStream;\n * subgraph: SubgraphDiscoverySnapshot;\n * }) {\n * const messages = useMessages(stream, subgraph);\n * return <Feed messages={messages} />;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * React binding for the v2-native stream runtime.\n *\n * `useStream` exposes three always-on projections\n * (`values` / `messages` / `toolCalls`) at the thread root plus\n * cheap discovery maps for subagents / subgraphs. Scoped views of\n * subagents, subgraphs, or any namespaced projection are surfaced via\n * the companion selector hooks:\n *\n * ```tsx\n * const stream = useStream({ assistantId: \"deep-agent\" });\n *\n * // Root messages — always on, already class instances.\n * stream.messages.map((m) => <Bubble key={m.id} msg={m} />);\n *\n * // Subagent view — mount = subscribe, unmount = unsubscribe.\n * function SubagentCard({ subagent }) {\n * const messages = useMessages(stream, subagent);\n * const toolCalls = useToolCalls(stream, subagent);\n * return <>{messages.map(...)}</>;\n * }\n * ```\n *\n * The first generic accepts either a plain state type\n * (`useStream<MyState>()`) *or* a compiled graph type\n * (`useStream<typeof agent>()`); in the latter case the\n * state shape is unwrapped from the graph via {@link InferStateType}, so\n * `stream.values` is always typed as the state, never as the graph\n * class itself.\n */\nexport function useStream<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n>(\n options: UseStreamOptions<InferStateType<T>>\n): UseStreamReturn<T, InterruptType, ConfigurableType> {\n type StateType = InferStateType<T>;\n // Branch-stable narrowings for each code path. The custom-adapter\n // branch can skip LGP client construction entirely, which keeps\n // bundles that *only* use a custom adapter free of the default\n // `sse`/`websocket` transport factories (tree-shaken).\n // Treat the options as a flat bag here — the discriminated union\n // exists to give call sites a nice error message, but at runtime\n // both branches are reachable through the same set of fields.\n interface OptionsBag {\n assistantId?: string;\n threadId?: string | null;\n client?: Client;\n apiUrl?: string;\n apiKey?: string;\n callerOptions?: ClientConfig[\"callerOptions\"];\n defaultHeaders?: ClientConfig[\"defaultHeaders\"];\n transport?: \"sse\" | \"websocket\" | AgentServerAdapter;\n fetch?: typeof fetch;\n webSocketFactory?: (url: string) => WebSocket;\n onThreadId?: (threadId: string) => void;\n onCreated?: (info: RunExecutionInfo) => void;\n onCompleted?: (info: RunCompletedInfo) => void;\n initialValues?: StateType;\n messagesKey?: string;\n }\n const asBag = options as OptionsBag;\n // Narrow once: a non-string `transport` is a custom adapter; anything\n // else (`\"sse\"` / `\"websocket\"` / `undefined`) is a built-in.\n const hasCustomAdapter =\n asBag.transport != null && typeof asBag.transport !== \"string\";\n const transport = asBag.transport;\n\n const client = useMemo<Client>(\n () =>\n asBag.client ??\n (new ClientCtor({\n apiUrl: asBag.apiUrl,\n apiKey: asBag.apiKey,\n callerOptions: asBag.callerOptions,\n defaultHeaders: asBag.defaultHeaders,\n }) as unknown as Client),\n [\n asBag.client,\n asBag.apiUrl,\n asBag.apiKey,\n asBag.callerOptions,\n asBag.defaultHeaders,\n ]\n );\n\n // Custom adapters may omit `assistantId`; the controller still\n // requires one so it has something to forward to `threads.stream`.\n // `\"_\"` is the well-known sentinel for \"adapter doesn't care\".\n const sentinel = \"_\";\n const assistantId =\n \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n // Recreate the controller only on assistantId / client / transport\n // change; the ThreadStream is bound to one assistant for its\n // lifetime and we want selector-hook subscriptions to stay stable\n // across renders.\n const controller = useMemo(\n () =>\n new StreamController<StateType, InterruptType, ConfigurableType>({\n assistantId,\n // Cast: the runtime `Client` is state-shape agnostic, but the\n // controller declares `client: Client<StateType>` so its own\n // typings line up. Tightening `submit`'s `input` parameter to\n // `Partial<StateType>` surfaced this variance mismatch that\n // was previously masked — the cast is equivalent to the\n // ClientCtor cast above.\n client: client as unknown as Client<StateType>,\n threadId: options.threadId ?? null,\n transport,\n fetch: hasCustomAdapter ? undefined : asBag.fetch,\n webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n onThreadId: options.onThreadId,\n onCreated: options.onCreated,\n onCompleted: options.onCompleted,\n initialValues: options.initialValues,\n messagesKey: options.messagesKey,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client, assistantId, transport]\n );\n\n // Rehydrate on threadId change. The initial hydrate is fired\n // synchronously inside the controller constructor so Suspense\n // callers don't deadlock waiting for an effect that never runs\n // (throwing `hydrationPromise` during render unmounts the subtree\n // before effects fire). We only re-hydrate here when the threadId\n // prop changes after the controller was already constructed with a\n // matching id.\n const lastHydratedRef = useRef<{\n controller: StreamController<StateType, InterruptType, ConfigurableType>;\n threadId: string | null;\n } | null>(null);\n useEffect(() => {\n const target = options.threadId ?? null;\n const last = lastHydratedRef.current;\n if (last?.controller !== controller) {\n // Freshly constructed controller already seeded the hydrate in\n // its constructor — record the id and skip the redundant call.\n lastHydratedRef.current = { controller, threadId: target };\n return;\n }\n if (last.threadId === target) return;\n lastHydratedRef.current = { controller, threadId: target };\n void controller.hydrate(target);\n }, [controller, options.threadId]);\n\n // Dispose on unmount / controller swap.\n //\n // We use `controller.activate()` instead of a naive\n // `() => controller.dispose()` cleanup because React 18+\n // `<StrictMode>` in dev mounts → unmounts → remounts components\n // synchronously to surface cleanup bugs. A naive cleanup would\n // permanently tear the controller down on that first synthetic\n // unmount and turn every subsequent `submit()` into a silent\n // no-op. `activate()` defers disposal to the next microtask and\n // cancels it if the effect re-runs — which is exactly the\n // StrictMode remount pattern.\n useEffect(() => controller.activate(), [controller]);\n\n // Headless-tool handling: if the caller supplied `tools`, watch the\n // root `values.__interrupt__` channel for protocol interrupts that\n // target a registered tool, invoke the handler, and auto-resume the\n // run. Ref-tracks the ids we've already handled so the same\n // interrupt on a subsequent render is never executed twice\n // (StrictMode safe).\n const handledToolsRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n handledToolsRef.current.clear();\n }, [options.threadId]);\n const tools = options.tools;\n const onTool = options.onTool;\n // Subscribe to values + interrupt updates via the root store so the\n // effect re-runs whenever a protocol interrupt lands or the\n // `__interrupt__` key is projected into values, not only on hook\n // re-render. We feed both sources to the flush helper because\n // v2-native runs surface protocol interrupts via\n // `rootStore.interrupts` (`input.requested` events), while legacy\n // graphs may still emit `values.__interrupt__`.\n const rootValuesForTools = useSyncExternalStore<StateType>(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().values,\n () => controller.rootStore.getSnapshot().values\n );\n const rootInterruptsForTools = useSyncExternalStore<\n readonly Interrupt<InterruptType>[]\n >(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().interrupts,\n () => controller.rootStore.getSnapshot().interrupts\n );\n useEffect(() => {\n if (!tools?.length) return;\n const valuesBag = rootValuesForTools as unknown as Record<string, unknown>;\n const existingInterrupts = Array.isArray(valuesBag?.__interrupt__)\n ? (valuesBag.__interrupt__ as Interrupt[])\n : [];\n const combined: Interrupt[] = [\n ...existingInterrupts,\n ...(rootInterruptsForTools as unknown as Interrupt[]),\n ];\n if (combined.length === 0) return;\n flushPendingHeadlessToolInterrupts(\n { ...valuesBag, __interrupt__: combined },\n tools,\n handledToolsRef.current,\n {\n onTool,\n defer: (run) => {\n void Promise.resolve().then(run);\n },\n resumeSubmit: (command) =>\n controller.submit(null, {\n command,\n } as StreamSubmitOptions<StateType, ConfigurableType>),\n }\n );\n }, [controller, tools, onTool, rootValuesForTools, rootInterruptsForTools]);\n\n const root = useSyncExternalStore<RootSnapshot<StateType, InterruptType>>(\n controller.rootStore.subscribe,\n controller.rootStore.getSnapshot,\n controller.rootStore.getSnapshot\n );\n const subagents = useSyncExternalStore<SubagentMap>(\n controller.subagentStore.subscribe,\n controller.subagentStore.getSnapshot,\n controller.subagentStore.getSnapshot\n );\n const subgraphs = useSyncExternalStore<SubgraphMap>(\n controller.subgraphStore.subscribe,\n controller.subgraphStore.getSnapshot,\n controller.subgraphStore.getSnapshot\n );\n const subgraphsByNode = useSyncExternalStore<SubgraphByNodeMap>(\n controller.subgraphByNodeStore.subscribe,\n controller.subgraphByNodeStore.getSnapshot,\n controller.subgraphByNodeStore.getSnapshot\n );\n\n return useMemo<UseStreamReturn<T, InterruptType, ConfigurableType>>(() => {\n const userFacingInterrupts = filterOutHeadlessToolInterrupts(\n root.interrupts\n );\n return {\n values: root.values,\n messages: root.messages,\n toolCalls: root.toolCalls as InferToolCalls<T>[],\n interrupts: userFacingInterrupts,\n interrupt: userFacingInterrupts[0],\n isLoading: root.isLoading,\n isThreadLoading: root.isThreadLoading,\n hydrationPromise: controller.hydrationPromise,\n error: root.error,\n threadId: root.threadId,\n subagents: subagents as UseStreamReturn<\n T,\n InterruptType,\n ConfigurableType\n >[\"subagents\"],\n subgraphs,\n subgraphsByNode,\n submit: (input, submitOptions) => controller.submit(input, submitOptions),\n stop: () => controller.stop(),\n respond: (response, target) => controller.respond(response, target),\n getThread: () => controller.getThread(),\n client,\n assistantId,\n [STREAM_CONTROLLER]: controller,\n } as UseStreamReturn<T, InterruptType, ConfigurableType>;\n }, [\n root,\n subagents,\n subgraphs,\n subgraphsByNode,\n controller,\n client,\n assistantId,\n ]);\n}\n\n/**\n * Convenience alias for the fully-resolved stream handle type.\n */\nexport type UseStreamResult<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n> = UseStreamReturn<T, InterruptType, ConfigurableType>;\n\n/**\n * Helper used by the selector hooks to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\n * instead of reading this directly.\n *\n * @internal\n */\nexport function getRegistry(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stream: UseStreamReturn<any, any, any>\n): ChannelRegistry {\n return stream[STREAM_CONTROLLER].registry;\n}\n\nexport type { ThreadStream };\n"],"mappings":";;;;;;;;;;;;;;;;AA0DA,MAAa,oBAAmC,OAAO,IACrD,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+LD,SAAgB,UAKd,SACqD;CA0BrD,MAAM,QAAQ;CAGd,MAAM,mBACJ,MAAM,aAAa,QAAQ,OAAO,MAAM,cAAc;CACxD,MAAM,YAAY,MAAM;CAExB,M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K;GACf,WAAW,KAAK;GAChB,YAAY;GACZ,WAAW,qBAAqB;GAChC,WAAW,KAAK;GAChB,iBAAiB,KAAK;GACtB,kBAAkB,WAAW;GAC7B,OAAO,KAAK;GACZ,UAAU,KAAK;GACJ;GAKX;GACA;GACA,SAAS,OAAO,kBAAkB,WAAW,OAAO,OAAO,cAAc;GACzE,YAAY,WAAW,MAAM;GAC7B,UAAU,UAAU,WAAW,WAAW,QAAQ,UAAU,OAAO;GACnE,iBAAiB,WAAW,WAAW;GACvC;GACA;IACC,oBAAoB;GACtB;IACA;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;;;;;;;;;;AAoBJ,SAAgB,YAEd,QACiB;AACjB,QAAO,OAAO,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"use-stream.cjs","names":["ClientCtor","StreamController"],"sources":["../src/use-stream.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n filterOutHeadlessToolInterrupts,\n flushPendingHeadlessToolInterrupts,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Client as ClientCtor,\n type ClientConfig,\n type ThreadStream,\n} from \"@langchain/langgraph-sdk/client\";\nimport {\n StreamController,\n type AgentServerAdapter,\n type AgentServerOptions as StreamAgentServerOptions,\n type ChannelRegistry,\n type CustomAdapterOptions as StreamCustomAdapterOptions,\n type InferStateType,\n type InferSubagentStates,\n type InferToolCalls,\n type RootSnapshot,\n type RunCompletedInfo,\n type RunExecutionInfo,\n type StreamSubmitOptions,\n type SubagentDiscoverySnapshot,\n type SubagentMap,\n type SubgraphByNodeMap,\n type SubgraphDiscoverySnapshot,\n type SubgraphMap,\n type UseStreamOptions as StreamUseStreamOptions,\n type WidenUpdateMessages,\n} from \"@langchain/langgraph-sdk/stream\";\n\nexport type AgentServerOptions<StateType extends object> =\n StreamAgentServerOptions<StateType>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n StreamCustomAdapterOptions<StateType>;\n\nexport type UseStreamOptions<\n StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<StateType>;\n\n/**\n * Private field on the hook return that carries the\n * {@link StreamController} reference. Selector hooks (`useMessages`,\n * `useToolCalls`, …) read this to reach the shared\n * {@link ChannelRegistry}. Typed as a symbol-keyed field to discourage\n * end-user access — use the selector hooks instead.\n *\n * Exported as a unique symbol so type narrowing works across\n * `useMessages(stream, target)` call sites.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n \"@langchain/react/controller\"\n);\n\nexport interface UseStreamReturn<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n StateType extends object = InferStateType<T>,\n SubagentStates = InferSubagentStates<T>,\n> {\n // ----- always-on root projections -----\n /**\n * The most recent `values`-channel snapshot emitted at the root\n * namespace — i.e. the thread-level state as the server sees it\n * after each superstep. Updated on every root `values` event, not\n * on token-level deltas: if you render `values.messages` directly\n * you'll see full turns appear at once instead of streaming\n * token-by-token. Use {@link messages} (or `useMessages`) for the\n * token-streamed view.\n *\n * Equivalent to calling `useValues(stream)`.\n */\n readonly values: StateType;\n /**\n * Type-only: the resolved state shape. Exposed so consumers can\n * derive companion hook argument types (`useValues<typeof stream>`)\n * without plumbing `T` through their component hierarchy.\n *\n * @internal\n */\n readonly \"~stateType\"?: StateType;\n /**\n * The root message projection. Assembled from two sources and\n * merged in real time:\n *\n * 1. `messages`-channel deltas — token-level streaming events\n * (`message-start`, `content-block-delta`, `message-finish`)\n * emitted by the runtime. These drive live, token-by-token\n * updates.\n * 2. `values.messages` snapshots — the authoritative ordering\n * and any messages the agent produces without token streaming\n * (human turns, tool results, echoes from subagents).\n *\n * If the backend only emits `values` events (no `messages`\n * channel), every message will appear fully-formed on each\n * values update rather than streaming. This is a backend/runtime\n * concern — the React layer faithfully renders whatever the\n * server sends.\n *\n * Equivalent to calling `useMessages(stream)` with no target.\n */\n readonly messages: BaseMessage[];\n /**\n * Root-namespace tool calls assembled from the `tools` channel.\n * Each entry is a fully parsed {@link AssembledToolCall} with\n * name, args, and id — suitable for rendering approval UIs or\n * forwarding to headless tool handlers.\n *\n * When the stream is typed with an agent brand or tool list,\n * entries are narrowed via {@link InferToolCalls}. Equivalent to\n * calling `useToolCalls(stream)` with no target.\n */\n readonly toolCalls: InferToolCalls<T>[];\n /**\n * All unresolved protocol interrupts observed on the root\n * namespace during the active thread. Populated from lifecycle /\n * input events and seeded on hydration from `thread.getState()`.\n * Cleared optimistically when a new run starts or an interrupt is\n * resolved via {@link respond} / `submit({ command: { resume } })`.\n */\n readonly interrupts: Interrupt<InterruptType>[];\n /**\n * Convenience alias for {@link interrupts}[0] — the primary\n * interrupt most UIs should act on when only one is pending.\n * `undefined` when no interrupt is active.\n */\n readonly interrupt: Interrupt<InterruptType> | undefined;\n /**\n * `true` while a run is active or being started on the current\n * thread. Driven by root-namespace lifecycle events (`running` →\n * `true`, terminal phases → `false`). Use this to disable submit\n * buttons and show in-flight spinners.\n */\n readonly isLoading: boolean;\n /**\n * `true` while the initial `thread.getState()` hydration for the\n * active thread is in flight. Distinct from {@link isLoading} —\n * thread loading covers the one-time fetch that seeds\n * {@link values} / {@link messages} before any user submit.\n */\n readonly isThreadLoading: boolean;\n /**\n * Promise that settles when the current thread's initial hydration\n * completes. Exposed so Suspense wrappers can `throw` it until the\n * first {@link StreamController.hydrate} call resolves (or rejects)\n * for the active thread. A fresh promise is installed on every\n * `switchThread`/`threadId` change.\n */\n readonly hydrationPromise: Promise<void>;\n /**\n * The last error observed on the active run or hydration attempt.\n * `undefined` when no error has occurred. Cleared optimistically\n * when a new {@link submit} starts.\n */\n readonly error: unknown;\n /**\n * Id of the thread the controller is bound to. `null` until the\n * first {@link submit} creates or selects a thread (or until an\n * explicit `threadId` option is provided and hydrated).\n */\n readonly threadId: string | null;\n\n // ----- always-on discovery -----\n /**\n * Subagents discovered on the root run. For DeepAgent-typed\n * streams the key set is narrowed to the subagent names declared\n * on the agent brand (`keyof InferSubagentStates<T>`).\n */\n readonly subagents: ReadonlyMap<\n keyof SubagentStates & string extends never\n ? string\n : keyof SubagentStates & string,\n SubagentDiscoverySnapshot\n >;\n /**\n * Subgraphs discovered on the root run.\n *\n * A namespace is classified as a subgraph iff at least one\n * strictly-deeper namespace has been observed with it as a prefix.\n * This is inferred from the lifecycle event stream — plain function\n * nodes (`orchestrator`, `writer` in the nested-stategraph example)\n * never appear here even though the server emits namespaced\n * lifecycle events for them. Promotion is monotonic and retroactive;\n * an entry appears as soon as the first descendant event lands.\n */\n readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n /**\n * Subgraphs indexed by the graph node that produced them\n * (`addNode(\"visualizer_0\", …)`). Each value is an array because\n * parallel fan-outs and loops can spawn multiple invocations of\n * the same node; arrays preserve insertion order. Updates in\n * lock-step with {@link subgraphs}.\n */\n readonly subgraphsByNode: ReadonlyMap<\n string,\n readonly SubgraphDiscoverySnapshot[]\n >;\n\n // ----- imperatives -----\n /**\n * Dispatch a new run on the bound thread.\n *\n * `input` is typed as `Partial<StateType>` so IDE autocompletion\n * surfaces the state keys declared on the root hook. Pass `null`\n * (or omit fields) when resuming an interrupt via `options.command.resume`\n * — the server accepts a null payload in that case.\n */\n submit(\n input: WidenUpdateMessages<Partial<StateType>> | null | undefined,\n options?: StreamSubmitOptions<StateType, ConfigurableType>\n ): Promise<void>;\n /**\n * Abort the in-flight run on the current thread without clearing\n * accumulated state. Sets {@link isLoading} to `false` immediately;\n * {@link values} and {@link messages} are preserved.\n */\n stop(): Promise<void>;\n /**\n * Resume a pending protocol interrupt by sending a response payload\n * back to the interrupted namespace.\n *\n * When `target` is omitted, responds to the latest unresolved\n * interrupt in {@link interrupts}. Pass an explicit\n * `{ interruptId, namespace? }` when multiple interrupts are\n * pending or the interrupt lives in a subgraph namespace.\n */\n respond(\n response: unknown,\n target?: { interruptId: string; namespace?: string[] }\n ): Promise<void>;\n\n // ----- identity -----\n /** LangGraph SDK client used to construct thread streams. */\n readonly client: Client;\n /** Assistant id the thread is bound to for its lifetime. */\n readonly assistantId: string;\n\n /**\n * Returns the bound {@link ThreadStream}, if one exists (`undefined`\n * until the thread is hydrated or the first submit completes). Prefer\n * the projections and selector hooks for UI work; use this for\n * low-level protocol access (raw subscriptions, state commands, etc.).\n */\n getThread(): ThreadStream | undefined;\n\n /** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */\n readonly [STREAM_CONTROLLER]: StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >;\n}\n\n/**\n * Erased stream handle useful as a parameter type for helpers and\n * wrapper components that pass a `stream` through to selector hooks\n * (`useMessages`, `useChannel`, …) without reading `values` directly.\n * Any fully-typed `UseStreamReturn<S, I, C>` is\n * assignable to `AnyStream` because the generic slots are `any`\n * (bivariant), which avoids the `CompiledStateGraph` → `Record<string,\n * unknown>` assignment friction you hit when using the bare\n * `UseStreamReturn` default.\n *\n * @example\n * ```tsx\n * function SubgraphCard({ stream, subgraph }: {\n * stream: AnyStream;\n * subgraph: SubgraphDiscoverySnapshot;\n * }) {\n * const messages = useMessages(stream, subgraph);\n * return <Feed messages={messages} />;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * React binding for the v2-native stream runtime.\n *\n * `useStream` exposes three always-on projections\n * (`values` / `messages` / `toolCalls`) at the thread root plus\n * cheap discovery maps for subagents / subgraphs. Scoped views of\n * subagents, subgraphs, or any namespaced projection are surfaced via\n * the companion selector hooks:\n *\n * ```tsx\n * const stream = useStream({ assistantId: \"deep-agent\" });\n *\n * // Root messages — always on, already class instances.\n * stream.messages.map((m) => <Bubble key={m.id} msg={m} />);\n *\n * // Subagent view — mount = subscribe, unmount = unsubscribe.\n * function SubagentCard({ subagent }) {\n * const messages = useMessages(stream, subagent);\n * const toolCalls = useToolCalls(stream, subagent);\n * return <>{messages.map(...)}</>;\n * }\n * ```\n *\n * The first generic accepts either a plain state type\n * (`useStream<MyState>()`) *or* a compiled graph type\n * (`useStream<typeof agent>()`); in the latter case the\n * state shape is unwrapped from the graph via {@link InferStateType}, so\n * `stream.values` is always typed as the state, never as the graph\n * class itself.\n */\nexport function useStream<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n>(\n options: UseStreamOptions<InferStateType<T>>\n): UseStreamReturn<T, InterruptType, ConfigurableType> {\n type StateType = InferStateType<T>;\n // Branch-stable narrowings for each code path. The custom-adapter\n // branch can skip LGP client construction entirely, which keeps\n // bundles that *only* use a custom adapter free of the default\n // `sse`/`websocket` transport factories (tree-shaken).\n // Treat the options as a flat bag here — the discriminated union\n // exists to give call sites a nice error message, but at runtime\n // both branches are reachable through the same set of fields.\n interface OptionsBag {\n assistantId?: string;\n threadId?: string | null;\n client?: Client;\n apiUrl?: string;\n apiKey?: string;\n callerOptions?: ClientConfig[\"callerOptions\"];\n defaultHeaders?: ClientConfig[\"defaultHeaders\"];\n transport?: \"sse\" | \"websocket\" | AgentServerAdapter;\n fetch?: typeof fetch;\n webSocketFactory?: (url: string) => WebSocket;\n onThreadId?: (threadId: string) => void;\n onCreated?: (info: RunExecutionInfo) => void;\n onCompleted?: (info: RunCompletedInfo) => void;\n initialValues?: StateType;\n messagesKey?: string;\n }\n const asBag = options as OptionsBag;\n // Narrow once: a non-string `transport` is a custom adapter; anything\n // else (`\"sse\"` / `\"websocket\"` / `undefined`) is a built-in.\n const hasCustomAdapter =\n asBag.transport != null && typeof asBag.transport !== \"string\";\n const transport = asBag.transport;\n\n const client = useMemo<Client>(\n () =>\n asBag.client ??\n (new ClientCtor({\n apiUrl: asBag.apiUrl,\n apiKey: asBag.apiKey,\n callerOptions: asBag.callerOptions,\n defaultHeaders: asBag.defaultHeaders,\n }) as unknown as Client),\n [\n asBag.client,\n asBag.apiUrl,\n asBag.apiKey,\n asBag.callerOptions,\n asBag.defaultHeaders,\n ]\n );\n\n // Custom adapters may omit `assistantId`; the controller still\n // requires one so it has something to forward to `threads.stream`.\n // `\"_\"` is the well-known sentinel for \"adapter doesn't care\".\n const sentinel = \"_\";\n const assistantId =\n \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n // Recreate the controller only on assistantId / client / transport\n // change; the ThreadStream is bound to one assistant for its\n // lifetime and we want selector-hook subscriptions to stay stable\n // across renders.\n const controller = useMemo(\n () =>\n new StreamController<StateType, InterruptType, ConfigurableType>({\n assistantId,\n // Cast: the runtime `Client` is state-shape agnostic, but the\n // controller declares `client: Client<StateType>` so its own\n // typings line up. Tightening `submit`'s `input` parameter to\n // `Partial<StateType>` surfaced this variance mismatch that\n // was previously masked — the cast is equivalent to the\n // ClientCtor cast above.\n client: client as unknown as Client<StateType>,\n threadId: options.threadId ?? null,\n transport,\n fetch: hasCustomAdapter ? undefined : asBag.fetch,\n webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n onThreadId: options.onThreadId,\n onCreated: options.onCreated,\n onCompleted: options.onCompleted,\n initialValues: options.initialValues,\n messagesKey: options.messagesKey,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client, assistantId, transport]\n );\n\n // Rehydrate on threadId change. The initial hydrate is fired\n // synchronously inside the controller constructor so Suspense\n // callers don't deadlock waiting for an effect that never runs\n // (throwing `hydrationPromise` during render unmounts the subtree\n // before effects fire). We only re-hydrate here when the threadId\n // prop changes after the controller was already constructed with a\n // matching id.\n const lastHydratedRef = useRef<{\n controller: StreamController<StateType, InterruptType, ConfigurableType>;\n threadId: string | null;\n } | null>(null);\n useEffect(() => {\n const target = options.threadId ?? null;\n const last = lastHydratedRef.current;\n if (last?.controller !== controller) {\n // Freshly constructed controller already seeded the hydrate in\n // its constructor — record the id and skip the redundant call.\n lastHydratedRef.current = { controller, threadId: target };\n return;\n }\n if (last.threadId === target) return;\n lastHydratedRef.current = { controller, threadId: target };\n void controller.hydrate(target);\n }, [controller, options.threadId]);\n\n // Dispose on unmount / controller swap.\n //\n // We use `controller.activate()` instead of a naive\n // `() => controller.dispose()` cleanup because React 18+\n // `<StrictMode>` in dev mounts → unmounts → remounts components\n // synchronously to surface cleanup bugs. A naive cleanup would\n // permanently tear the controller down on that first synthetic\n // unmount and turn every subsequent `submit()` into a silent\n // no-op. `activate()` defers disposal to the next microtask and\n // cancels it if the effect re-runs — which is exactly the\n // StrictMode remount pattern.\n useEffect(() => controller.activate(), [controller]);\n\n // Headless-tool handling: if the caller supplied `tools`, watch the\n // root `values.__interrupt__` channel for protocol interrupts that\n // target a registered tool, invoke the handler, and auto-resume the\n // run. Ref-tracks the ids we've already handled so the same\n // interrupt on a subsequent render is never executed twice\n // (StrictMode safe).\n const handledToolsRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n handledToolsRef.current.clear();\n }, [options.threadId]);\n const tools = options.tools;\n const onTool = options.onTool;\n // Subscribe to values + interrupt updates via the root store so the\n // effect re-runs whenever a protocol interrupt lands or the\n // `__interrupt__` key is projected into values, not only on hook\n // re-render. Prefer protocol interrupts from `rootStore.interrupts`\n // (`input.requested` events) because their ids are accepted directly\n // by `Command({ resume })`; fall back to `values.__interrupt__` for\n // older streams that only expose interrupts through values.\n const rootValuesForTools = useSyncExternalStore<StateType>(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().values,\n () => controller.rootStore.getSnapshot().values\n );\n const rootInterruptsForTools = useSyncExternalStore<\n readonly Interrupt<InterruptType>[]\n >(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().interrupts,\n () => controller.rootStore.getSnapshot().interrupts\n );\n useEffect(() => {\n if (!tools?.length) return;\n const valuesBag = rootValuesForTools as unknown as Record<string, unknown>;\n const protocolInterrupts = rootInterruptsForTools as unknown as Interrupt[];\n const valuesInterrupts = Array.isArray(valuesBag?.__interrupt__)\n ? (valuesBag.__interrupt__ as Interrupt[])\n : [];\n const headlessInterrupts =\n protocolInterrupts.length > 0 ? protocolInterrupts : valuesInterrupts;\n if (headlessInterrupts.length === 0) return;\n flushPendingHeadlessToolInterrupts(\n { ...valuesBag, __interrupt__: headlessInterrupts },\n tools,\n handledToolsRef.current,\n {\n onTool,\n defer: (run) => {\n void Promise.resolve().then(run);\n },\n resumeSubmit: (command) =>\n controller.submit(null, {\n command,\n } as StreamSubmitOptions<StateType, ConfigurableType>),\n }\n );\n }, [controller, tools, onTool, rootValuesForTools, rootInterruptsForTools]);\n\n const root = useSyncExternalStore<RootSnapshot<StateType, InterruptType>>(\n controller.rootStore.subscribe,\n controller.rootStore.getSnapshot,\n controller.rootStore.getSnapshot\n );\n const subagents = useSyncExternalStore<SubagentMap>(\n controller.subagentStore.subscribe,\n controller.subagentStore.getSnapshot,\n controller.subagentStore.getSnapshot\n );\n const subgraphs = useSyncExternalStore<SubgraphMap>(\n controller.subgraphStore.subscribe,\n controller.subgraphStore.getSnapshot,\n controller.subgraphStore.getSnapshot\n );\n const subgraphsByNode = useSyncExternalStore<SubgraphByNodeMap>(\n controller.subgraphByNodeStore.subscribe,\n controller.subgraphByNodeStore.getSnapshot,\n controller.subgraphByNodeStore.getSnapshot\n );\n\n return useMemo<UseStreamReturn<T, InterruptType, ConfigurableType>>(() => {\n const userFacingInterrupts = filterOutHeadlessToolInterrupts(\n root.interrupts\n );\n return {\n values: root.values,\n messages: root.messages,\n toolCalls: root.toolCalls as InferToolCalls<T>[],\n interrupts: userFacingInterrupts,\n interrupt: userFacingInterrupts[0],\n isLoading: root.isLoading,\n isThreadLoading: root.isThreadLoading,\n hydrationPromise: controller.hydrationPromise,\n error: root.error,\n threadId: root.threadId,\n subagents: subagents as UseStreamReturn<\n T,\n InterruptType,\n ConfigurableType\n >[\"subagents\"],\n subgraphs,\n subgraphsByNode,\n submit: (input, submitOptions) => controller.submit(input, submitOptions),\n stop: () => controller.stop(),\n respond: (response, target) => controller.respond(response, target),\n getThread: () => controller.getThread(),\n client,\n assistantId,\n [STREAM_CONTROLLER]: controller,\n } as UseStreamReturn<T, InterruptType, ConfigurableType>;\n }, [\n root,\n subagents,\n subgraphs,\n subgraphsByNode,\n controller,\n client,\n assistantId,\n ]);\n}\n\n/**\n * Convenience alias for the fully-resolved stream handle type.\n */\nexport type UseStreamResult<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n> = UseStreamReturn<T, InterruptType, ConfigurableType>;\n\n/**\n * Helper used by the selector hooks to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\n * instead of reading this directly.\n *\n * @internal\n */\nexport function getRegistry(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stream: UseStreamReturn<any, any, any>\n): ChannelRegistry {\n return stream[STREAM_CONTROLLER].registry;\n}\n\nexport type { ThreadStream };\n"],"mappings":";;;;;;;;;;;;;;;;AA0DA,MAAa,oBAAmC,OAAO,IACrD,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQD,SAAgB,UAKd,SACqD;CA0BrD,MAAM,QAAQ;CAGd,MAAM,mBACJ,MAAM,aAAa,QAAQ,OAAO,MAAM,cAAc;CACxD,MAAM,YAAY,MAAM;CAExB,MAAM,UAAA,GAAA,MAAA,eAEF,MAAM,UACL,IAAIA,gCAAAA,OAAW;EACd,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,eAAe,MAAM;EACrB,gBAAgB,MAAM;EACvB,CAAC,EACJ;EACE,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACP,CACF;CAKD,MAAM,WAAW;CACjB,MAAM,cACJ,iBAAiB,UAAW,QAAQ,eAAe,WAAY;CAMjE,MAAM,cAAA,GAAA,MAAA,eAEF,IAAIC,gCAAAA,iBAA6D;EAC/D;EAOQ;EACR,UAAU,QAAQ,YAAY;EAC9B;EACA,OAAO,mBAAmB,KAAA,IAAY,MAAM;EA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;;;;;;;;;AAoBJ,SAAgB,YAEd,QACiB;AACjB,QAAO,OAAO,mBAAmB"}
|
package/dist/use-stream.d.cts
CHANGED
|
@@ -60,10 +60,44 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
60
60
|
* Equivalent to calling `useMessages(stream)` with no target.
|
|
61
61
|
*/
|
|
62
62
|
readonly messages: BaseMessage[];
|
|
63
|
+
/**
|
|
64
|
+
* Root-namespace tool calls assembled from the `tools` channel.
|
|
65
|
+
* Each entry is a fully parsed {@link AssembledToolCall} with
|
|
66
|
+
* name, args, and id — suitable for rendering approval UIs or
|
|
67
|
+
* forwarding to headless tool handlers.
|
|
68
|
+
*
|
|
69
|
+
* When the stream is typed with an agent brand or tool list,
|
|
70
|
+
* entries are narrowed via {@link InferToolCalls}. Equivalent to
|
|
71
|
+
* calling `useToolCalls(stream)` with no target.
|
|
72
|
+
*/
|
|
63
73
|
readonly toolCalls: InferToolCalls<T>[];
|
|
74
|
+
/**
|
|
75
|
+
* All unresolved protocol interrupts observed on the root
|
|
76
|
+
* namespace during the active thread. Populated from lifecycle /
|
|
77
|
+
* input events and seeded on hydration from `thread.getState()`.
|
|
78
|
+
* Cleared optimistically when a new run starts or an interrupt is
|
|
79
|
+
* resolved via {@link respond} / `submit({ command: { resume } })`.
|
|
80
|
+
*/
|
|
64
81
|
readonly interrupts: Interrupt<InterruptType>[];
|
|
82
|
+
/**
|
|
83
|
+
* Convenience alias for {@link interrupts}[0] — the primary
|
|
84
|
+
* interrupt most UIs should act on when only one is pending.
|
|
85
|
+
* `undefined` when no interrupt is active.
|
|
86
|
+
*/
|
|
65
87
|
readonly interrupt: Interrupt<InterruptType> | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* `true` while a run is active or being started on the current
|
|
90
|
+
* thread. Driven by root-namespace lifecycle events (`running` →
|
|
91
|
+
* `true`, terminal phases → `false`). Use this to disable submit
|
|
92
|
+
* buttons and show in-flight spinners.
|
|
93
|
+
*/
|
|
66
94
|
readonly isLoading: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* `true` while the initial `thread.getState()` hydration for the
|
|
97
|
+
* active thread is in flight. Distinct from {@link isLoading} —
|
|
98
|
+
* thread loading covers the one-time fetch that seeds
|
|
99
|
+
* {@link values} / {@link messages} before any user submit.
|
|
100
|
+
*/
|
|
67
101
|
readonly isThreadLoading: boolean;
|
|
68
102
|
/**
|
|
69
103
|
* Promise that settles when the current thread's initial hydration
|
|
@@ -73,7 +107,17 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
73
107
|
* `switchThread`/`threadId` change.
|
|
74
108
|
*/
|
|
75
109
|
readonly hydrationPromise: Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* The last error observed on the active run or hydration attempt.
|
|
112
|
+
* `undefined` when no error has occurred. Cleared optimistically
|
|
113
|
+
* when a new {@link submit} starts.
|
|
114
|
+
*/
|
|
76
115
|
readonly error: unknown;
|
|
116
|
+
/**
|
|
117
|
+
* Id of the thread the controller is bound to. `null` until the
|
|
118
|
+
* first {@link submit} creates or selects a thread (or until an
|
|
119
|
+
* explicit `threadId` option is provided and hydrated).
|
|
120
|
+
*/
|
|
77
121
|
readonly threadId: string | null;
|
|
78
122
|
/**
|
|
79
123
|
* Subagents discovered on the root run. For DeepAgent-typed
|
|
@@ -110,14 +154,35 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
110
154
|
* — the server accepts a null payload in that case.
|
|
111
155
|
*/
|
|
112
156
|
submit(input: WidenUpdateMessages<Partial<StateType>> | null | undefined, options?: StreamSubmitOptions<StateType, ConfigurableType>): Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Abort the in-flight run on the current thread without clearing
|
|
159
|
+
* accumulated state. Sets {@link isLoading} to `false` immediately;
|
|
160
|
+
* {@link values} and {@link messages} are preserved.
|
|
161
|
+
*/
|
|
113
162
|
stop(): Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* Resume a pending protocol interrupt by sending a response payload
|
|
165
|
+
* back to the interrupted namespace.
|
|
166
|
+
*
|
|
167
|
+
* When `target` is omitted, responds to the latest unresolved
|
|
168
|
+
* interrupt in {@link interrupts}. Pass an explicit
|
|
169
|
+
* `{ interruptId, namespace? }` when multiple interrupts are
|
|
170
|
+
* pending or the interrupt lives in a subgraph namespace.
|
|
171
|
+
*/
|
|
114
172
|
respond(response: unknown, target?: {
|
|
115
173
|
interruptId: string;
|
|
116
174
|
namespace?: string[];
|
|
117
175
|
}): Promise<void>;
|
|
176
|
+
/** LangGraph SDK client used to construct thread streams. */
|
|
118
177
|
readonly client: Client;
|
|
178
|
+
/** Assistant id the thread is bound to for its lifetime. */
|
|
119
179
|
readonly assistantId: string;
|
|
120
|
-
/**
|
|
180
|
+
/**
|
|
181
|
+
* Returns the bound {@link ThreadStream}, if one exists (`undefined`
|
|
182
|
+
* until the thread is hydrated or the first submit completes). Prefer
|
|
183
|
+
* the projections and selector hooks for UI work; use this for
|
|
184
|
+
* low-level protocol access (raw subscriptions, state commands, etc.).
|
|
185
|
+
*/
|
|
121
186
|
getThread(): ThreadStream | undefined;
|
|
122
187
|
/** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */
|
|
123
188
|
readonly [STREAM_CONTROLLER]: StreamController<StateType, InterruptType, ConfigurableType>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-stream.d.cts","names":[],"sources":["../src/use-stream.ts"],"mappings":";;;;;;KAsCY,oBAAA,6BACV,kBAAA,CAAyB,SAAA;AAAA,KAEf,sBAAA,6BACV,oBAAA,CAA2B,SAAA;AAAA,KAEjB,kBAAA,4BACiB,MAAA,qBACzB,gBAAA,CAAuB,SAAA;;;;;;;;;AAL3B;;cAiBa,iBAAA;AAAA,UAII,eAAA,KACX,MAAA,8EAE8B,MAAA,8CACP,cAAA,CAAe,CAAA,oBACzB,mBAAA,CAAoB,CAAA;EA1BN;;;;;AAGjC;;;;;;EAHiC,SAwCtB,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;;;;EArBb,MAAA,CACE,KAAA,EAAO,mBAAA,CAAoB,OAAA,CAAQ,SAAA,uBACnC,OAAA,GAAU,mBAAA,CAAoB,SAAA,EAAW,gBAAA,IACxC,OAAA;EAoCO;;;;;EA9BV,IAAA,IAAQ,OAAA;EAiCU;AA0BpB;;;;;AAgCA;;;EAjFE,OAAA,CACE,QAAA,WACA,MAAA;IAAW,WAAA;IAAqB,SAAA;EAAA,IAC/B,OAAA;EAmFM;EAAA,SA/EA,MAAA,EAAQ,MAAA;EAgFG;EAAA,SA9EX,WAAA;EA8ER;;;;;;EAtED,SAAA,IAAa,YAAA;EAmEqB;EAAA,UAhExB,iBAAA,GAAoB,gBAAA,CAC5B,SAAA,EACA,aAAA,EACA,gBAAA;AAAA;;;;;;;;;AAwTJ;;;;;;;;;;;;;KA9RY,SAAA,GAAY,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCR,SAAA,KACV,MAAA,8EAE8B,MAAA,kBAAA,CAElC,OAAA,EAAS,kBAAA,CAAiB,cAAA,CAAe,CAAA,KACxC,eAAA,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA;;;;KAwPzB,eAAA,KACN,MAAA,8EAE8B,MAAA,qBAChC,eAAA,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA"}
|
package/dist/use-stream.d.ts
CHANGED
|
@@ -60,10 +60,44 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
60
60
|
* Equivalent to calling `useMessages(stream)` with no target.
|
|
61
61
|
*/
|
|
62
62
|
readonly messages: BaseMessage[];
|
|
63
|
+
/**
|
|
64
|
+
* Root-namespace tool calls assembled from the `tools` channel.
|
|
65
|
+
* Each entry is a fully parsed {@link AssembledToolCall} with
|
|
66
|
+
* name, args, and id — suitable for rendering approval UIs or
|
|
67
|
+
* forwarding to headless tool handlers.
|
|
68
|
+
*
|
|
69
|
+
* When the stream is typed with an agent brand or tool list,
|
|
70
|
+
* entries are narrowed via {@link InferToolCalls}. Equivalent to
|
|
71
|
+
* calling `useToolCalls(stream)` with no target.
|
|
72
|
+
*/
|
|
63
73
|
readonly toolCalls: InferToolCalls<T>[];
|
|
74
|
+
/**
|
|
75
|
+
* All unresolved protocol interrupts observed on the root
|
|
76
|
+
* namespace during the active thread. Populated from lifecycle /
|
|
77
|
+
* input events and seeded on hydration from `thread.getState()`.
|
|
78
|
+
* Cleared optimistically when a new run starts or an interrupt is
|
|
79
|
+
* resolved via {@link respond} / `submit({ command: { resume } })`.
|
|
80
|
+
*/
|
|
64
81
|
readonly interrupts: Interrupt<InterruptType>[];
|
|
82
|
+
/**
|
|
83
|
+
* Convenience alias for {@link interrupts}[0] — the primary
|
|
84
|
+
* interrupt most UIs should act on when only one is pending.
|
|
85
|
+
* `undefined` when no interrupt is active.
|
|
86
|
+
*/
|
|
65
87
|
readonly interrupt: Interrupt<InterruptType> | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* `true` while a run is active or being started on the current
|
|
90
|
+
* thread. Driven by root-namespace lifecycle events (`running` →
|
|
91
|
+
* `true`, terminal phases → `false`). Use this to disable submit
|
|
92
|
+
* buttons and show in-flight spinners.
|
|
93
|
+
*/
|
|
66
94
|
readonly isLoading: boolean;
|
|
95
|
+
/**
|
|
96
|
+
* `true` while the initial `thread.getState()` hydration for the
|
|
97
|
+
* active thread is in flight. Distinct from {@link isLoading} —
|
|
98
|
+
* thread loading covers the one-time fetch that seeds
|
|
99
|
+
* {@link values} / {@link messages} before any user submit.
|
|
100
|
+
*/
|
|
67
101
|
readonly isThreadLoading: boolean;
|
|
68
102
|
/**
|
|
69
103
|
* Promise that settles when the current thread's initial hydration
|
|
@@ -73,7 +107,17 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
73
107
|
* `switchThread`/`threadId` change.
|
|
74
108
|
*/
|
|
75
109
|
readonly hydrationPromise: Promise<void>;
|
|
110
|
+
/**
|
|
111
|
+
* The last error observed on the active run or hydration attempt.
|
|
112
|
+
* `undefined` when no error has occurred. Cleared optimistically
|
|
113
|
+
* when a new {@link submit} starts.
|
|
114
|
+
*/
|
|
76
115
|
readonly error: unknown;
|
|
116
|
+
/**
|
|
117
|
+
* Id of the thread the controller is bound to. `null` until the
|
|
118
|
+
* first {@link submit} creates or selects a thread (or until an
|
|
119
|
+
* explicit `threadId` option is provided and hydrated).
|
|
120
|
+
*/
|
|
77
121
|
readonly threadId: string | null;
|
|
78
122
|
/**
|
|
79
123
|
* Subagents discovered on the root run. For DeepAgent-typed
|
|
@@ -110,14 +154,35 @@ interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown,
|
|
|
110
154
|
* — the server accepts a null payload in that case.
|
|
111
155
|
*/
|
|
112
156
|
submit(input: WidenUpdateMessages<Partial<StateType>> | null | undefined, options?: StreamSubmitOptions<StateType, ConfigurableType>): Promise<void>;
|
|
157
|
+
/**
|
|
158
|
+
* Abort the in-flight run on the current thread without clearing
|
|
159
|
+
* accumulated state. Sets {@link isLoading} to `false` immediately;
|
|
160
|
+
* {@link values} and {@link messages} are preserved.
|
|
161
|
+
*/
|
|
113
162
|
stop(): Promise<void>;
|
|
163
|
+
/**
|
|
164
|
+
* Resume a pending protocol interrupt by sending a response payload
|
|
165
|
+
* back to the interrupted namespace.
|
|
166
|
+
*
|
|
167
|
+
* When `target` is omitted, responds to the latest unresolved
|
|
168
|
+
* interrupt in {@link interrupts}. Pass an explicit
|
|
169
|
+
* `{ interruptId, namespace? }` when multiple interrupts are
|
|
170
|
+
* pending or the interrupt lives in a subgraph namespace.
|
|
171
|
+
*/
|
|
114
172
|
respond(response: unknown, target?: {
|
|
115
173
|
interruptId: string;
|
|
116
174
|
namespace?: string[];
|
|
117
175
|
}): Promise<void>;
|
|
176
|
+
/** LangGraph SDK client used to construct thread streams. */
|
|
118
177
|
readonly client: Client;
|
|
178
|
+
/** Assistant id the thread is bound to for its lifetime. */
|
|
119
179
|
readonly assistantId: string;
|
|
120
|
-
/**
|
|
180
|
+
/**
|
|
181
|
+
* Returns the bound {@link ThreadStream}, if one exists (`undefined`
|
|
182
|
+
* until the thread is hydrated or the first submit completes). Prefer
|
|
183
|
+
* the projections and selector hooks for UI work; use this for
|
|
184
|
+
* low-level protocol access (raw subscriptions, state commands, etc.).
|
|
185
|
+
*/
|
|
121
186
|
getThread(): ThreadStream | undefined;
|
|
122
187
|
/** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */
|
|
123
188
|
readonly [STREAM_CONTROLLER]: StreamController<StateType, InterruptType, ConfigurableType>;
|
package/dist/use-stream.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-stream.d.ts","names":[],"sources":["../src/use-stream.ts"],"mappings":";;;;;;KAsCY,oBAAA,6BACV,kBAAA,CAAyB,SAAA;AAAA,KAEf,sBAAA,6BACV,oBAAA,CAA2B,SAAA;AAAA,KAEjB,kBAAA,4BACiB,MAAA,qBACzB,gBAAA,CAAuB,SAAA;;;;;;;;;AAL3B;;cAiBa,iBAAA;AAAA,UAII,eAAA,KACX,MAAA,8EAE8B,MAAA,8CACP,cAAA,CAAe,CAAA,oBACzB,mBAAA,CAAoB,CAAA;EA1BN;;;;;AAGjC;;;;;;EAHiC,SAwCtB,MAAA,EAAQ,SAAA;EAnCO;;;;;;;EAAA,SA2Cf,YAAA,GAAe,SAAA;EA7BzB;;;;AAED;;;;;;;;;;;;;;;;EAFC,SAkDU,QAAA,EAAU,WAAA;EAAA,
|
|
1
|
+
{"version":3,"file":"use-stream.d.ts","names":[],"sources":["../src/use-stream.ts"],"mappings":";;;;;;KAsCY,oBAAA,6BACV,kBAAA,CAAyB,SAAA;AAAA,KAEf,sBAAA,6BACV,oBAAA,CAA2B,SAAA;AAAA,KAEjB,kBAAA,4BACiB,MAAA,qBACzB,gBAAA,CAAuB,SAAA;;;;;;;;;AAL3B;;cAiBa,iBAAA;AAAA,UAII,eAAA,KACX,MAAA,8EAE8B,MAAA,8CACP,cAAA,CAAe,CAAA,oB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AAAA;;;;;;;;;AAwTJ;;;;;;;;;;;;;KA9RY,SAAA,GAAY,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCR,SAAA,KACV,MAAA,8EAE8B,MAAA,kBAAA,CAElC,OAAA,EAAS,kBAAA,CAAiB,cAAA,CAAe,CAAA,KACxC,eAAA,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA;;;;KAwPzB,eAAA,KACN,MAAA,8EAE8B,MAAA,qBAChC,eAAA,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA"}
|
package/dist/use-stream.js
CHANGED
|
@@ -110,11 +110,13 @@ function useStream(options) {
|
|
|
110
110
|
useEffect(() => {
|
|
111
111
|
if (!tools?.length) return;
|
|
112
112
|
const valuesBag = rootValuesForTools;
|
|
113
|
-
const
|
|
114
|
-
|
|
113
|
+
const protocolInterrupts = rootInterruptsForTools;
|
|
114
|
+
const valuesInterrupts = Array.isArray(valuesBag?.__interrupt__) ? valuesBag.__interrupt__ : [];
|
|
115
|
+
const headlessInterrupts = protocolInterrupts.length > 0 ? protocolInterrupts : valuesInterrupts;
|
|
116
|
+
if (headlessInterrupts.length === 0) return;
|
|
115
117
|
flushPendingHeadlessToolInterrupts({
|
|
116
118
|
...valuesBag,
|
|
117
|
-
__interrupt__:
|
|
119
|
+
__interrupt__: headlessInterrupts
|
|
118
120
|
}, tools, handledToolsRef.current, {
|
|
119
121
|
onTool,
|
|
120
122
|
defer: (run) => {
|
package/dist/use-stream.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-stream.js","names":["ClientCtor"],"sources":["../src/use-stream.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n filterOutHeadlessToolInterrupts,\n flushPendingHeadlessToolInterrupts,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Client as ClientCtor,\n type ClientConfig,\n type ThreadStream,\n} from \"@langchain/langgraph-sdk/client\";\nimport {\n StreamController,\n type AgentServerAdapter,\n type AgentServerOptions as StreamAgentServerOptions,\n type ChannelRegistry,\n type CustomAdapterOptions as StreamCustomAdapterOptions,\n type InferStateType,\n type InferSubagentStates,\n type InferToolCalls,\n type RootSnapshot,\n type RunCompletedInfo,\n type RunExecutionInfo,\n type StreamSubmitOptions,\n type SubagentDiscoverySnapshot,\n type SubagentMap,\n type SubgraphByNodeMap,\n type SubgraphDiscoverySnapshot,\n type SubgraphMap,\n type UseStreamOptions as StreamUseStreamOptions,\n type WidenUpdateMessages,\n} from \"@langchain/langgraph-sdk/stream\";\n\nexport type AgentServerOptions<StateType extends object> =\n StreamAgentServerOptions<StateType>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n StreamCustomAdapterOptions<StateType>;\n\nexport type UseStreamOptions<\n StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<StateType>;\n\n/**\n * Private field on the hook return that carries the\n * {@link StreamController} reference. Selector hooks (`useMessages`,\n * `useToolCalls`, …) read this to reach the shared\n * {@link ChannelRegistry}. Typed as a symbol-keyed field to discourage\n * end-user access — use the selector hooks instead.\n *\n * Exported as a unique symbol so type narrowing works across\n * `useMessages(stream, target)` call sites.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n \"@langchain/react/controller\"\n);\n\nexport interface UseStreamReturn<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n StateType extends object = InferStateType<T>,\n SubagentStates = InferSubagentStates<T>,\n> {\n // ----- always-on root projections -----\n /**\n * The most recent `values`-channel snapshot emitted at the root\n * namespace — i.e. the thread-level state as the server sees it\n * after each superstep. Updated on every root `values` event, not\n * on token-level deltas: if you render `values.messages` directly\n * you'll see full turns appear at once instead of streaming\n * token-by-token. Use {@link messages} (or `useMessages`) for the\n * token-streamed view.\n *\n * Equivalent to calling `useValues(stream)`.\n */\n readonly values: StateType;\n /**\n * Type-only: the resolved state shape. Exposed so consumers can\n * derive companion hook argument types (`useValues<typeof stream>`)\n * without plumbing `T` through their component hierarchy.\n *\n * @internal\n */\n readonly \"~stateType\"?: StateType;\n /**\n * The root message projection. Assembled from two sources and\n * merged in real time:\n *\n * 1. `messages`-channel deltas — token-level streaming events\n * (`message-start`, `content-block-delta`, `message-finish`)\n * emitted by the runtime. These drive live, token-by-token\n * updates.\n * 2. `values.messages` snapshots — the authoritative ordering\n * and any messages the agent produces without token streaming\n * (human turns, tool results, echoes from subagents).\n *\n * If the backend only emits `values` events (no `messages`\n * channel), every message will appear fully-formed on each\n * values update rather than streaming. This is a backend/runtime\n * concern — the React layer faithfully renders whatever the\n * server sends.\n *\n * Equivalent to calling `useMessages(stream)` with no target.\n */\n readonly messages: BaseMessage[];\n readonly toolCalls: InferToolCalls<T>[];\n readonly interrupts: Interrupt<InterruptType>[];\n readonly interrupt: Interrupt<InterruptType> | undefined;\n readonly isLoading: boolean;\n readonly isThreadLoading: boolean;\n /**\n * Promise that settles when the current thread's initial hydration\n * completes. Exposed so Suspense wrappers can `throw` it until the\n * first {@link StreamController.hydrate} call resolves (or rejects)\n * for the active thread. A fresh promise is installed on every\n * `switchThread`/`threadId` change.\n */\n readonly hydrationPromise: Promise<void>;\n readonly error: unknown;\n readonly threadId: string | null;\n\n // ----- always-on discovery -----\n /**\n * Subagents discovered on the root run. For DeepAgent-typed\n * streams the key set is narrowed to the subagent names declared\n * on the agent brand (`keyof InferSubagentStates<T>`).\n */\n readonly subagents: ReadonlyMap<\n keyof SubagentStates & string extends never\n ? string\n : keyof SubagentStates & string,\n SubagentDiscoverySnapshot\n >;\n /**\n * Subgraphs discovered on the root run.\n *\n * A namespace is classified as a subgraph iff at least one\n * strictly-deeper namespace has been observed with it as a prefix.\n * This is inferred from the lifecycle event stream — plain function\n * nodes (`orchestrator`, `writer` in the nested-stategraph example)\n * never appear here even though the server emits namespaced\n * lifecycle events for them. Promotion is monotonic and retroactive;\n * an entry appears as soon as the first descendant event lands.\n */\n readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n /**\n * Subgraphs indexed by the graph node that produced them\n * (`addNode(\"visualizer_0\", …)`). Each value is an array because\n * parallel fan-outs and loops can spawn multiple invocations of\n * the same node; arrays preserve insertion order. Updates in\n * lock-step with {@link subgraphs}.\n */\n readonly subgraphsByNode: ReadonlyMap<\n string,\n readonly SubgraphDiscoverySnapshot[]\n >;\n\n // ----- imperatives -----\n /**\n * Dispatch a new run on the bound thread.\n *\n * `input` is typed as `Partial<StateType>` so IDE autocompletion\n * surfaces the state keys declared on the root hook. Pass `null`\n * (or omit fields) when resuming an interrupt via `options.command.resume`\n * — the server accepts a null payload in that case.\n */\n submit(\n input: WidenUpdateMessages<Partial<StateType>> | null | undefined,\n options?: StreamSubmitOptions<StateType, ConfigurableType>\n ): Promise<void>;\n stop(): Promise<void>;\n respond(\n response: unknown,\n target?: { interruptId: string; namespace?: string[] }\n ): Promise<void>;\n\n // ----- identity -----\n readonly client: Client;\n readonly assistantId: string;\n\n /** v2 escape hatch — returns the bound {@link ThreadStream}. */\n getThread(): ThreadStream | undefined;\n\n /** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */\n readonly [STREAM_CONTROLLER]: StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >;\n}\n\n/**\n * Erased stream handle useful as a parameter type for helpers and\n * wrapper components that pass a `stream` through to selector hooks\n * (`useMessages`, `useChannel`, …) without reading `values` directly.\n * Any fully-typed `UseStreamReturn<S, I, C>` is\n * assignable to `AnyStream` because the generic slots are `any`\n * (bivariant), which avoids the `CompiledStateGraph` → `Record<string,\n * unknown>` assignment friction you hit when using the bare\n * `UseStreamReturn` default.\n *\n * @example\n * ```tsx\n * function SubgraphCard({ stream, subgraph }: {\n * stream: AnyStream;\n * subgraph: SubgraphDiscoverySnapshot;\n * }) {\n * const messages = useMessages(stream, subgraph);\n * return <Feed messages={messages} />;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * React binding for the v2-native stream runtime.\n *\n * `useStream` exposes three always-on projections\n * (`values` / `messages` / `toolCalls`) at the thread root plus\n * cheap discovery maps for subagents / subgraphs. Scoped views of\n * subagents, subgraphs, or any namespaced projection are surfaced via\n * the companion selector hooks:\n *\n * ```tsx\n * const stream = useStream({ assistantId: \"deep-agent\" });\n *\n * // Root messages — always on, already class instances.\n * stream.messages.map((m) => <Bubble key={m.id} msg={m} />);\n *\n * // Subagent view — mount = subscribe, unmount = unsubscribe.\n * function SubagentCard({ subagent }) {\n * const messages = useMessages(stream, subagent);\n * const toolCalls = useToolCalls(stream, subagent);\n * return <>{messages.map(...)}</>;\n * }\n * ```\n *\n * The first generic accepts either a plain state type\n * (`useStream<MyState>()`) *or* a compiled graph type\n * (`useStream<typeof agent>()`); in the latter case the\n * state shape is unwrapped from the graph via {@link InferStateType}, so\n * `stream.values` is always typed as the state, never as the graph\n * class itself.\n */\nexport function useStream<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n>(\n options: UseStreamOptions<InferStateType<T>>\n): UseStreamReturn<T, InterruptType, ConfigurableType> {\n type StateType = InferStateType<T>;\n // Branch-stable narrowings for each code path. The custom-adapter\n // branch can skip LGP client construction entirely, which keeps\n // bundles that *only* use a custom adapter free of the default\n // `sse`/`websocket` transport factories (tree-shaken).\n // Treat the options as a flat bag here — the discriminated union\n // exists to give call sites a nice error message, but at runtime\n // both branches are reachable through the same set of fields.\n interface OptionsBag {\n assistantId?: string;\n threadId?: string | null;\n client?: Client;\n apiUrl?: string;\n apiKey?: string;\n callerOptions?: ClientConfig[\"callerOptions\"];\n defaultHeaders?: ClientConfig[\"defaultHeaders\"];\n transport?: \"sse\" | \"websocket\" | AgentServerAdapter;\n fetch?: typeof fetch;\n webSocketFactory?: (url: string) => WebSocket;\n onThreadId?: (threadId: string) => void;\n onCreated?: (info: RunExecutionInfo) => void;\n onCompleted?: (info: RunCompletedInfo) => void;\n initialValues?: StateType;\n messagesKey?: string;\n }\n const asBag = options as OptionsBag;\n // Narrow once: a non-string `transport` is a custom adapter; anything\n // else (`\"sse\"` / `\"websocket\"` / `undefined`) is a built-in.\n const hasCustomAdapter =\n asBag.transport != null && typeof asBag.transport !== \"string\";\n const transport = asBag.transport;\n\n const client = useMemo<Client>(\n () =>\n asBag.client ??\n (new ClientCtor({\n apiUrl: asBag.apiUrl,\n apiKey: asBag.apiKey,\n callerOptions: asBag.callerOptions,\n defaultHeaders: asBag.defaultHeaders,\n }) as unknown as Client),\n [\n asBag.client,\n asBag.apiUrl,\n asBag.apiKey,\n asBag.callerOptions,\n asBag.defaultHeaders,\n ]\n );\n\n // Custom adapters may omit `assistantId`; the controller still\n // requires one so it has something to forward to `threads.stream`.\n // `\"_\"` is the well-known sentinel for \"adapter doesn't care\".\n const sentinel = \"_\";\n const assistantId =\n \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n // Recreate the controller only on assistantId / client / transport\n // change; the ThreadStream is bound to one assistant for its\n // lifetime and we want selector-hook subscriptions to stay stable\n // across renders.\n const controller = useMemo(\n () =>\n new StreamController<StateType, InterruptType, ConfigurableType>({\n assistantId,\n // Cast: the runtime `Client` is state-shape agnostic, but the\n // controller declares `client: Client<StateType>` so its own\n // typings line up. Tightening `submit`'s `input` parameter to\n // `Partial<StateType>` surfaced this variance mismatch that\n // was previously masked — the cast is equivalent to the\n // ClientCtor cast above.\n client: client as unknown as Client<StateType>,\n threadId: options.threadId ?? null,\n transport,\n fetch: hasCustomAdapter ? undefined : asBag.fetch,\n webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n onThreadId: options.onThreadId,\n onCreated: options.onCreated,\n onCompleted: options.onCompleted,\n initialValues: options.initialValues,\n messagesKey: options.messagesKey,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client, assistantId, transport]\n );\n\n // Rehydrate on threadId change. The initial hydrate is fired\n // synchronously inside the controller constructor so Suspense\n // callers don't deadlock waiting for an effect that never runs\n // (throwing `hydrationPromise` during render unmounts the subtree\n // before effects fire). We only re-hydrate here when the threadId\n // prop changes after the controller was already constructed with a\n // matching id.\n const lastHydratedRef = useRef<{\n controller: StreamController<StateType, InterruptType, ConfigurableType>;\n threadId: string | null;\n } | null>(null);\n useEffect(() => {\n const target = options.threadId ?? null;\n const last = lastHydratedRef.current;\n if (last?.controller !== controller) {\n // Freshly constructed controller already seeded the hydrate in\n // its constructor — record the id and skip the redundant call.\n lastHydratedRef.current = { controller, threadId: target };\n return;\n }\n if (last.threadId === target) return;\n lastHydratedRef.current = { controller, threadId: target };\n void controller.hydrate(target);\n }, [controller, options.threadId]);\n\n // Dispose on unmount / controller swap.\n //\n // We use `controller.activate()` instead of a naive\n // `() => controller.dispose()` cleanup because React 18+\n // `<StrictMode>` in dev mounts → unmounts → remounts components\n // synchronously to surface cleanup bugs. A naive cleanup would\n // permanently tear the controller down on that first synthetic\n // unmount and turn every subsequent `submit()` into a silent\n // no-op. `activate()` defers disposal to the next microtask and\n // cancels it if the effect re-runs — which is exactly the\n // StrictMode remount pattern.\n useEffect(() => controller.activate(), [controller]);\n\n // Headless-tool handling: if the caller supplied `tools`, watch the\n // root `values.__interrupt__` channel for protocol interrupts that\n // target a registered tool, invoke the handler, and auto-resume the\n // run. Ref-tracks the ids we've already handled so the same\n // interrupt on a subsequent render is never executed twice\n // (StrictMode safe).\n const handledToolsRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n handledToolsRef.current.clear();\n }, [options.threadId]);\n const tools = options.tools;\n const onTool = options.onTool;\n // Subscribe to values + interrupt updates via the root store so the\n // effect re-runs whenever a protocol interrupt lands or the\n // `__interrupt__` key is projected into values, not only on hook\n // re-render. We feed both sources to the flush helper because\n // v2-native runs surface protocol interrupts via\n // `rootStore.interrupts` (`input.requested` events), while legacy\n // graphs may still emit `values.__interrupt__`.\n const rootValuesForTools = useSyncExternalStore<StateType>(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().values,\n () => controller.rootStore.getSnapshot().values\n );\n const rootInterruptsForTools = useSyncExternalStore<\n readonly Interrupt<InterruptType>[]\n >(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().interrupts,\n () => controller.rootStore.getSnapshot().interrupts\n );\n useEffect(() => {\n if (!tools?.length) return;\n const valuesBag = rootValuesForTools as unknown as Record<string, unknown>;\n const existingInterrupts = Array.isArray(valuesBag?.__interrupt__)\n ? (valuesBag.__interrupt__ as Interrupt[])\n : [];\n const combined: Interrupt[] = [\n ...existingInterrupts,\n ...(rootInterruptsForTools as unknown as Interrupt[]),\n ];\n if (combined.length === 0) return;\n flushPendingHeadlessToolInterrupts(\n { ...valuesBag, __interrupt__: combined },\n tools,\n handledToolsRef.current,\n {\n onTool,\n defer: (run) => {\n void Promise.resolve().then(run);\n },\n resumeSubmit: (command) =>\n controller.submit(null, {\n command,\n } as StreamSubmitOptions<StateType, ConfigurableType>),\n }\n );\n }, [controller, tools, onTool, rootValuesForTools, rootInterruptsForTools]);\n\n const root = useSyncExternalStore<RootSnapshot<StateType, InterruptType>>(\n controller.rootStore.subscribe,\n controller.rootStore.getSnapshot,\n controller.rootStore.getSnapshot\n );\n const subagents = useSyncExternalStore<SubagentMap>(\n controller.subagentStore.subscribe,\n controller.subagentStore.getSnapshot,\n controller.subagentStore.getSnapshot\n );\n const subgraphs = useSyncExternalStore<SubgraphMap>(\n controller.subgraphStore.subscribe,\n controller.subgraphStore.getSnapshot,\n controller.subgraphStore.getSnapshot\n );\n const subgraphsByNode = useSyncExternalStore<SubgraphByNodeMap>(\n controller.subgraphByNodeStore.subscribe,\n controller.subgraphByNodeStore.getSnapshot,\n controller.subgraphByNodeStore.getSnapshot\n );\n\n return useMemo<UseStreamReturn<T, InterruptType, ConfigurableType>>(() => {\n const userFacingInterrupts = filterOutHeadlessToolInterrupts(\n root.interrupts\n );\n return {\n values: root.values,\n messages: root.messages,\n toolCalls: root.toolCalls as InferToolCalls<T>[],\n interrupts: userFacingInterrupts,\n interrupt: userFacingInterrupts[0],\n isLoading: root.isLoading,\n isThreadLoading: root.isThreadLoading,\n hydrationPromise: controller.hydrationPromise,\n error: root.error,\n threadId: root.threadId,\n subagents: subagents as UseStreamReturn<\n T,\n InterruptType,\n ConfigurableType\n >[\"subagents\"],\n subgraphs,\n subgraphsByNode,\n submit: (input, submitOptions) => controller.submit(input, submitOptions),\n stop: () => controller.stop(),\n respond: (response, target) => controller.respond(response, target),\n getThread: () => controller.getThread(),\n client,\n assistantId,\n [STREAM_CONTROLLER]: controller,\n } as UseStreamReturn<T, InterruptType, ConfigurableType>;\n }, [\n root,\n subagents,\n subgraphs,\n subgraphsByNode,\n controller,\n client,\n assistantId,\n ]);\n}\n\n/**\n * Convenience alias for the fully-resolved stream handle type.\n */\nexport type UseStreamResult<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n> = UseStreamReturn<T, InterruptType, ConfigurableType>;\n\n/**\n * Helper used by the selector hooks to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\n * instead of reading this directly.\n *\n * @internal\n */\nexport function getRegistry(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stream: UseStreamReturn<any, any, any>\n): ChannelRegistry {\n return stream[STREAM_CONTROLLER].registry;\n}\n\nexport type { ThreadStream };\n"],"mappings":";;;;;;;;;;;;;;;;AA0DA,MAAa,oBAAmC,OAAO,IACrD,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+LD,SAAgB,UAKd,SACqD;CA0BrD,MAAM,QAAQ;CAGd,MAAM,mBACJ,MAAM,aAAa,QAAQ,OAAO,MAAM,cAAc;CACxD,MAAM,YAAY,MAAM;CAExB,MAAM,SAAS,cAEX,MA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W,QAAQ,UAAU,OAAO;GACnE,iBAAiB,WAAW,WAAW;GACvC;GACA;IACC,oBAAoB;GACtB;IACA;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;;;;;;;;;;AAoBJ,SAAgB,YAEd,QACiB;AACjB,QAAO,OAAO,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"use-stream.js","names":["ClientCtor"],"sources":["../src/use-stream.ts"],"sourcesContent":["/* __LC_ALLOW_ENTRYPOINT_SIDE_EFFECTS__ */\n\n\"use client\";\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n filterOutHeadlessToolInterrupts,\n flushPendingHeadlessToolInterrupts,\n} from \"@langchain/langgraph-sdk\";\nimport {\n Client as ClientCtor,\n type ClientConfig,\n type ThreadStream,\n} from \"@langchain/langgraph-sdk/client\";\nimport {\n StreamController,\n type AgentServerAdapter,\n type AgentServerOptions as StreamAgentServerOptions,\n type ChannelRegistry,\n type CustomAdapterOptions as StreamCustomAdapterOptions,\n type InferStateType,\n type InferSubagentStates,\n type InferToolCalls,\n type RootSnapshot,\n type RunCompletedInfo,\n type RunExecutionInfo,\n type StreamSubmitOptions,\n type SubagentDiscoverySnapshot,\n type SubagentMap,\n type SubgraphByNodeMap,\n type SubgraphDiscoverySnapshot,\n type SubgraphMap,\n type UseStreamOptions as StreamUseStreamOptions,\n type WidenUpdateMessages,\n} from \"@langchain/langgraph-sdk/stream\";\n\nexport type AgentServerOptions<StateType extends object> =\n StreamAgentServerOptions<StateType>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n StreamCustomAdapterOptions<StateType>;\n\nexport type UseStreamOptions<\n StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<StateType>;\n\n/**\n * Private field on the hook return that carries the\n * {@link StreamController} reference. Selector hooks (`useMessages`,\n * `useToolCalls`, …) read this to reach the shared\n * {@link ChannelRegistry}. Typed as a symbol-keyed field to discourage\n * end-user access — use the selector hooks instead.\n *\n * Exported as a unique symbol so type narrowing works across\n * `useMessages(stream, target)` call sites.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n \"@langchain/react/controller\"\n);\n\nexport interface UseStreamReturn<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n StateType extends object = InferStateType<T>,\n SubagentStates = InferSubagentStates<T>,\n> {\n // ----- always-on root projections -----\n /**\n * The most recent `values`-channel snapshot emitted at the root\n * namespace — i.e. the thread-level state as the server sees it\n * after each superstep. Updated on every root `values` event, not\n * on token-level deltas: if you render `values.messages` directly\n * you'll see full turns appear at once instead of streaming\n * token-by-token. Use {@link messages} (or `useMessages`) for the\n * token-streamed view.\n *\n * Equivalent to calling `useValues(stream)`.\n */\n readonly values: StateType;\n /**\n * Type-only: the resolved state shape. Exposed so consumers can\n * derive companion hook argument types (`useValues<typeof stream>`)\n * without plumbing `T` through their component hierarchy.\n *\n * @internal\n */\n readonly \"~stateType\"?: StateType;\n /**\n * The root message projection. Assembled from two sources and\n * merged in real time:\n *\n * 1. `messages`-channel deltas — token-level streaming events\n * (`message-start`, `content-block-delta`, `message-finish`)\n * emitted by the runtime. These drive live, token-by-token\n * updates.\n * 2. `values.messages` snapshots — the authoritative ordering\n * and any messages the agent produces without token streaming\n * (human turns, tool results, echoes from subagents).\n *\n * If the backend only emits `values` events (no `messages`\n * channel), every message will appear fully-formed on each\n * values update rather than streaming. This is a backend/runtime\n * concern — the React layer faithfully renders whatever the\n * server sends.\n *\n * Equivalent to calling `useMessages(stream)` with no target.\n */\n readonly messages: BaseMessage[];\n /**\n * Root-namespace tool calls assembled from the `tools` channel.\n * Each entry is a fully parsed {@link AssembledToolCall} with\n * name, args, and id — suitable for rendering approval UIs or\n * forwarding to headless tool handlers.\n *\n * When the stream is typed with an agent brand or tool list,\n * entries are narrowed via {@link InferToolCalls}. Equivalent to\n * calling `useToolCalls(stream)` with no target.\n */\n readonly toolCalls: InferToolCalls<T>[];\n /**\n * All unresolved protocol interrupts observed on the root\n * namespace during the active thread. Populated from lifecycle /\n * input events and seeded on hydration from `thread.getState()`.\n * Cleared optimistically when a new run starts or an interrupt is\n * resolved via {@link respond} / `submit({ command: { resume } })`.\n */\n readonly interrupts: Interrupt<InterruptType>[];\n /**\n * Convenience alias for {@link interrupts}[0] — the primary\n * interrupt most UIs should act on when only one is pending.\n * `undefined` when no interrupt is active.\n */\n readonly interrupt: Interrupt<InterruptType> | undefined;\n /**\n * `true` while a run is active or being started on the current\n * thread. Driven by root-namespace lifecycle events (`running` →\n * `true`, terminal phases → `false`). Use this to disable submit\n * buttons and show in-flight spinners.\n */\n readonly isLoading: boolean;\n /**\n * `true` while the initial `thread.getState()` hydration for the\n * active thread is in flight. Distinct from {@link isLoading} —\n * thread loading covers the one-time fetch that seeds\n * {@link values} / {@link messages} before any user submit.\n */\n readonly isThreadLoading: boolean;\n /**\n * Promise that settles when the current thread's initial hydration\n * completes. Exposed so Suspense wrappers can `throw` it until the\n * first {@link StreamController.hydrate} call resolves (or rejects)\n * for the active thread. A fresh promise is installed on every\n * `switchThread`/`threadId` change.\n */\n readonly hydrationPromise: Promise<void>;\n /**\n * The last error observed on the active run or hydration attempt.\n * `undefined` when no error has occurred. Cleared optimistically\n * when a new {@link submit} starts.\n */\n readonly error: unknown;\n /**\n * Id of the thread the controller is bound to. `null` until the\n * first {@link submit} creates or selects a thread (or until an\n * explicit `threadId` option is provided and hydrated).\n */\n readonly threadId: string | null;\n\n // ----- always-on discovery -----\n /**\n * Subagents discovered on the root run. For DeepAgent-typed\n * streams the key set is narrowed to the subagent names declared\n * on the agent brand (`keyof InferSubagentStates<T>`).\n */\n readonly subagents: ReadonlyMap<\n keyof SubagentStates & string extends never\n ? string\n : keyof SubagentStates & string,\n SubagentDiscoverySnapshot\n >;\n /**\n * Subgraphs discovered on the root run.\n *\n * A namespace is classified as a subgraph iff at least one\n * strictly-deeper namespace has been observed with it as a prefix.\n * This is inferred from the lifecycle event stream — plain function\n * nodes (`orchestrator`, `writer` in the nested-stategraph example)\n * never appear here even though the server emits namespaced\n * lifecycle events for them. Promotion is monotonic and retroactive;\n * an entry appears as soon as the first descendant event lands.\n */\n readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n /**\n * Subgraphs indexed by the graph node that produced them\n * (`addNode(\"visualizer_0\", …)`). Each value is an array because\n * parallel fan-outs and loops can spawn multiple invocations of\n * the same node; arrays preserve insertion order. Updates in\n * lock-step with {@link subgraphs}.\n */\n readonly subgraphsByNode: ReadonlyMap<\n string,\n readonly SubgraphDiscoverySnapshot[]\n >;\n\n // ----- imperatives -----\n /**\n * Dispatch a new run on the bound thread.\n *\n * `input` is typed as `Partial<StateType>` so IDE autocompletion\n * surfaces the state keys declared on the root hook. Pass `null`\n * (or omit fields) when resuming an interrupt via `options.command.resume`\n * — the server accepts a null payload in that case.\n */\n submit(\n input: WidenUpdateMessages<Partial<StateType>> | null | undefined,\n options?: StreamSubmitOptions<StateType, ConfigurableType>\n ): Promise<void>;\n /**\n * Abort the in-flight run on the current thread without clearing\n * accumulated state. Sets {@link isLoading} to `false` immediately;\n * {@link values} and {@link messages} are preserved.\n */\n stop(): Promise<void>;\n /**\n * Resume a pending protocol interrupt by sending a response payload\n * back to the interrupted namespace.\n *\n * When `target` is omitted, responds to the latest unresolved\n * interrupt in {@link interrupts}. Pass an explicit\n * `{ interruptId, namespace? }` when multiple interrupts are\n * pending or the interrupt lives in a subgraph namespace.\n */\n respond(\n response: unknown,\n target?: { interruptId: string; namespace?: string[] }\n ): Promise<void>;\n\n // ----- identity -----\n /** LangGraph SDK client used to construct thread streams. */\n readonly client: Client;\n /** Assistant id the thread is bound to for its lifetime. */\n readonly assistantId: string;\n\n /**\n * Returns the bound {@link ThreadStream}, if one exists (`undefined`\n * until the thread is hydrated or the first submit completes). Prefer\n * the projections and selector hooks for UI work; use this for\n * low-level protocol access (raw subscriptions, state commands, etc.).\n */\n getThread(): ThreadStream | undefined;\n\n /** @internal Used by selector hooks (`useMessages`, `useToolCalls`, …). */\n readonly [STREAM_CONTROLLER]: StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >;\n}\n\n/**\n * Erased stream handle useful as a parameter type for helpers and\n * wrapper components that pass a `stream` through to selector hooks\n * (`useMessages`, `useChannel`, …) without reading `values` directly.\n * Any fully-typed `UseStreamReturn<S, I, C>` is\n * assignable to `AnyStream` because the generic slots are `any`\n * (bivariant), which avoids the `CompiledStateGraph` → `Record<string,\n * unknown>` assignment friction you hit when using the bare\n * `UseStreamReturn` default.\n *\n * @example\n * ```tsx\n * function SubgraphCard({ stream, subgraph }: {\n * stream: AnyStream;\n * subgraph: SubgraphDiscoverySnapshot;\n * }) {\n * const messages = useMessages(stream, subgraph);\n * return <Feed messages={messages} />;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * React binding for the v2-native stream runtime.\n *\n * `useStream` exposes three always-on projections\n * (`values` / `messages` / `toolCalls`) at the thread root plus\n * cheap discovery maps for subagents / subgraphs. Scoped views of\n * subagents, subgraphs, or any namespaced projection are surfaced via\n * the companion selector hooks:\n *\n * ```tsx\n * const stream = useStream({ assistantId: \"deep-agent\" });\n *\n * // Root messages — always on, already class instances.\n * stream.messages.map((m) => <Bubble key={m.id} msg={m} />);\n *\n * // Subagent view — mount = subscribe, unmount = unsubscribe.\n * function SubagentCard({ subagent }) {\n * const messages = useMessages(stream, subagent);\n * const toolCalls = useToolCalls(stream, subagent);\n * return <>{messages.map(...)}</>;\n * }\n * ```\n *\n * The first generic accepts either a plain state type\n * (`useStream<MyState>()`) *or* a compiled graph type\n * (`useStream<typeof agent>()`); in the latter case the\n * state shape is unwrapped from the graph via {@link InferStateType}, so\n * `stream.values` is always typed as the state, never as the graph\n * class itself.\n */\nexport function useStream<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n>(\n options: UseStreamOptions<InferStateType<T>>\n): UseStreamReturn<T, InterruptType, ConfigurableType> {\n type StateType = InferStateType<T>;\n // Branch-stable narrowings for each code path. The custom-adapter\n // branch can skip LGP client construction entirely, which keeps\n // bundles that *only* use a custom adapter free of the default\n // `sse`/`websocket` transport factories (tree-shaken).\n // Treat the options as a flat bag here — the discriminated union\n // exists to give call sites a nice error message, but at runtime\n // both branches are reachable through the same set of fields.\n interface OptionsBag {\n assistantId?: string;\n threadId?: string | null;\n client?: Client;\n apiUrl?: string;\n apiKey?: string;\n callerOptions?: ClientConfig[\"callerOptions\"];\n defaultHeaders?: ClientConfig[\"defaultHeaders\"];\n transport?: \"sse\" | \"websocket\" | AgentServerAdapter;\n fetch?: typeof fetch;\n webSocketFactory?: (url: string) => WebSocket;\n onThreadId?: (threadId: string) => void;\n onCreated?: (info: RunExecutionInfo) => void;\n onCompleted?: (info: RunCompletedInfo) => void;\n initialValues?: StateType;\n messagesKey?: string;\n }\n const asBag = options as OptionsBag;\n // Narrow once: a non-string `transport` is a custom adapter; anything\n // else (`\"sse\"` / `\"websocket\"` / `undefined`) is a built-in.\n const hasCustomAdapter =\n asBag.transport != null && typeof asBag.transport !== \"string\";\n const transport = asBag.transport;\n\n const client = useMemo<Client>(\n () =>\n asBag.client ??\n (new ClientCtor({\n apiUrl: asBag.apiUrl,\n apiKey: asBag.apiKey,\n callerOptions: asBag.callerOptions,\n defaultHeaders: asBag.defaultHeaders,\n }) as unknown as Client),\n [\n asBag.client,\n asBag.apiUrl,\n asBag.apiKey,\n asBag.callerOptions,\n asBag.defaultHeaders,\n ]\n );\n\n // Custom adapters may omit `assistantId`; the controller still\n // requires one so it has something to forward to `threads.stream`.\n // `\"_\"` is the well-known sentinel for \"adapter doesn't care\".\n const sentinel = \"_\";\n const assistantId =\n \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n // Recreate the controller only on assistantId / client / transport\n // change; the ThreadStream is bound to one assistant for its\n // lifetime and we want selector-hook subscriptions to stay stable\n // across renders.\n const controller = useMemo(\n () =>\n new StreamController<StateType, InterruptType, ConfigurableType>({\n assistantId,\n // Cast: the runtime `Client` is state-shape agnostic, but the\n // controller declares `client: Client<StateType>` so its own\n // typings line up. Tightening `submit`'s `input` parameter to\n // `Partial<StateType>` surfaced this variance mismatch that\n // was previously masked — the cast is equivalent to the\n // ClientCtor cast above.\n client: client as unknown as Client<StateType>,\n threadId: options.threadId ?? null,\n transport,\n fetch: hasCustomAdapter ? undefined : asBag.fetch,\n webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n onThreadId: options.onThreadId,\n onCreated: options.onCreated,\n onCompleted: options.onCompleted,\n initialValues: options.initialValues,\n messagesKey: options.messagesKey,\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [client, assistantId, transport]\n );\n\n // Rehydrate on threadId change. The initial hydrate is fired\n // synchronously inside the controller constructor so Suspense\n // callers don't deadlock waiting for an effect that never runs\n // (throwing `hydrationPromise` during render unmounts the subtree\n // before effects fire). We only re-hydrate here when the threadId\n // prop changes after the controller was already constructed with a\n // matching id.\n const lastHydratedRef = useRef<{\n controller: StreamController<StateType, InterruptType, ConfigurableType>;\n threadId: string | null;\n } | null>(null);\n useEffect(() => {\n const target = options.threadId ?? null;\n const last = lastHydratedRef.current;\n if (last?.controller !== controller) {\n // Freshly constructed controller already seeded the hydrate in\n // its constructor — record the id and skip the redundant call.\n lastHydratedRef.current = { controller, threadId: target };\n return;\n }\n if (last.threadId === target) return;\n lastHydratedRef.current = { controller, threadId: target };\n void controller.hydrate(target);\n }, [controller, options.threadId]);\n\n // Dispose on unmount / controller swap.\n //\n // We use `controller.activate()` instead of a naive\n // `() => controller.dispose()` cleanup because React 18+\n // `<StrictMode>` in dev mounts → unmounts → remounts components\n // synchronously to surface cleanup bugs. A naive cleanup would\n // permanently tear the controller down on that first synthetic\n // unmount and turn every subsequent `submit()` into a silent\n // no-op. `activate()` defers disposal to the next microtask and\n // cancels it if the effect re-runs — which is exactly the\n // StrictMode remount pattern.\n useEffect(() => controller.activate(), [controller]);\n\n // Headless-tool handling: if the caller supplied `tools`, watch the\n // root `values.__interrupt__` channel for protocol interrupts that\n // target a registered tool, invoke the handler, and auto-resume the\n // run. Ref-tracks the ids we've already handled so the same\n // interrupt on a subsequent render is never executed twice\n // (StrictMode safe).\n const handledToolsRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n handledToolsRef.current.clear();\n }, [options.threadId]);\n const tools = options.tools;\n const onTool = options.onTool;\n // Subscribe to values + interrupt updates via the root store so the\n // effect re-runs whenever a protocol interrupt lands or the\n // `__interrupt__` key is projected into values, not only on hook\n // re-render. Prefer protocol interrupts from `rootStore.interrupts`\n // (`input.requested` events) because their ids are accepted directly\n // by `Command({ resume })`; fall back to `values.__interrupt__` for\n // older streams that only expose interrupts through values.\n const rootValuesForTools = useSyncExternalStore<StateType>(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().values,\n () => controller.rootStore.getSnapshot().values\n );\n const rootInterruptsForTools = useSyncExternalStore<\n readonly Interrupt<InterruptType>[]\n >(\n controller.rootStore.subscribe,\n () => controller.rootStore.getSnapshot().interrupts,\n () => controller.rootStore.getSnapshot().interrupts\n );\n useEffect(() => {\n if (!tools?.length) return;\n const valuesBag = rootValuesForTools as unknown as Record<string, unknown>;\n const protocolInterrupts = rootInterruptsForTools as unknown as Interrupt[];\n const valuesInterrupts = Array.isArray(valuesBag?.__interrupt__)\n ? (valuesBag.__interrupt__ as Interrupt[])\n : [];\n const headlessInterrupts =\n protocolInterrupts.length > 0 ? protocolInterrupts : valuesInterrupts;\n if (headlessInterrupts.length === 0) return;\n flushPendingHeadlessToolInterrupts(\n { ...valuesBag, __interrupt__: headlessInterrupts },\n tools,\n handledToolsRef.current,\n {\n onTool,\n defer: (run) => {\n void Promise.resolve().then(run);\n },\n resumeSubmit: (command) =>\n controller.submit(null, {\n command,\n } as StreamSubmitOptions<StateType, ConfigurableType>),\n }\n );\n }, [controller, tools, onTool, rootValuesForTools, rootInterruptsForTools]);\n\n const root = useSyncExternalStore<RootSnapshot<StateType, InterruptType>>(\n controller.rootStore.subscribe,\n controller.rootStore.getSnapshot,\n controller.rootStore.getSnapshot\n );\n const subagents = useSyncExternalStore<SubagentMap>(\n controller.subagentStore.subscribe,\n controller.subagentStore.getSnapshot,\n controller.subagentStore.getSnapshot\n );\n const subgraphs = useSyncExternalStore<SubgraphMap>(\n controller.subgraphStore.subscribe,\n controller.subgraphStore.getSnapshot,\n controller.subgraphStore.getSnapshot\n );\n const subgraphsByNode = useSyncExternalStore<SubgraphByNodeMap>(\n controller.subgraphByNodeStore.subscribe,\n controller.subgraphByNodeStore.getSnapshot,\n controller.subgraphByNodeStore.getSnapshot\n );\n\n return useMemo<UseStreamReturn<T, InterruptType, ConfigurableType>>(() => {\n const userFacingInterrupts = filterOutHeadlessToolInterrupts(\n root.interrupts\n );\n return {\n values: root.values,\n messages: root.messages,\n toolCalls: root.toolCalls as InferToolCalls<T>[],\n interrupts: userFacingInterrupts,\n interrupt: userFacingInterrupts[0],\n isLoading: root.isLoading,\n isThreadLoading: root.isThreadLoading,\n hydrationPromise: controller.hydrationPromise,\n error: root.error,\n threadId: root.threadId,\n subagents: subagents as UseStreamReturn<\n T,\n InterruptType,\n ConfigurableType\n >[\"subagents\"],\n subgraphs,\n subgraphsByNode,\n submit: (input, submitOptions) => controller.submit(input, submitOptions),\n stop: () => controller.stop(),\n respond: (response, target) => controller.respond(response, target),\n getThread: () => controller.getThread(),\n client,\n assistantId,\n [STREAM_CONTROLLER]: controller,\n } as UseStreamReturn<T, InterruptType, ConfigurableType>;\n }, [\n root,\n subagents,\n subgraphs,\n subgraphsByNode,\n controller,\n client,\n assistantId,\n ]);\n}\n\n/**\n * Convenience alias for the fully-resolved stream handle type.\n */\nexport type UseStreamResult<\n T = Record<string, unknown>,\n InterruptType = unknown,\n ConfigurableType extends object = Record<string, unknown>,\n> = UseStreamReturn<T, InterruptType, ConfigurableType>;\n\n/**\n * Helper used by the selector hooks to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\n * instead of reading this directly.\n *\n * @internal\n */\nexport function getRegistry(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n stream: UseStreamReturn<any, any, any>\n): ChannelRegistry {\n return stream[STREAM_CONTROLLER].registry;\n}\n\nexport type { ThreadStream };\n"],"mappings":";;;;;;;;;;;;;;;;AA0DA,MAAa,oBAAmC,OAAO,IACrD,8BACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQD,SAAgB,UAKd,SACqD;CA0BrD,MAAM,QAAQ;CAGd,MAAM,mBACJ,MAAM,aAAa,QAAQ,OAAO,MAAM,cAAc;CACxD,MAAM,YAAY,MAAM;CAExB,MAAM,SAAS,cAEX,MAAM,UACL,IAAIA,SAAW;EACd,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,eAAe,MAAM;EACrB,gBAAgB,MAAM;EACvB,CAAC,EACJ;EACE,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACN,MAAM;EACP,CACF;CAKD,MAAM,WAAW;CACjB,MAAM,cACJ,iBAAiB,UAAW,QAAQ,eAAe,WAAY;CAMjE,MAAM,aAAa,cAEf,IAAI,iBAA6D;EAC/D;EAOQ;EACR,UAAU,QAAQ,YAAY;EAC9B;EACA,OAAO,mBAAmB,KAAA,IAAY,MAAM;EAC5C,kBAAkB,mBAAmB,KAAA,IAAY,MAAM;EACvD,YAAY,QAAQ;EACpB,WAAW,QAAQ;EACnB,aAAa,QAAQ;EACrB,eAAe,QAAQ;EACvB,aAAa,QAAQ;EACtB,CAAC,EAEJ;EAAC;EAAQ;EAAa;EAAU,CACjC;CASD,MAAM,kBAAkB,OAGd,KAAK;AACf,iBAAgB;EACd,MAAM,SAAS,QAAQ,YAAY;EACnC,MAAM,OAAO,gBAAgB;AAC7B,MAAI,MAAM,eAAe,YAAY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WACzB,WAAW,cAAc,aACzB,WAAW,cAAc,YAC1B;CACD,MAAM,YAAY,qBAChB,WAAW,cAAc,WACzB,WAAW,cAAc,aACzB,WAAW,cAAc,YAC1B;CACD,MAAM,kBAAkB,qBACtB,WAAW,oBAAoB,WAC/B,WAAW,oBAAoB,aAC/B,WAAW,oBAAoB,YAChC;AAED,QAAO,cAAmE;EACxE,MAAM,uBAAuB,gCAC3B,KAAK,WACN;AACD,SAAO;GACL,QAAQ,KAAK;GACb,UAAU,KAAK;GACf,WAAW,KAAK;GAChB,YAAY;GACZ,WAAW,qBAAqB;GAChC,WAAW,KAAK;GAChB,iBAAiB,KAAK;GACtB,kBAAkB,WAAW;GAC7B,OAAO,KAAK;GACZ,UAAU,KAAK;GACJ;GAKX;GACA;GACA,SAAS,OAAO,kBAAkB,WAAW,OAAO,OAAO,cAAc;GACzE,YAAY,WAAW,MAAM;GAC7B,UAAU,UAAU,WAAW,WAAW,QAAQ,UAAU,OAAO;GACnE,iBAAiB,WAAW,WAAW;GACvC;GACA;IACC,oBAAoB;GACtB;IACA;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC;;;;;;;;;;AAoBJ,SAAgB,YAEd,QACiB;AACjB,QAAO,OAAO,mBAAmB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@langchain/react",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "React integration for LangGraph & LangChain",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
"directory": "libs/sdk-react"
|
|
11
11
|
},
|
|
12
12
|
"dependencies": {
|
|
13
|
-
"@langchain/langgraph-sdk": "1.9.
|
|
13
|
+
"@langchain/langgraph-sdk": "1.9.6"
|
|
14
14
|
},
|
|
15
15
|
"devDependencies": {
|
|
16
16
|
"@hono/node-server": "^1.19.13",
|