@langchain/svelte 0.4.6 → 1.0.0
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/README.md +37 -443
- package/dist/context.cjs +72 -0
- package/dist/context.cjs.map +1 -0
- package/dist/context.d.cts +72 -0
- package/dist/context.d.cts.map +1 -0
- package/dist/context.d.ts +72 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +70 -0
- package/dist/context.js.map +1 -0
- package/dist/index.cjs +32 -316
- package/dist/index.d.cts +11 -97
- package/dist/index.d.ts +11 -97
- package/dist/index.js +10 -290
- package/dist/selectors.svelte.cjs +214 -0
- package/dist/selectors.svelte.cjs.map +1 -0
- package/dist/selectors.svelte.d.cts +146 -0
- package/dist/selectors.svelte.d.cts.map +1 -0
- package/dist/selectors.svelte.d.ts +146 -0
- package/dist/selectors.svelte.d.ts.map +1 -0
- package/dist/selectors.svelte.js +204 -0
- package/dist/selectors.svelte.js.map +1 -0
- package/dist/use-audio-player.svelte.cjs +608 -0
- package/dist/use-audio-player.svelte.cjs.map +1 -0
- package/dist/use-audio-player.svelte.d.cts +70 -0
- package/dist/use-audio-player.svelte.d.cts.map +1 -0
- package/dist/use-audio-player.svelte.d.ts +70 -0
- package/dist/use-audio-player.svelte.d.ts.map +1 -0
- package/dist/use-audio-player.svelte.js +608 -0
- package/dist/use-audio-player.svelte.js.map +1 -0
- package/dist/use-media-url.svelte.cjs +54 -0
- package/dist/use-media-url.svelte.cjs.map +1 -0
- package/dist/use-media-url.svelte.d.cts +29 -0
- package/dist/use-media-url.svelte.d.cts.map +1 -0
- package/dist/use-media-url.svelte.d.ts +29 -0
- package/dist/use-media-url.svelte.d.ts.map +1 -0
- package/dist/use-media-url.svelte.js +54 -0
- package/dist/use-media-url.svelte.js.map +1 -0
- package/dist/use-projection.svelte.cjs +62 -0
- package/dist/use-projection.svelte.cjs.map +1 -0
- package/dist/use-projection.svelte.d.cts +65 -0
- package/dist/use-projection.svelte.d.cts.map +1 -0
- package/dist/use-projection.svelte.d.ts +65 -0
- package/dist/use-projection.svelte.d.ts.map +1 -0
- package/dist/use-projection.svelte.js +62 -0
- package/dist/use-projection.svelte.js.map +1 -0
- package/dist/use-stream.svelte.cjs +193 -0
- package/dist/use-stream.svelte.cjs.map +1 -0
- package/dist/use-stream.svelte.d.cts +116 -0
- package/dist/use-stream.svelte.d.cts.map +1 -0
- package/dist/use-stream.svelte.d.ts +116 -0
- package/dist/use-stream.svelte.d.ts.map +1 -0
- package/dist/use-stream.svelte.js +191 -0
- package/dist/use-stream.svelte.js.map +1 -0
- package/dist/use-video-player.svelte.cjs +233 -0
- package/dist/use-video-player.svelte.cjs.map +1 -0
- package/dist/use-video-player.svelte.d.cts +66 -0
- package/dist/use-video-player.svelte.d.cts.map +1 -0
- package/dist/use-video-player.svelte.d.ts +66 -0
- package/dist/use-video-player.svelte.d.ts.map +1 -0
- package/dist/use-video-player.svelte.js +233 -0
- package/dist/use-video-player.svelte.js.map +1 -0
- package/package.json +9 -8
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/stream.custom.cjs +0 -122
- package/dist/stream.custom.cjs.map +0 -1
- package/dist/stream.custom.js +0 -122
- package/dist/stream.custom.js.map +0 -1
- package/dist/subagents.cjs +0 -81
- package/dist/subagents.cjs.map +0 -1
- package/dist/subagents.js +0 -81
- package/dist/subagents.js.map +0 -1
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
let svelte = require("svelte");
|
|
2
|
+
let _langchain_langgraph_sdk = require("@langchain/langgraph-sdk");
|
|
3
|
+
let _langchain_langgraph_sdk_client = require("@langchain/langgraph-sdk/client");
|
|
4
|
+
let _langchain_langgraph_sdk_stream = require("@langchain/langgraph-sdk/stream");
|
|
5
|
+
//#region src/use-stream.svelte.ts
|
|
6
|
+
function readValueOrGetter(input) {
|
|
7
|
+
if (typeof input === "function") return input();
|
|
8
|
+
return input;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Private field on the handle that carries the {@link StreamController}
|
|
12
|
+
* reference. Selector composables read this to reach the shared
|
|
13
|
+
* {@link ChannelRegistry}. Use the selector composables
|
|
14
|
+
* (`useMessages`, `useToolCalls`, `useValues`, …) instead of reading
|
|
15
|
+
* this directly.
|
|
16
|
+
*/
|
|
17
|
+
const STREAM_CONTROLLER = Symbol.for("@langchain/svelte/controller");
|
|
18
|
+
/**
|
|
19
|
+
* Svelte 5 binding for the v2-native stream runtime.
|
|
20
|
+
*
|
|
21
|
+
* Returns a handle whose reactive fields are plain getters on a
|
|
22
|
+
* stable object — templates can read `stream.messages` directly and
|
|
23
|
+
* `$derived(stream.isLoading)` auto-tracks the getter.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```svelte
|
|
27
|
+
* <script lang="ts">
|
|
28
|
+
* import { useStream } from "@langchain/svelte";
|
|
29
|
+
*
|
|
30
|
+
* const stream = useStream({
|
|
31
|
+
* assistantId: "agent",
|
|
32
|
+
* apiUrl: "http://localhost:2024",
|
|
33
|
+
* });
|
|
34
|
+
* <\/script>
|
|
35
|
+
*
|
|
36
|
+
* {#each stream.messages as msg (msg.id)}
|
|
37
|
+
* <div>{msg.content}</div>
|
|
38
|
+
* {/each}
|
|
39
|
+
* <button onclick={() =>
|
|
40
|
+
* stream.submit({ messages: [{ type: "human", content: "Hi" }] })
|
|
41
|
+
* }>
|
|
42
|
+
* Send
|
|
43
|
+
* </button>
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* `assistantId`, `client`, and `transport` are captured at composable
|
|
47
|
+
* init. To bind a new assistant/transport, remount the component.
|
|
48
|
+
* Only `threadId` is treated as reactive — pass it as a getter
|
|
49
|
+
* (`threadId: () => active`) to drive an in-place thread swap.
|
|
50
|
+
*/
|
|
51
|
+
function useStream(options) {
|
|
52
|
+
const asBag = options;
|
|
53
|
+
const hasCustomAdapter = asBag.transport != null && typeof asBag.transport !== "string";
|
|
54
|
+
const transport = asBag.transport;
|
|
55
|
+
const client = asBag.client ?? new _langchain_langgraph_sdk_client.Client({
|
|
56
|
+
apiUrl: asBag.apiUrl,
|
|
57
|
+
apiKey: asBag.apiKey,
|
|
58
|
+
callerOptions: asBag.callerOptions,
|
|
59
|
+
defaultHeaders: asBag.defaultHeaders
|
|
60
|
+
});
|
|
61
|
+
const sentinel = "_";
|
|
62
|
+
const assistantId = "assistantId" in options ? options.assistantId ?? sentinel : sentinel;
|
|
63
|
+
const initialThreadId = readValueOrGetter(asBag.threadId) ?? null;
|
|
64
|
+
const controller = new _langchain_langgraph_sdk_stream.StreamController({
|
|
65
|
+
assistantId,
|
|
66
|
+
client,
|
|
67
|
+
threadId: initialThreadId,
|
|
68
|
+
transport,
|
|
69
|
+
fetch: hasCustomAdapter ? void 0 : asBag.fetch,
|
|
70
|
+
webSocketFactory: hasCustomAdapter ? void 0 : asBag.webSocketFactory,
|
|
71
|
+
onThreadId: options.onThreadId,
|
|
72
|
+
onCreated: options.onCreated,
|
|
73
|
+
initialValues: options.initialValues,
|
|
74
|
+
messagesKey: options.messagesKey
|
|
75
|
+
});
|
|
76
|
+
(0, svelte.onDestroy)(controller.activate());
|
|
77
|
+
let rootSnapshot = $state(controller.rootStore.getSnapshot());
|
|
78
|
+
(0, svelte.onDestroy)(controller.rootStore.subscribe(() => {
|
|
79
|
+
rootSnapshot = controller.rootStore.getSnapshot();
|
|
80
|
+
}));
|
|
81
|
+
let subagentSnapshot = $state(controller.subagentStore.getSnapshot());
|
|
82
|
+
(0, svelte.onDestroy)(controller.subagentStore.subscribe(() => {
|
|
83
|
+
subagentSnapshot = controller.subagentStore.getSnapshot();
|
|
84
|
+
}));
|
|
85
|
+
let subgraphSnapshot = $state(controller.subgraphStore.getSnapshot());
|
|
86
|
+
(0, svelte.onDestroy)(controller.subgraphStore.subscribe(() => {
|
|
87
|
+
subgraphSnapshot = controller.subgraphStore.getSnapshot();
|
|
88
|
+
}));
|
|
89
|
+
let subgraphByNodeSnapshot = $state(controller.subgraphByNodeStore.getSnapshot());
|
|
90
|
+
(0, svelte.onDestroy)(controller.subgraphByNodeStore.subscribe(() => {
|
|
91
|
+
subgraphByNodeSnapshot = controller.subgraphByNodeStore.getSnapshot();
|
|
92
|
+
}));
|
|
93
|
+
if (typeof asBag.threadId === "function") {
|
|
94
|
+
const getThreadId = asBag.threadId;
|
|
95
|
+
let previousThreadId = initialThreadId;
|
|
96
|
+
$effect(() => {
|
|
97
|
+
const next = getThreadId() ?? null;
|
|
98
|
+
if (next === previousThreadId) return;
|
|
99
|
+
previousThreadId = next;
|
|
100
|
+
controller.hydrate(next);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
const tools = options.tools;
|
|
104
|
+
const onTool = options.onTool;
|
|
105
|
+
if (tools?.length) {
|
|
106
|
+
const handledTools = /* @__PURE__ */ new Set();
|
|
107
|
+
let handledForThreadId = initialThreadId;
|
|
108
|
+
$effect(() => {
|
|
109
|
+
const currentThreadId = rootSnapshot.threadId;
|
|
110
|
+
if (currentThreadId !== handledForThreadId) {
|
|
111
|
+
handledTools.clear();
|
|
112
|
+
handledForThreadId = currentThreadId;
|
|
113
|
+
}
|
|
114
|
+
const valuesBag = rootSnapshot.values;
|
|
115
|
+
const combined = [...Array.isArray(valuesBag?.__interrupt__) ? valuesBag.__interrupt__ : [], ...rootSnapshot.interrupts];
|
|
116
|
+
if (combined.length === 0) return;
|
|
117
|
+
(0, _langchain_langgraph_sdk.flushPendingHeadlessToolInterrupts)({
|
|
118
|
+
...valuesBag,
|
|
119
|
+
__interrupt__: combined
|
|
120
|
+
}, tools, handledTools, {
|
|
121
|
+
onTool,
|
|
122
|
+
defer: (run) => {
|
|
123
|
+
Promise.resolve().then(run);
|
|
124
|
+
},
|
|
125
|
+
resumeSubmit: (command) => controller.submit(null, { command })
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
get values() {
|
|
131
|
+
return rootSnapshot.values;
|
|
132
|
+
},
|
|
133
|
+
get messages() {
|
|
134
|
+
return rootSnapshot.messages;
|
|
135
|
+
},
|
|
136
|
+
get toolCalls() {
|
|
137
|
+
return rootSnapshot.toolCalls;
|
|
138
|
+
},
|
|
139
|
+
get interrupts() {
|
|
140
|
+
return rootSnapshot.interrupts;
|
|
141
|
+
},
|
|
142
|
+
get interrupt() {
|
|
143
|
+
return rootSnapshot.interrupt;
|
|
144
|
+
},
|
|
145
|
+
get isLoading() {
|
|
146
|
+
return rootSnapshot.isLoading;
|
|
147
|
+
},
|
|
148
|
+
get isThreadLoading() {
|
|
149
|
+
return rootSnapshot.isThreadLoading;
|
|
150
|
+
},
|
|
151
|
+
get error() {
|
|
152
|
+
return rootSnapshot.error;
|
|
153
|
+
},
|
|
154
|
+
get threadId() {
|
|
155
|
+
return rootSnapshot.threadId;
|
|
156
|
+
},
|
|
157
|
+
get hydrationPromise() {
|
|
158
|
+
return controller.hydrationPromise;
|
|
159
|
+
},
|
|
160
|
+
get subagents() {
|
|
161
|
+
return subagentSnapshot;
|
|
162
|
+
},
|
|
163
|
+
get subgraphs() {
|
|
164
|
+
return subgraphSnapshot;
|
|
165
|
+
},
|
|
166
|
+
get subgraphsByNode() {
|
|
167
|
+
return subgraphByNodeSnapshot;
|
|
168
|
+
},
|
|
169
|
+
submit: (input, submitOptions) => controller.submit(input, submitOptions),
|
|
170
|
+
stop: () => controller.stop(),
|
|
171
|
+
respond: (response, target) => controller.respond(response, target),
|
|
172
|
+
getThread: () => controller.getThread(),
|
|
173
|
+
client,
|
|
174
|
+
assistantId,
|
|
175
|
+
[STREAM_CONTROLLER]: controller
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Helper used by the selector composables to reach the underlying
|
|
180
|
+
* {@link ChannelRegistry} from a stream handle. Kept internal —
|
|
181
|
+
* application code should call `useMessages`, `useToolCalls`, etc.
|
|
182
|
+
*
|
|
183
|
+
* @internal
|
|
184
|
+
*/
|
|
185
|
+
function getRegistry(stream) {
|
|
186
|
+
return stream[STREAM_CONTROLLER].registry;
|
|
187
|
+
}
|
|
188
|
+
//#endregion
|
|
189
|
+
exports.STREAM_CONTROLLER = STREAM_CONTROLLER;
|
|
190
|
+
exports.getRegistry = getRegistry;
|
|
191
|
+
exports.useStream = useStream;
|
|
192
|
+
|
|
193
|
+
//# sourceMappingURL=use-stream.svelte.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-stream.svelte.cjs","names":["ClientCtor","StreamController"],"sources":["../src/use-stream.svelte.ts"],"sourcesContent":["import { onDestroy } from \"svelte\";\nimport type { BaseMessage } from \"@langchain/core/messages\";\nimport type { Client, Interrupt } from \"@langchain/langgraph-sdk\";\nimport {\n flushPendingHeadlessToolInterrupts,\n type AnyHeadlessToolImplementation,\n type OnToolCallback,\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 AssembledToolCall,\n type ChannelRegistry,\n type CustomAdapterOptions as StreamCustomAdapterOptions,\n type InferStateType,\n type InferSubagentStates,\n type RootSnapshot,\n type StateOf as StreamStateOf,\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\n/** @deprecated Prefer {@link InferStateType}. */\nexport type StateOf<T> = StreamStateOf<T>;\n\n/**\n * A value that may be either a plain `T` or a getter `() => T`. Used\n * for reactive-capable option inputs (currently `threadId` only). When\n * a getter is passed the composable tracks it via `$effect` and\n * re-hydrates when the returned value changes.\n */\nexport type ValueOrGetter<T> = T | (() => T);\n\nfunction readValueOrGetter<T>(\n input: ValueOrGetter<T> | undefined\n): T | undefined {\n if (typeof input === \"function\") return (input as () => T)();\n return input;\n}\n\ntype SvelteThreadId = ValueOrGetter<string | null | undefined>;\n\nexport type AgentServerOptions<StateType extends object> =\n StreamAgentServerOptions<StateType, SvelteThreadId>;\n\nexport type CustomAdapterOptions<StateType extends object> =\n StreamCustomAdapterOptions<StateType, SvelteThreadId, string>;\n\nexport type UseStreamOptions<\n StateType extends object = Record<string, unknown>,\n> = StreamUseStreamOptions<\n StateType,\n SvelteThreadId,\n string | undefined,\n string | undefined,\n string\n>;\n\n/**\n * Private field on the handle that carries the {@link StreamController}\n * reference. Selector composables read this to reach the shared\n * {@link ChannelRegistry}. Use the selector composables\n * (`useMessages`, `useToolCalls`, `useValues`, …) instead of reading\n * this directly.\n */\nexport const STREAM_CONTROLLER: unique symbol = Symbol.for(\n \"@langchain/svelte/controller\"\n);\n\n/**\n * Svelte binding return type for {@link useStream}. Reactive\n * projections are exposed as getters on a stable object so templates\n * can read `stream.messages` directly without a `.value` / `.current`\n * hop and `$derived` wrappers auto-track the getter read.\n *\n * Destructuring (`const { messages } = stream`) breaks reactivity —\n * this is a Svelte 5 constraint and applies to every getter-object\n * pattern. Access fields through the live `stream` handle instead.\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 readonly values: StateType;\n readonly messages: BaseMessage[];\n readonly toolCalls: AssembledToolCall[];\n readonly interrupts: Interrupt<InterruptType>[];\n readonly interrupt: Interrupt<InterruptType> | undefined;\n readonly isLoading: boolean;\n readonly isThreadLoading: boolean;\n readonly error: unknown;\n readonly threadId: string | null;\n /**\n * Promise that settles when the current thread's initial hydration\n * completes. Useful in SvelteKit `load()` handlers (or any\n * async-init site) to block until the controller has reconciled\n * with server-held state.\n */\n readonly hydrationPromise: Promise<void>;\n\n readonly subagents: ReadonlyMap<\n keyof SubagentStates & string extends never\n ? string\n : keyof SubagentStates & string,\n SubagentDiscoverySnapshot\n >;\n readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;\n readonly subgraphsByNode: ReadonlyMap<\n string,\n readonly SubgraphDiscoverySnapshot[]\n >;\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 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 composables. */\n readonly [STREAM_CONTROLLER]: StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >;\n}\n\n/**\n * Erased handle useful as a parameter type for helpers and wrapper\n * components that pass a `stream` through to selector composables\n * without reading `values` directly. Mirrors the React\n * `AnyStream` alias.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyStream = UseStreamReturn<any, any, any>;\n\n/**\n * Svelte 5 binding for the v2-native stream runtime.\n *\n * Returns a handle whose reactive fields are plain getters on a\n * stable object — templates can read `stream.messages` directly and\n * `$derived(stream.isLoading)` auto-tracks the getter.\n *\n * @example\n * ```svelte\n * <script lang=\"ts\">\n * import { useStream } from \"@langchain/svelte\";\n *\n * const stream = useStream({\n * assistantId: \"agent\",\n * apiUrl: \"http://localhost:2024\",\n * });\n * </script>\n *\n * {#each stream.messages as msg (msg.id)}\n * <div>{msg.content}</div>\n * {/each}\n * <button onclick={() =>\n * stream.submit({ messages: [{ type: \"human\", content: \"Hi\" }] })\n * }>\n * Send\n * </button>\n * ```\n *\n * `assistantId`, `client`, and `transport` are captured at composable\n * init. To bind a new assistant/transport, remount the component.\n * Only `threadId` is treated as reactive — pass it as a getter\n * (`threadId: () => active`) to drive an in-place thread swap.\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\n interface OptionsBag {\n assistantId?: string;\n threadId?: ValueOrGetter<string | null | undefined>;\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?: (meta: { run_id: string; thread_id: string }) => void;\n initialValues?: StateType;\n messagesKey?: string;\n tools?: AnyHeadlessToolImplementation[];\n onTool?: OnToolCallback;\n }\n const asBag = options as OptionsBag;\n\n const hasCustomAdapter =\n asBag.transport != null && typeof asBag.transport !== \"string\";\n const transport = asBag.transport;\n\n // Client construction — captured once at init. Consumers that need\n // to swap `apiUrl`/`apiKey` at runtime remount the owning component.\n const client: Client =\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 // Custom adapters may omit `assistantId`; the controller still\n // requires one so it has something to forward to `threads.stream`.\n const sentinel = \"_\";\n const assistantId =\n \"assistantId\" in options ? (options.assistantId ?? sentinel) : sentinel;\n\n const initialThreadId = readValueOrGetter(asBag.threadId) ?? null;\n\n // Plain `let` binding, not `$state`: the controller holds maps of\n // listeners, Promises, and the live `ThreadStream`, none of which\n // survive Svelte's deep `$state` proxy wrapping.\n const controller = new StreamController<\n StateType,\n InterruptType,\n ConfigurableType\n >({\n assistantId,\n // `Client` is state-shape agnostic at runtime; the controller\n // advertises `Client<StateType>` on its public type for ergonomics.\n client: client as unknown as Client<StateType>,\n threadId: initialThreadId,\n transport,\n fetch: hasCustomAdapter ? undefined : asBag.fetch,\n webSocketFactory: hasCustomAdapter ? undefined : asBag.webSocketFactory,\n onThreadId: options.onThreadId,\n onCreated: options.onCreated,\n initialValues: options.initialValues,\n messagesKey: options.messagesKey,\n });\n\n // Deferred dispose: mirrors React's activate/dispose pattern so HMR\n // and other scope-reuse scenarios stay clean. `activate()` cancels\n // a pending dispose if the owning scope survives.\n const deactivate = controller.activate();\n onDestroy(deactivate);\n\n // ─── Reactive state bridges ─────────────────────────────────────────\n //\n // Each always-on `StreamStore` is wrapped in a runes `$state` slot\n // seeded from `getSnapshot()` and kept in sync via `store.subscribe`.\n // Subscriptions are torn down on component destroy.\n let rootSnapshot = $state<RootSnapshot<StateType, InterruptType>>(\n controller.rootStore.getSnapshot()\n );\n const unsubscribeRoot = controller.rootStore.subscribe(() => {\n rootSnapshot = controller.rootStore.getSnapshot();\n });\n onDestroy(unsubscribeRoot);\n\n let subagentSnapshot = $state<SubagentMap>(\n controller.subagentStore.getSnapshot()\n );\n const unsubscribeSubagents = controller.subagentStore.subscribe(() => {\n subagentSnapshot = controller.subagentStore.getSnapshot();\n });\n onDestroy(unsubscribeSubagents);\n\n let subgraphSnapshot = $state<SubgraphMap>(\n controller.subgraphStore.getSnapshot()\n );\n const unsubscribeSubgraphs = controller.subgraphStore.subscribe(() => {\n subgraphSnapshot = controller.subgraphStore.getSnapshot();\n });\n onDestroy(unsubscribeSubgraphs);\n\n let subgraphByNodeSnapshot = $state<SubgraphByNodeMap>(\n controller.subgraphByNodeStore.getSnapshot()\n );\n const unsubscribeSubgraphByNode = controller.subgraphByNodeStore.subscribe(\n () => {\n subgraphByNodeSnapshot = controller.subgraphByNodeStore.getSnapshot();\n }\n );\n onDestroy(unsubscribeSubgraphByNode);\n\n // ─── threadId reactivity ────────────────────────────────────────────\n //\n // Only matters when the caller passed a getter. The initial hydrate\n // already fired in the controller constructor, so skip the first\n // tick to avoid a redundant `thread.state.get()`.\n if (typeof asBag.threadId === \"function\") {\n const getThreadId = asBag.threadId;\n let previousThreadId = initialThreadId;\n $effect(() => {\n const next = (getThreadId() ?? null) as string | null;\n if (next === previousThreadId) return;\n previousThreadId = next;\n void controller.hydrate(next);\n });\n }\n\n // ─── Headless-tool handling ─────────────────────────────────────────\n //\n // Watch the root `values.__interrupt__` key plus the protocol-\n // surfaced interrupts for items targeting a registered tool, invoke\n // the handler, and resume the run with the handler's return value.\n // Dedup via an id set so rerenders don't replay a tool call twice.\n const tools = options.tools;\n const onTool = options.onTool;\n if (tools?.length) {\n const handledTools = new Set<string>();\n let handledForThreadId: string | null = initialThreadId;\n $effect(() => {\n // Reset dedup set when the active thread id changes — a fresh\n // thread may legitimately re-emit a tool-call id we've seen.\n const currentThreadId = rootSnapshot.threadId;\n if (currentThreadId !== handledForThreadId) {\n handledTools.clear();\n handledForThreadId = currentThreadId;\n }\n\n const valuesBag = rootSnapshot.values as unknown as Record<\n string,\n unknown\n >;\n const existing = Array.isArray(valuesBag?.__interrupt__)\n ? (valuesBag.__interrupt__ as Interrupt[])\n : [];\n const combined: Interrupt[] = [\n ...existing,\n ...(rootSnapshot.interrupts as unknown as Interrupt[]),\n ];\n if (combined.length === 0) return;\n flushPendingHeadlessToolInterrupts(\n { ...valuesBag, __interrupt__: combined },\n tools,\n handledTools,\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 });\n }\n\n // ─── Public handle ──────────────────────────────────────────────────\n //\n // Single stable object with getters. Getters read the runes\n // `$state` slots, which drives template reactivity automatically.\n const handle: UseStreamReturn<T, InterruptType, ConfigurableType> = {\n get values() {\n return rootSnapshot.values;\n },\n get messages() {\n return rootSnapshot.messages;\n },\n get toolCalls() {\n return rootSnapshot.toolCalls;\n },\n get interrupts() {\n return rootSnapshot.interrupts;\n },\n get interrupt() {\n return rootSnapshot.interrupt;\n },\n get isLoading() {\n return rootSnapshot.isLoading;\n },\n get isThreadLoading() {\n return rootSnapshot.isThreadLoading;\n },\n get error() {\n return rootSnapshot.error;\n },\n get threadId() {\n return rootSnapshot.threadId;\n },\n get hydrationPromise() {\n return controller.hydrationPromise;\n },\n get subagents() {\n return subagentSnapshot as UseStreamReturn<\n T,\n InterruptType,\n ConfigurableType\n >[\"subagents\"];\n },\n get subgraphs() {\n return subgraphSnapshot;\n },\n get subgraphsByNode() {\n return subgraphByNodeSnapshot;\n },\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 };\n\n return handle;\n}\n\n/** Convenience alias for the fully-resolved stream handle type. */\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 composables to reach the underlying\n * {@link ChannelRegistry} from a stream handle. Kept internal —\n * application code should call `useMessages`, `useToolCalls`, etc.\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":";;;;;AA6CA,SAAS,kBACP,OACe;AACf,KAAI,OAAO,UAAU,WAAY,QAAQ,OAAmB;AAC5D,QAAO;;;;;;;;;AA4BT,MAAa,oBAAmC,OAAO,IACrD,+BACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkHD,SAAgB,UAKd,SACqD;CAqBrD,MAAM,QAAQ;CAEd,MAAM,mBACJ,MAAM,aAAa,QAAQ,OAAO,MAAM,cAAc;CACxD,MAAM,YAAY,MAAM;CAIxB,MAAM,SACJ,MAAM,UACL,IAAIA,gCAAAA,OAAW;EACd,QAAQ,MAAM;EACd,QAAQ,MAAM;EACd,eAAe,MA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nE,iBAAiB,WAAW,WAAW;EACvC;EACA;GACC,oBAAoB;EACtB;;;;;;;;;AAmBH,SAAgB,YAEd,QACiB;AACjB,QAAO,OAAO,mBAAmB"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { BaseMessage } from "@langchain/core/messages";
|
|
2
|
+
import { Client, Interrupt } from "@langchain/langgraph-sdk";
|
|
3
|
+
import { ThreadStream } from "@langchain/langgraph-sdk/client";
|
|
4
|
+
import { AgentServerOptions, AssembledToolCall, ChannelRegistry, CustomAdapterOptions, InferStateType, InferSubagentStates, StateOf, StreamController, StreamSubmitOptions, SubagentDiscoverySnapshot, SubgraphDiscoverySnapshot, UseStreamOptions, WidenUpdateMessages } from "@langchain/langgraph-sdk/stream";
|
|
5
|
+
|
|
6
|
+
//#region src/use-stream.svelte.d.ts
|
|
7
|
+
/** @deprecated Prefer {@link InferStateType}. */
|
|
8
|
+
type StateOf$1<T> = StateOf<T>;
|
|
9
|
+
/**
|
|
10
|
+
* A value that may be either a plain `T` or a getter `() => T`. Used
|
|
11
|
+
* for reactive-capable option inputs (currently `threadId` only). When
|
|
12
|
+
* a getter is passed the composable tracks it via `$effect` and
|
|
13
|
+
* re-hydrates when the returned value changes.
|
|
14
|
+
*/
|
|
15
|
+
type ValueOrGetter<T> = T | (() => T);
|
|
16
|
+
type SvelteThreadId = ValueOrGetter<string | null | undefined>;
|
|
17
|
+
type AgentServerOptions$1<StateType extends object> = AgentServerOptions<StateType, SvelteThreadId>;
|
|
18
|
+
type CustomAdapterOptions$1<StateType extends object> = CustomAdapterOptions<StateType, SvelteThreadId, string>;
|
|
19
|
+
type UseStreamOptions$1<StateType extends object = Record<string, unknown>> = UseStreamOptions<StateType, SvelteThreadId, string | undefined, string | undefined, string>;
|
|
20
|
+
/**
|
|
21
|
+
* Private field on the handle that carries the {@link StreamController}
|
|
22
|
+
* reference. Selector composables read this to reach the shared
|
|
23
|
+
* {@link ChannelRegistry}. Use the selector composables
|
|
24
|
+
* (`useMessages`, `useToolCalls`, `useValues`, …) instead of reading
|
|
25
|
+
* this directly.
|
|
26
|
+
*/
|
|
27
|
+
declare const STREAM_CONTROLLER: unique symbol;
|
|
28
|
+
/**
|
|
29
|
+
* Svelte binding return type for {@link useStream}. Reactive
|
|
30
|
+
* projections are exposed as getters on a stable object so templates
|
|
31
|
+
* can read `stream.messages` directly without a `.value` / `.current`
|
|
32
|
+
* hop and `$derived` wrappers auto-track the getter read.
|
|
33
|
+
*
|
|
34
|
+
* Destructuring (`const { messages } = stream`) breaks reactivity —
|
|
35
|
+
* this is a Svelte 5 constraint and applies to every getter-object
|
|
36
|
+
* pattern. Access fields through the live `stream` handle instead.
|
|
37
|
+
*/
|
|
38
|
+
interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>, StateType extends object = InferStateType<T>, SubagentStates = InferSubagentStates<T>> {
|
|
39
|
+
readonly values: StateType;
|
|
40
|
+
readonly messages: BaseMessage[];
|
|
41
|
+
readonly toolCalls: AssembledToolCall[];
|
|
42
|
+
readonly interrupts: Interrupt<InterruptType>[];
|
|
43
|
+
readonly interrupt: Interrupt<InterruptType> | undefined;
|
|
44
|
+
readonly isLoading: boolean;
|
|
45
|
+
readonly isThreadLoading: boolean;
|
|
46
|
+
readonly error: unknown;
|
|
47
|
+
readonly threadId: string | null;
|
|
48
|
+
/**
|
|
49
|
+
* Promise that settles when the current thread's initial hydration
|
|
50
|
+
* completes. Useful in SvelteKit `load()` handlers (or any
|
|
51
|
+
* async-init site) to block until the controller has reconciled
|
|
52
|
+
* with server-held state.
|
|
53
|
+
*/
|
|
54
|
+
readonly hydrationPromise: Promise<void>;
|
|
55
|
+
readonly subagents: ReadonlyMap<keyof SubagentStates & string extends never ? string : keyof SubagentStates & string, SubagentDiscoverySnapshot>;
|
|
56
|
+
readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;
|
|
57
|
+
readonly subgraphsByNode: ReadonlyMap<string, readonly SubgraphDiscoverySnapshot[]>;
|
|
58
|
+
submit(input: WidenUpdateMessages<Partial<StateType>> | null | undefined, options?: StreamSubmitOptions<StateType, ConfigurableType>): Promise<void>;
|
|
59
|
+
stop(): Promise<void>;
|
|
60
|
+
respond(response: unknown, target?: {
|
|
61
|
+
interruptId: string;
|
|
62
|
+
namespace?: string[];
|
|
63
|
+
}): Promise<void>;
|
|
64
|
+
readonly client: Client;
|
|
65
|
+
readonly assistantId: string;
|
|
66
|
+
/** v2 escape hatch — returns the bound {@link ThreadStream}. */
|
|
67
|
+
getThread(): ThreadStream | undefined;
|
|
68
|
+
/** @internal Used by selector composables. */
|
|
69
|
+
readonly [STREAM_CONTROLLER]: StreamController<StateType, InterruptType, ConfigurableType>;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Erased handle useful as a parameter type for helpers and wrapper
|
|
73
|
+
* components that pass a `stream` through to selector composables
|
|
74
|
+
* without reading `values` directly. Mirrors the React
|
|
75
|
+
* `AnyStream` alias.
|
|
76
|
+
*/
|
|
77
|
+
type AnyStream = UseStreamReturn<any, any, any>;
|
|
78
|
+
/**
|
|
79
|
+
* Svelte 5 binding for the v2-native stream runtime.
|
|
80
|
+
*
|
|
81
|
+
* Returns a handle whose reactive fields are plain getters on a
|
|
82
|
+
* stable object — templates can read `stream.messages` directly and
|
|
83
|
+
* `$derived(stream.isLoading)` auto-tracks the getter.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```svelte
|
|
87
|
+
* <script lang="ts">
|
|
88
|
+
* import { useStream } from "@langchain/svelte";
|
|
89
|
+
*
|
|
90
|
+
* const stream = useStream({
|
|
91
|
+
* assistantId: "agent",
|
|
92
|
+
* apiUrl: "http://localhost:2024",
|
|
93
|
+
* });
|
|
94
|
+
* </script>
|
|
95
|
+
*
|
|
96
|
+
* {#each stream.messages as msg (msg.id)}
|
|
97
|
+
* <div>{msg.content}</div>
|
|
98
|
+
* {/each}
|
|
99
|
+
* <button onclick={() =>
|
|
100
|
+
* stream.submit({ messages: [{ type: "human", content: "Hi" }] })
|
|
101
|
+
* }>
|
|
102
|
+
* Send
|
|
103
|
+
* </button>
|
|
104
|
+
* ```
|
|
105
|
+
*
|
|
106
|
+
* `assistantId`, `client`, and `transport` are captured at composable
|
|
107
|
+
* init. To bind a new assistant/transport, remount the component.
|
|
108
|
+
* Only `threadId` is treated as reactive — pass it as a getter
|
|
109
|
+
* (`threadId: () => active`) to drive an in-place thread swap.
|
|
110
|
+
*/
|
|
111
|
+
declare function useStream<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>>(options: UseStreamOptions$1<InferStateType<T>>): UseStreamReturn<T, InterruptType, ConfigurableType>;
|
|
112
|
+
/** Convenience alias for the fully-resolved stream handle type. */
|
|
113
|
+
type UseStreamResult<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>> = UseStreamReturn<T, InterruptType, ConfigurableType>;
|
|
114
|
+
//#endregion
|
|
115
|
+
export { AgentServerOptions$1 as AgentServerOptions, AnyStream, CustomAdapterOptions$1 as CustomAdapterOptions, STREAM_CONTROLLER, StateOf$1 as StateOf, type ThreadStream, UseStreamOptions$1 as UseStreamOptions, UseStreamResult, UseStreamReturn, useStream };
|
|
116
|
+
//# sourceMappingURL=use-stream.svelte.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-stream.svelte.d.cts","names":[],"sources":["../src/use-stream.svelte.ts"],"mappings":";;;;;;;KAmCY,SAAA,MAAa,OAAA,CAAc,CAAA;AAAvC;;;;;;AAAA,KAQY,aAAA,MAAmB,CAAA,UAAW,CAAA;AAAA,KASrC,cAAA,GAAiB,aAAA;AAAA,KAEV,oBAAA,6BACV,kBAAA,CAAyB,SAAA,EAAW,cAAA;AAAA,KAE1B,sBAAA,6BACV,oBAAA,CAA2B,SAAA,EAAW,cAAA;AAAA,KAE5B,kBAAA,4BACiB,MAAA,qBACzB,gBAAA,CACF,SAAA,EACA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,KACN,MAAA,8EAE8B,MAAA,qBAChC,eAAA,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { Client, Interrupt } from "@langchain/langgraph-sdk";
|
|
2
|
+
import { ThreadStream } from "@langchain/langgraph-sdk/client";
|
|
3
|
+
import { AgentServerOptions, AssembledToolCall, ChannelRegistry, CustomAdapterOptions, InferStateType, InferSubagentStates, StateOf, StreamController, StreamSubmitOptions, SubagentDiscoverySnapshot, SubgraphDiscoverySnapshot, UseStreamOptions, WidenUpdateMessages } from "@langchain/langgraph-sdk/stream";
|
|
4
|
+
import { BaseMessage } from "@langchain/core/messages";
|
|
5
|
+
|
|
6
|
+
//#region src/use-stream.svelte.d.ts
|
|
7
|
+
/** @deprecated Prefer {@link InferStateType}. */
|
|
8
|
+
type StateOf$1<T> = StateOf<T>;
|
|
9
|
+
/**
|
|
10
|
+
* A value that may be either a plain `T` or a getter `() => T`. Used
|
|
11
|
+
* for reactive-capable option inputs (currently `threadId` only). When
|
|
12
|
+
* a getter is passed the composable tracks it via `$effect` and
|
|
13
|
+
* re-hydrates when the returned value changes.
|
|
14
|
+
*/
|
|
15
|
+
type ValueOrGetter<T> = T | (() => T);
|
|
16
|
+
type SvelteThreadId = ValueOrGetter<string | null | undefined>;
|
|
17
|
+
type AgentServerOptions$1<StateType extends object> = AgentServerOptions<StateType, SvelteThreadId>;
|
|
18
|
+
type CustomAdapterOptions$1<StateType extends object> = CustomAdapterOptions<StateType, SvelteThreadId, string>;
|
|
19
|
+
type UseStreamOptions$1<StateType extends object = Record<string, unknown>> = UseStreamOptions<StateType, SvelteThreadId, string | undefined, string | undefined, string>;
|
|
20
|
+
/**
|
|
21
|
+
* Private field on the handle that carries the {@link StreamController}
|
|
22
|
+
* reference. Selector composables read this to reach the shared
|
|
23
|
+
* {@link ChannelRegistry}. Use the selector composables
|
|
24
|
+
* (`useMessages`, `useToolCalls`, `useValues`, …) instead of reading
|
|
25
|
+
* this directly.
|
|
26
|
+
*/
|
|
27
|
+
declare const STREAM_CONTROLLER: unique symbol;
|
|
28
|
+
/**
|
|
29
|
+
* Svelte binding return type for {@link useStream}. Reactive
|
|
30
|
+
* projections are exposed as getters on a stable object so templates
|
|
31
|
+
* can read `stream.messages` directly without a `.value` / `.current`
|
|
32
|
+
* hop and `$derived` wrappers auto-track the getter read.
|
|
33
|
+
*
|
|
34
|
+
* Destructuring (`const { messages } = stream`) breaks reactivity —
|
|
35
|
+
* this is a Svelte 5 constraint and applies to every getter-object
|
|
36
|
+
* pattern. Access fields through the live `stream` handle instead.
|
|
37
|
+
*/
|
|
38
|
+
interface UseStreamReturn<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>, StateType extends object = InferStateType<T>, SubagentStates = InferSubagentStates<T>> {
|
|
39
|
+
readonly values: StateType;
|
|
40
|
+
readonly messages: BaseMessage[];
|
|
41
|
+
readonly toolCalls: AssembledToolCall[];
|
|
42
|
+
readonly interrupts: Interrupt<InterruptType>[];
|
|
43
|
+
readonly interrupt: Interrupt<InterruptType> | undefined;
|
|
44
|
+
readonly isLoading: boolean;
|
|
45
|
+
readonly isThreadLoading: boolean;
|
|
46
|
+
readonly error: unknown;
|
|
47
|
+
readonly threadId: string | null;
|
|
48
|
+
/**
|
|
49
|
+
* Promise that settles when the current thread's initial hydration
|
|
50
|
+
* completes. Useful in SvelteKit `load()` handlers (or any
|
|
51
|
+
* async-init site) to block until the controller has reconciled
|
|
52
|
+
* with server-held state.
|
|
53
|
+
*/
|
|
54
|
+
readonly hydrationPromise: Promise<void>;
|
|
55
|
+
readonly subagents: ReadonlyMap<keyof SubagentStates & string extends never ? string : keyof SubagentStates & string, SubagentDiscoverySnapshot>;
|
|
56
|
+
readonly subgraphs: ReadonlyMap<string, SubgraphDiscoverySnapshot>;
|
|
57
|
+
readonly subgraphsByNode: ReadonlyMap<string, readonly SubgraphDiscoverySnapshot[]>;
|
|
58
|
+
submit(input: WidenUpdateMessages<Partial<StateType>> | null | undefined, options?: StreamSubmitOptions<StateType, ConfigurableType>): Promise<void>;
|
|
59
|
+
stop(): Promise<void>;
|
|
60
|
+
respond(response: unknown, target?: {
|
|
61
|
+
interruptId: string;
|
|
62
|
+
namespace?: string[];
|
|
63
|
+
}): Promise<void>;
|
|
64
|
+
readonly client: Client;
|
|
65
|
+
readonly assistantId: string;
|
|
66
|
+
/** v2 escape hatch — returns the bound {@link ThreadStream}. */
|
|
67
|
+
getThread(): ThreadStream | undefined;
|
|
68
|
+
/** @internal Used by selector composables. */
|
|
69
|
+
readonly [STREAM_CONTROLLER]: StreamController<StateType, InterruptType, ConfigurableType>;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Erased handle useful as a parameter type for helpers and wrapper
|
|
73
|
+
* components that pass a `stream` through to selector composables
|
|
74
|
+
* without reading `values` directly. Mirrors the React
|
|
75
|
+
* `AnyStream` alias.
|
|
76
|
+
*/
|
|
77
|
+
type AnyStream = UseStreamReturn<any, any, any>;
|
|
78
|
+
/**
|
|
79
|
+
* Svelte 5 binding for the v2-native stream runtime.
|
|
80
|
+
*
|
|
81
|
+
* Returns a handle whose reactive fields are plain getters on a
|
|
82
|
+
* stable object — templates can read `stream.messages` directly and
|
|
83
|
+
* `$derived(stream.isLoading)` auto-tracks the getter.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```svelte
|
|
87
|
+
* <script lang="ts">
|
|
88
|
+
* import { useStream } from "@langchain/svelte";
|
|
89
|
+
*
|
|
90
|
+
* const stream = useStream({
|
|
91
|
+
* assistantId: "agent",
|
|
92
|
+
* apiUrl: "http://localhost:2024",
|
|
93
|
+
* });
|
|
94
|
+
* </script>
|
|
95
|
+
*
|
|
96
|
+
* {#each stream.messages as msg (msg.id)}
|
|
97
|
+
* <div>{msg.content}</div>
|
|
98
|
+
* {/each}
|
|
99
|
+
* <button onclick={() =>
|
|
100
|
+
* stream.submit({ messages: [{ type: "human", content: "Hi" }] })
|
|
101
|
+
* }>
|
|
102
|
+
* Send
|
|
103
|
+
* </button>
|
|
104
|
+
* ```
|
|
105
|
+
*
|
|
106
|
+
* `assistantId`, `client`, and `transport` are captured at composable
|
|
107
|
+
* init. To bind a new assistant/transport, remount the component.
|
|
108
|
+
* Only `threadId` is treated as reactive — pass it as a getter
|
|
109
|
+
* (`threadId: () => active`) to drive an in-place thread swap.
|
|
110
|
+
*/
|
|
111
|
+
declare function useStream<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>>(options: UseStreamOptions$1<InferStateType<T>>): UseStreamReturn<T, InterruptType, ConfigurableType>;
|
|
112
|
+
/** Convenience alias for the fully-resolved stream handle type. */
|
|
113
|
+
type UseStreamResult<T = Record<string, unknown>, InterruptType = unknown, ConfigurableType extends object = Record<string, unknown>> = UseStreamReturn<T, InterruptType, ConfigurableType>;
|
|
114
|
+
//#endregion
|
|
115
|
+
export { AgentServerOptions$1 as AgentServerOptions, AnyStream, CustomAdapterOptions$1 as CustomAdapterOptions, STREAM_CONTROLLER, StateOf$1 as StateOf, type ThreadStream, UseStreamOptions$1 as UseStreamOptions, UseStreamResult, UseStreamReturn, useStream };
|
|
116
|
+
//# sourceMappingURL=use-stream.svelte.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-stream.svelte.d.ts","names":[],"sources":["../src/use-stream.svelte.ts"],"mappings":";;;;;;;KAmCY,SAAA,MAAa,OAAA,CAAc,CAAA;AAAvC;;;;;;AAAA,KAQY,aAAA,MAAmB,CAAA,UAAW,CAAA;AAAA,KASrC,cAAA,GAAiB,aAAA;AAAA,KAEV,oBAAA,6BACV,kBAAA,CAAyB,SAAA,EAAW,cAAA;AAAA,KAE1B,sBAAA,6BACV,oBAAA,CAA2B,SAAA,EAAW,cAAA;AAAA,KAE5B,kBAAA,4BACiB,MAAA,qBACzB,gBAAA,CACF,SAAA,EACA,cAAA;;;;;;;;cAaW,iBAAA;;;;;AAvB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,CAAgB,CAAA,EAAG,aAAA,EAAe,gBAAA"}
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { onDestroy } from "svelte";
|
|
2
|
+
import { flushPendingHeadlessToolInterrupts } from "@langchain/langgraph-sdk";
|
|
3
|
+
import { Client as Client$1 } from "@langchain/langgraph-sdk/client";
|
|
4
|
+
import { StreamController } from "@langchain/langgraph-sdk/stream";
|
|
5
|
+
//#region src/use-stream.svelte.ts
|
|
6
|
+
function readValueOrGetter(input) {
|
|
7
|
+
if (typeof input === "function") return input();
|
|
8
|
+
return input;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Private field on the handle that carries the {@link StreamController}
|
|
12
|
+
* reference. Selector composables read this to reach the shared
|
|
13
|
+
* {@link ChannelRegistry}. Use the selector composables
|
|
14
|
+
* (`useMessages`, `useToolCalls`, `useValues`, …) instead of reading
|
|
15
|
+
* this directly.
|
|
16
|
+
*/
|
|
17
|
+
const STREAM_CONTROLLER = Symbol.for("@langchain/svelte/controller");
|
|
18
|
+
/**
|
|
19
|
+
* Svelte 5 binding for the v2-native stream runtime.
|
|
20
|
+
*
|
|
21
|
+
* Returns a handle whose reactive fields are plain getters on a
|
|
22
|
+
* stable object — templates can read `stream.messages` directly and
|
|
23
|
+
* `$derived(stream.isLoading)` auto-tracks the getter.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```svelte
|
|
27
|
+
* <script lang="ts">
|
|
28
|
+
* import { useStream } from "@langchain/svelte";
|
|
29
|
+
*
|
|
30
|
+
* const stream = useStream({
|
|
31
|
+
* assistantId: "agent",
|
|
32
|
+
* apiUrl: "http://localhost:2024",
|
|
33
|
+
* });
|
|
34
|
+
* <\/script>
|
|
35
|
+
*
|
|
36
|
+
* {#each stream.messages as msg (msg.id)}
|
|
37
|
+
* <div>{msg.content}</div>
|
|
38
|
+
* {/each}
|
|
39
|
+
* <button onclick={() =>
|
|
40
|
+
* stream.submit({ messages: [{ type: "human", content: "Hi" }] })
|
|
41
|
+
* }>
|
|
42
|
+
* Send
|
|
43
|
+
* </button>
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* `assistantId`, `client`, and `transport` are captured at composable
|
|
47
|
+
* init. To bind a new assistant/transport, remount the component.
|
|
48
|
+
* Only `threadId` is treated as reactive — pass it as a getter
|
|
49
|
+
* (`threadId: () => active`) to drive an in-place thread swap.
|
|
50
|
+
*/
|
|
51
|
+
function useStream(options) {
|
|
52
|
+
const asBag = options;
|
|
53
|
+
const hasCustomAdapter = asBag.transport != null && typeof asBag.transport !== "string";
|
|
54
|
+
const transport = asBag.transport;
|
|
55
|
+
const client = asBag.client ?? new Client$1({
|
|
56
|
+
apiUrl: asBag.apiUrl,
|
|
57
|
+
apiKey: asBag.apiKey,
|
|
58
|
+
callerOptions: asBag.callerOptions,
|
|
59
|
+
defaultHeaders: asBag.defaultHeaders
|
|
60
|
+
});
|
|
61
|
+
const sentinel = "_";
|
|
62
|
+
const assistantId = "assistantId" in options ? options.assistantId ?? sentinel : sentinel;
|
|
63
|
+
const initialThreadId = readValueOrGetter(asBag.threadId) ?? null;
|
|
64
|
+
const controller = new StreamController({
|
|
65
|
+
assistantId,
|
|
66
|
+
client,
|
|
67
|
+
threadId: initialThreadId,
|
|
68
|
+
transport,
|
|
69
|
+
fetch: hasCustomAdapter ? void 0 : asBag.fetch,
|
|
70
|
+
webSocketFactory: hasCustomAdapter ? void 0 : asBag.webSocketFactory,
|
|
71
|
+
onThreadId: options.onThreadId,
|
|
72
|
+
onCreated: options.onCreated,
|
|
73
|
+
initialValues: options.initialValues,
|
|
74
|
+
messagesKey: options.messagesKey
|
|
75
|
+
});
|
|
76
|
+
onDestroy(controller.activate());
|
|
77
|
+
let rootSnapshot = $state(controller.rootStore.getSnapshot());
|
|
78
|
+
onDestroy(controller.rootStore.subscribe(() => {
|
|
79
|
+
rootSnapshot = controller.rootStore.getSnapshot();
|
|
80
|
+
}));
|
|
81
|
+
let subagentSnapshot = $state(controller.subagentStore.getSnapshot());
|
|
82
|
+
onDestroy(controller.subagentStore.subscribe(() => {
|
|
83
|
+
subagentSnapshot = controller.subagentStore.getSnapshot();
|
|
84
|
+
}));
|
|
85
|
+
let subgraphSnapshot = $state(controller.subgraphStore.getSnapshot());
|
|
86
|
+
onDestroy(controller.subgraphStore.subscribe(() => {
|
|
87
|
+
subgraphSnapshot = controller.subgraphStore.getSnapshot();
|
|
88
|
+
}));
|
|
89
|
+
let subgraphByNodeSnapshot = $state(controller.subgraphByNodeStore.getSnapshot());
|
|
90
|
+
onDestroy(controller.subgraphByNodeStore.subscribe(() => {
|
|
91
|
+
subgraphByNodeSnapshot = controller.subgraphByNodeStore.getSnapshot();
|
|
92
|
+
}));
|
|
93
|
+
if (typeof asBag.threadId === "function") {
|
|
94
|
+
const getThreadId = asBag.threadId;
|
|
95
|
+
let previousThreadId = initialThreadId;
|
|
96
|
+
$effect(() => {
|
|
97
|
+
const next = getThreadId() ?? null;
|
|
98
|
+
if (next === previousThreadId) return;
|
|
99
|
+
previousThreadId = next;
|
|
100
|
+
controller.hydrate(next);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
const tools = options.tools;
|
|
104
|
+
const onTool = options.onTool;
|
|
105
|
+
if (tools?.length) {
|
|
106
|
+
const handledTools = /* @__PURE__ */ new Set();
|
|
107
|
+
let handledForThreadId = initialThreadId;
|
|
108
|
+
$effect(() => {
|
|
109
|
+
const currentThreadId = rootSnapshot.threadId;
|
|
110
|
+
if (currentThreadId !== handledForThreadId) {
|
|
111
|
+
handledTools.clear();
|
|
112
|
+
handledForThreadId = currentThreadId;
|
|
113
|
+
}
|
|
114
|
+
const valuesBag = rootSnapshot.values;
|
|
115
|
+
const combined = [...Array.isArray(valuesBag?.__interrupt__) ? valuesBag.__interrupt__ : [], ...rootSnapshot.interrupts];
|
|
116
|
+
if (combined.length === 0) return;
|
|
117
|
+
flushPendingHeadlessToolInterrupts({
|
|
118
|
+
...valuesBag,
|
|
119
|
+
__interrupt__: combined
|
|
120
|
+
}, tools, handledTools, {
|
|
121
|
+
onTool,
|
|
122
|
+
defer: (run) => {
|
|
123
|
+
Promise.resolve().then(run);
|
|
124
|
+
},
|
|
125
|
+
resumeSubmit: (command) => controller.submit(null, { command })
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
get values() {
|
|
131
|
+
return rootSnapshot.values;
|
|
132
|
+
},
|
|
133
|
+
get messages() {
|
|
134
|
+
return rootSnapshot.messages;
|
|
135
|
+
},
|
|
136
|
+
get toolCalls() {
|
|
137
|
+
return rootSnapshot.toolCalls;
|
|
138
|
+
},
|
|
139
|
+
get interrupts() {
|
|
140
|
+
return rootSnapshot.interrupts;
|
|
141
|
+
},
|
|
142
|
+
get interrupt() {
|
|
143
|
+
return rootSnapshot.interrupt;
|
|
144
|
+
},
|
|
145
|
+
get isLoading() {
|
|
146
|
+
return rootSnapshot.isLoading;
|
|
147
|
+
},
|
|
148
|
+
get isThreadLoading() {
|
|
149
|
+
return rootSnapshot.isThreadLoading;
|
|
150
|
+
},
|
|
151
|
+
get error() {
|
|
152
|
+
return rootSnapshot.error;
|
|
153
|
+
},
|
|
154
|
+
get threadId() {
|
|
155
|
+
return rootSnapshot.threadId;
|
|
156
|
+
},
|
|
157
|
+
get hydrationPromise() {
|
|
158
|
+
return controller.hydrationPromise;
|
|
159
|
+
},
|
|
160
|
+
get subagents() {
|
|
161
|
+
return subagentSnapshot;
|
|
162
|
+
},
|
|
163
|
+
get subgraphs() {
|
|
164
|
+
return subgraphSnapshot;
|
|
165
|
+
},
|
|
166
|
+
get subgraphsByNode() {
|
|
167
|
+
return subgraphByNodeSnapshot;
|
|
168
|
+
},
|
|
169
|
+
submit: (input, submitOptions) => controller.submit(input, submitOptions),
|
|
170
|
+
stop: () => controller.stop(),
|
|
171
|
+
respond: (response, target) => controller.respond(response, target),
|
|
172
|
+
getThread: () => controller.getThread(),
|
|
173
|
+
client,
|
|
174
|
+
assistantId,
|
|
175
|
+
[STREAM_CONTROLLER]: controller
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Helper used by the selector composables to reach the underlying
|
|
180
|
+
* {@link ChannelRegistry} from a stream handle. Kept internal —
|
|
181
|
+
* application code should call `useMessages`, `useToolCalls`, etc.
|
|
182
|
+
*
|
|
183
|
+
* @internal
|
|
184
|
+
*/
|
|
185
|
+
function getRegistry(stream) {
|
|
186
|
+
return stream[STREAM_CONTROLLER].registry;
|
|
187
|
+
}
|
|
188
|
+
//#endregion
|
|
189
|
+
export { STREAM_CONTROLLER, getRegistry, useStream };
|
|
190
|
+
|
|
191
|
+
//# sourceMappingURL=use-stream.svelte.js.map
|