@langchain/angular 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +17 -15
  2. package/dist/context.cjs +6 -52
  3. package/dist/context.cjs.map +1 -1
  4. package/dist/context.d.cts +55 -71
  5. package/dist/context.d.cts.map +1 -1
  6. package/dist/context.d.ts +51 -67
  7. package/dist/context.d.ts.map +1 -1
  8. package/dist/context.js +7 -52
  9. package/dist/context.js.map +1 -1
  10. package/dist/index.cjs +26 -462
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +255 -104
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.ts +254 -103
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +25 -463
  17. package/dist/index.js.map +1 -1
  18. package/dist/node_modules/.pnpm/langchain@1.2.30_@langchain_core@1.1.31_@opentelemetry_api@1.9.0_openai@6.27.0_ws@8.19._0520fb05d9e85da5f9e061dfe28cdbc8/node_modules/langchain/dist/index.d.cts +2 -2
  19. package/dist/node_modules/.pnpm/langchain@1.2.30_@langchain_core@1.1.31_@opentelemetry_api@1.9.0_openai@6.27.0_ws@8.19._0520fb05d9e85da5f9e061dfe28cdbc8/node_modules/langchain/dist/index.d.ts +2 -2
  20. package/dist/stream-service-instance.d.cts +70 -0
  21. package/dist/stream-service-instance.d.cts.map +1 -0
  22. package/dist/stream-service-instance.d.ts +70 -0
  23. package/dist/stream-service-instance.d.ts.map +1 -0
  24. package/dist/stream.custom.cjs +59 -161
  25. package/dist/stream.custom.cjs.map +1 -1
  26. package/dist/stream.custom.d.cts +45 -0
  27. package/dist/stream.custom.d.cts.map +1 -0
  28. package/dist/stream.custom.d.ts +45 -0
  29. package/dist/stream.custom.d.ts.map +1 -0
  30. package/dist/stream.custom.js +60 -163
  31. package/dist/stream.custom.js.map +1 -1
  32. package/dist/stream.lgp.cjs +163 -0
  33. package/dist/stream.lgp.cjs.map +1 -0
  34. package/dist/stream.lgp.d.cts +57 -0
  35. package/dist/stream.lgp.d.cts.map +1 -0
  36. package/dist/stream.lgp.d.ts +57 -0
  37. package/dist/stream.lgp.d.ts.map +1 -0
  38. package/dist/stream.lgp.js +163 -0
  39. package/dist/stream.lgp.js.map +1 -0
  40. package/package.json +3 -3
package/dist/context.js CHANGED
@@ -1,4 +1,5 @@
1
- import { useStream } from "./index.js";
1
+ import { injectStreamCustom } from "./stream.custom.js";
2
+ import { useStreamLGP } from "./stream.lgp.js";
2
3
  import { InjectionToken, inject, makeEnvironmentProviders } from "@angular/core";
3
4
  //#region src/context.ts
4
5
  /**
@@ -76,64 +77,18 @@ function provideStream(options) {
76
77
  provide: STREAM_INSTANCE,
77
78
  useFactory: () => {
78
79
  const defaults = inject(STREAM_DEFAULTS, { optional: true });
79
- return useStream({
80
+ const merged = {
80
81
  ...defaults ?? {},
81
82
  ...options,
82
83
  apiUrl: options.apiUrl ?? defaults?.apiUrl,
83
84
  client: options.client ?? defaults?.client
84
- });
85
+ };
86
+ if ("transport" in merged) return injectStreamCustom(merged);
87
+ return useStreamLGP(merged);
85
88
  }
86
89
  };
87
90
  }
88
- /**
89
- * Injects the shared stream instance from the nearest ancestor that
90
- * provided one via `provideStream()`.
91
- *
92
- * Throws if no ancestor provides a stream instance.
93
- *
94
- * @example
95
- * ```typescript
96
- * import { Component } from "@angular/core";
97
- * import { injectStream } from "@langchain/angular";
98
- *
99
- * @Component({
100
- * template: `
101
- * @for (msg of stream.messages(); track msg.id) {
102
- * <div>{{ msg.content }}</div>
103
- * }
104
- * <button
105
- * [disabled]="stream.isLoading()"
106
- * (click)="onSubmit()"
107
- * >Send</button>
108
- * `,
109
- * })
110
- * export class ChatComponent {
111
- * stream = injectStream();
112
- *
113
- * onSubmit() {
114
- * void this.stream.submit({
115
- * messages: [{ type: "human", content: "Hello!" }],
116
- * });
117
- * }
118
- * }
119
- * ```
120
- *
121
- * @example With type parameters for full type safety:
122
- * ```typescript
123
- * import type { agent } from "./agent";
124
- *
125
- * export class ChatComponent {
126
- * stream = injectStream<typeof agent>();
127
- * // stream.messages() returns typed messages
128
- * }
129
- * ```
130
- */
131
- function injectStream() {
132
- const instance = inject(STREAM_INSTANCE, { optional: true });
133
- if (instance == null) throw new Error("injectStream() requires an ancestor component to provide a stream via provideStream(). Add provideStream({ assistantId: '...' }) to the providers array of a parent component, or use useStream() directly.");
134
- return instance;
135
- }
136
91
  //#endregion
137
- export { STREAM_DEFAULTS, STREAM_INSTANCE, injectStream, provideStream, provideStreamDefaults };
92
+ export { STREAM_DEFAULTS, STREAM_INSTANCE, provideStream, provideStreamDefaults };
138
93
 
139
94
  //# sourceMappingURL=context.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":["angularInject"],"sources":["../src/context.ts"],"sourcesContent":["import {\n InjectionToken,\n inject as angularInject,\n type EnvironmentProviders,\n makeEnvironmentProviders,\n} from \"@angular/core\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { Client } from \"@langchain/langgraph-sdk\";\nimport type {\n ResolveStreamOptions,\n InferBag,\n InferStateType,\n UseStreamCustomOptions,\n} from \"@langchain/langgraph-sdk/ui\";\nimport { useStream } from \"./index.js\";\n\n/**\n * Configuration defaults for `useStream` and `injectStream` calls.\n */\nexport interface StreamDefaults {\n /** Base URL of the LangGraph API. */\n apiUrl?: string;\n /** API key for authenticating with the LangGraph API. */\n apiKey?: string;\n /** Pre-configured Client instance. */\n client?: Client;\n}\n\n/**\n * Injection token for stream default configuration.\n * Provide via `provideStreamDefaults()` in your application config.\n */\nexport const STREAM_DEFAULTS = new InjectionToken<StreamDefaults>(\n \"LANGCHAIN_STREAM_DEFAULTS\",\n);\n\n/**\n * Injection token for a shared stream instance.\n * Provide via `provideStream()` at the component level.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport const STREAM_INSTANCE = new InjectionToken<any>(\n \"LANGCHAIN_STREAM_INSTANCE\",\n);\n\n/**\n * Provides default LangGraph configuration at the application level.\n *\n * Use this in your application's `providers` array to set defaults like\n * `apiUrl` that will be used by all `useStream` and `injectStream` calls.\n *\n * @example\n * ```typescript\n * // app.config.ts\n * import { ApplicationConfig } from \"@angular/core\";\n * import { provideStreamDefaults } from \"@langchain/angular\";\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [\n * provideStreamDefaults({\n * apiUrl: \"http://localhost:2024\",\n * }),\n * ],\n * };\n * ```\n */\nexport function provideStreamDefaults(\n defaults: StreamDefaults,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: STREAM_DEFAULTS, useValue: defaults },\n ]);\n}\n\n/**\n * Creates a provider for a shared `useStream` instance at the component level.\n *\n * Add the returned provider to a component's `providers` array so that all\n * child components can access the same stream via `injectStream()`.\n *\n * @example\n * ```typescript\n * import { Component } from \"@angular/core\";\n * import { provideStream, injectStream } from \"@langchain/angular\";\n *\n * @Component({\n * providers: [provideStream({ assistantId: \"agent\" })],\n * template: `\n * <app-message-list />\n * <app-message-input />\n * `,\n * })\n * export class ChatContainer {}\n *\n * // In child components:\n * @Component({\n * template: `\n * @for (msg of stream.messages(); track msg.id) {\n * <div>{{ msg.content }}</div>\n * }\n * `,\n * })\n * export class MessageListComponent {\n * stream = injectStream();\n * }\n * ```\n */\nexport function provideStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options:\n | ResolveStreamOptions<T, InferBag<T, Bag>>\n | UseStreamCustomOptions<InferStateType<T>, InferBag<T, Bag>>,\n) {\n return {\n provide: STREAM_INSTANCE,\n useFactory: () => {\n const defaults = angularInject(STREAM_DEFAULTS, { optional: true });\n const merged = {\n ...(defaults ?? {}),\n ...options,\n apiUrl: (options as Record<string, unknown>).apiUrl ?? defaults?.apiUrl,\n client: (options as Record<string, unknown>).client ?? defaults?.client,\n };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return useStream(merged as any);\n },\n };\n}\n\n/**\n * Injects the shared stream instance from the nearest ancestor that\n * provided one via `provideStream()`.\n *\n * Throws if no ancestor provides a stream instance.\n *\n * @example\n * ```typescript\n * import { Component } from \"@angular/core\";\n * import { injectStream } from \"@langchain/angular\";\n *\n * @Component({\n * template: `\n * @for (msg of stream.messages(); track msg.id) {\n * <div>{{ msg.content }}</div>\n * }\n * <button\n * [disabled]=\"stream.isLoading()\"\n * (click)=\"onSubmit()\"\n * >Send</button>\n * `,\n * })\n * export class ChatComponent {\n * stream = injectStream();\n *\n * onSubmit() {\n * void this.stream.submit({\n * messages: [{ type: \"human\", content: \"Hello!\" }],\n * });\n * }\n * }\n * ```\n *\n * @example With type parameters for full type safety:\n * ```typescript\n * import type { agent } from \"./agent\";\n *\n * export class ChatComponent {\n * stream = injectStream<typeof agent>();\n * // stream.messages() returns typed messages\n * }\n * ```\n */\nexport function injectStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(): ReturnType<typeof useStream<T, Bag>> {\n const instance = angularInject(STREAM_INSTANCE, { optional: true });\n if (instance == null) {\n throw new Error(\n \"injectStream() requires an ancestor component to provide a stream via provideStream(). \" +\n \"Add provideStream({ assistantId: '...' }) to the providers array of a parent component, \" +\n \"or use useStream() directly.\",\n );\n }\n return instance;\n}\n"],"mappings":";;;;;;;AAgCA,MAAa,kBAAkB,IAAI,eACjC,4BACD;;;;;AAOD,MAAa,kBAAkB,IAAI,eACjC,4BACD;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,sBACd,UACsB;AACtB,QAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAiB,UAAU;EAAU,CACjD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCJ,SAAgB,cAId,SAGA;AACA,QAAO;EACL,SAAS;EACT,kBAAkB;GAChB,MAAM,WAAWA,OAAc,iBAAiB,EAAE,UAAU,MAAM,CAAC;AAQnE,UAAO,UAPQ;IACb,GAAI,YAAY,EAAE;IAClB,GAAG;IACH,QAAS,QAAoC,UAAU,UAAU;IACjE,QAAS,QAAoC,UAAU,UAAU;IAClE,CAE8B;;EAElC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CH,SAAgB,eAG0B;CACxC,MAAM,WAAWA,OAAc,iBAAiB,EAAE,UAAU,MAAM,CAAC;AACnE,KAAI,YAAY,KACd,OAAM,IAAI,MACR,8MAGD;AAEH,QAAO"}
1
+ {"version":3,"file":"context.js","names":["angularInject"],"sources":["../src/context.ts"],"sourcesContent":["import {\n InjectionToken,\n inject as angularInject,\n type EnvironmentProviders,\n makeEnvironmentProviders,\n} from \"@angular/core\";\nimport type { BagTemplate } from \"@langchain/langgraph-sdk\";\nimport { Client } from \"@langchain/langgraph-sdk\";\nimport type {\n ResolveStreamOptions,\n InferBag,\n InferStateType,\n UseStreamCustomOptions,\n} from \"@langchain/langgraph-sdk/ui\";\nimport type { StreamServiceInstance } from \"./stream-service-instance.js\";\nimport { useStreamLGP } from \"./stream.lgp.js\";\nimport { injectStreamCustom } from \"./stream.custom.js\";\n\n/**\n * Configuration defaults for `useStream` and `injectStream` calls.\n */\nexport interface StreamDefaults {\n /** Base URL of the LangGraph API. */\n apiUrl?: string;\n /** API key for authenticating with the LangGraph API. */\n apiKey?: string;\n /** Pre-configured Client instance. */\n client?: Client;\n}\n\n/**\n * Injection token for stream default configuration.\n * Provide via `provideStreamDefaults()` in your application config.\n */\nexport const STREAM_DEFAULTS = new InjectionToken<StreamDefaults>(\n \"LANGCHAIN_STREAM_DEFAULTS\",\n);\n\n/**\n * Injection token for a shared stream instance.\n * Provide via `provideStream()` at the component level.\n */\nexport const STREAM_INSTANCE = new InjectionToken<StreamServiceInstance>(\n \"LANGCHAIN_STREAM_INSTANCE\",\n);\n\n/**\n * Provides default LangGraph configuration at the application level.\n *\n * Use this in your application's `providers` array to set defaults like\n * `apiUrl` that will be used by all `useStream` and `injectStream` calls.\n *\n * @example\n * ```typescript\n * // app.config.ts\n * import { ApplicationConfig } from \"@angular/core\";\n * import { provideStreamDefaults } from \"@langchain/angular\";\n *\n * export const appConfig: ApplicationConfig = {\n * providers: [\n * provideStreamDefaults({\n * apiUrl: \"http://localhost:2024\",\n * }),\n * ],\n * };\n * ```\n */\nexport function provideStreamDefaults(\n defaults: StreamDefaults,\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n { provide: STREAM_DEFAULTS, useValue: defaults },\n ]);\n}\n\n/**\n * Creates a provider for a shared `useStream` instance at the component level.\n *\n * Add the returned provider to a component's `providers` array so that all\n * child components can access the same stream via `injectStream()`.\n *\n * @example\n * ```typescript\n * import { Component } from \"@angular/core\";\n * import { provideStream, injectStream } from \"@langchain/angular\";\n *\n * @Component({\n * providers: [provideStream({ assistantId: \"agent\" })],\n * template: `\n * <app-message-list />\n * <app-message-input />\n * `,\n * })\n * export class ChatContainer {}\n *\n * // In child components:\n * @Component({\n * template: `\n * @for (msg of stream.messages(); track msg.id) {\n * <div>{{ msg.content }}</div>\n * }\n * `,\n * })\n * export class MessageListComponent {\n * stream = injectStream();\n * }\n * ```\n */\nexport function provideStream<\n T = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate,\n>(\n options:\n | ResolveStreamOptions<T, InferBag<T, Bag>>\n | UseStreamCustomOptions<InferStateType<T>, InferBag<T, Bag>>,\n) {\n return {\n provide: STREAM_INSTANCE,\n useFactory: () => {\n const defaults = angularInject(STREAM_DEFAULTS, { optional: true });\n const merged = {\n ...(defaults ?? {}),\n ...options,\n apiUrl: (options as Record<string, unknown>).apiUrl ?? defaults?.apiUrl,\n client: (options as Record<string, unknown>).client ?? defaults?.client,\n };\n if (\"transport\" in merged) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return injectStreamCustom(merged as any);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return useStreamLGP(merged as any);\n },\n };\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,kBAAkB,IAAI,eACjC,4BACD;;;;;AAMD,MAAa,kBAAkB,IAAI,eACjC,4BACD;;;;;;;;;;;;;;;;;;;;;;AAuBD,SAAgB,sBACd,UACsB;AACtB,QAAO,yBAAyB,CAC9B;EAAE,SAAS;EAAiB,UAAU;EAAU,CACjD,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCJ,SAAgB,cAId,SAGA;AACA,QAAO;EACL,SAAS;EACT,kBAAkB;GAChB,MAAM,WAAWA,OAAc,iBAAiB,EAAE,UAAU,MAAM,CAAC;GACnE,MAAM,SAAS;IACb,GAAI,YAAY,EAAE;IAClB,GAAG;IACH,QAAS,QAAoC,UAAU,UAAU;IACjE,QAAS,QAAoC,UAAU,UAAU;IAClE;AACD,OAAI,eAAe,OAEjB,QAAO,mBAAmB,OAAc;AAG1C,UAAO,aAAa,OAAc;;EAErC"}
package/dist/index.cjs CHANGED
@@ -1,471 +1,33 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_stream_custom = require("./stream.custom.cjs");
3
- const require_decorate = require("./_virtual/_@oxc-project_runtime@0.115.0/helpers/decorate.cjs");
3
+ const require_stream_lgp = require("./stream.lgp.cjs");
4
4
  const require_context = require("./context.cjs");
5
+ const require_decorate = require("./_virtual/_@oxc-project_runtime@0.115.0/helpers/decorate.cjs");
5
6
  let _angular_core = require("@angular/core");
6
7
  let _langchain_langgraph_sdk_ui = require("@langchain/langgraph-sdk/ui");
7
- let _langchain_langgraph_sdk = require("@langchain/langgraph-sdk");
8
- let _langchain_langgraph_sdk_utils = require("@langchain/langgraph-sdk/utils");
9
8
  //#region src/index.ts
10
- function fetchHistory(client, threadId, options) {
11
- if (options?.limit === false) return client.threads.getState(threadId).then((state) => {
12
- if (state.checkpoint == null) return [];
13
- return [state];
14
- });
15
- const limit = typeof options?.limit === "number" ? options.limit : 10;
16
- return client.threads.getHistory(threadId, { limit });
17
- }
18
- function useStream(options) {
19
- if ("transport" in options) return require_stream_custom.useStreamCustom(options);
20
- return useStreamLGP(options);
21
- }
22
- function resolveRunMetadataStorage(reconnectOnMount) {
23
- if (typeof globalThis.window === "undefined") return null;
24
- if (reconnectOnMount === true) return globalThis.window.sessionStorage;
25
- if (typeof reconnectOnMount === "function") return reconnectOnMount();
26
- return null;
27
- }
28
- function useStreamLGP(options) {
29
- const runMetadataStorage = resolveRunMetadataStorage(options.reconnectOnMount);
30
- const getMessages = (value) => {
31
- const messagesKey = options.messagesKey ?? "messages";
32
- return Array.isArray(value[messagesKey]) ? value[messagesKey] : [];
33
- };
34
- const setMessages = (current, messages) => {
35
- const messagesKey = options.messagesKey ?? "messages";
36
- return {
37
- ...current,
38
- [messagesKey]: messages
39
- };
40
- };
41
- const historyLimit = typeof options.fetchStateHistory === "object" && options.fetchStateHistory != null ? options.fetchStateHistory.limit ?? false : options.fetchStateHistory ?? false;
42
- const threadId = (0, _angular_core.signal)(void 0);
43
- let threadIdPromise = null;
44
- const client = options.client ?? new _langchain_langgraph_sdk.Client({ apiUrl: options.apiUrl });
45
- const history = (0, _angular_core.signal)({
46
- data: void 0,
47
- error: void 0,
48
- isLoading: false,
49
- mutate: async () => void 0
50
- });
51
- async function mutate(mutateId) {
52
- const tid = mutateId ?? threadId();
53
- if (!tid) return void 0;
54
- try {
55
- const data = await fetchHistory(client, tid, { limit: historyLimit });
56
- history.set({
57
- data,
58
- error: void 0,
59
- isLoading: false,
60
- mutate
61
- });
62
- return data;
63
- } catch (err) {
64
- history.update((prev) => ({
65
- ...prev,
66
- error: err,
67
- isLoading: false
68
- }));
69
- options.onError?.(err, void 0);
70
- return;
71
- }
72
- }
73
- history.update((prev) => ({
74
- ...prev,
75
- mutate
76
- }));
77
- const branch = (0, _angular_core.signal)("");
78
- const branchContext = (0, _angular_core.computed)(() => (0, _langchain_langgraph_sdk_ui.getBranchContext)(branch(), history().data ?? void 0));
79
- const messageManager = new _langchain_langgraph_sdk_ui.MessageTupleManager();
80
- const stream = new _langchain_langgraph_sdk_ui.StreamManager(messageManager, {
81
- throttle: options.throttle ?? false,
82
- subagentToolNames: options.subagentToolNames,
83
- filterSubagentMessages: options.filterSubagentMessages,
84
- toMessage: _langchain_langgraph_sdk_ui.toMessageClass
85
- });
86
- const pendingRuns = new _langchain_langgraph_sdk_ui.PendingRunsTracker();
87
- const queueEntries = (0, _angular_core.signal)(pendingRuns.entries);
88
- const queueSize = (0, _angular_core.signal)(pendingRuns.size);
89
- const historyValues = (0, _angular_core.computed)(() => branchContext().threadHead?.values ?? options.initialValues ?? {});
90
- const historyError = (0, _angular_core.computed)(() => {
91
- const error = branchContext().threadHead?.tasks?.at(-1)?.error;
92
- if (error == null) return void 0;
93
- try {
94
- const parsed = JSON.parse(error);
95
- if (_langchain_langgraph_sdk_ui.StreamError.isStructuredError(parsed)) return new _langchain_langgraph_sdk_ui.StreamError(parsed);
96
- return parsed;
97
- } catch {}
98
- return error;
99
- });
100
- const streamValues = (0, _angular_core.signal)(stream.values);
101
- const streamError = (0, _angular_core.signal)(stream.error);
102
- const isLoading = (0, _angular_core.signal)(stream.isLoading);
103
- const values = (0, _angular_core.computed)(() => streamValues() ?? historyValues());
104
- const error = (0, _angular_core.computed)(() => streamError() ?? historyError() ?? history().error);
105
- const messageMetadata = (0, _angular_core.computed)(() => (0, _langchain_langgraph_sdk_ui.getMessagesMetadataMap)({
106
- initialValues: options.initialValues,
107
- history: history().data,
108
- getMessages,
109
- branchContext: branchContext()
110
- }));
111
- const subagentVersion = (0, _angular_core.signal)(0);
112
- (0, _angular_core.effect)((onCleanup) => {
113
- const unsubscribe = stream.subscribe(() => {
114
- streamValues.set(stream.values);
115
- streamError.set(stream.error);
116
- isLoading.set(stream.isLoading);
117
- subagentVersion.update((v) => v + 1);
118
- });
119
- onCleanup(() => unsubscribe());
120
- });
121
- pendingRuns.subscribe(() => {
122
- queueEntries.set(pendingRuns.entries);
123
- queueSize.set(pendingRuns.size);
124
- });
125
- (0, _angular_core.effect)((onCleanup) => {
126
- const hvMessages = getMessages(historyValues());
127
- if (options.filterSubagentMessages && !isLoading() && !history().isLoading && hvMessages.length > 0) {
128
- stream.reconstructSubagents(hvMessages, { skipIfPopulated: true });
129
- const tid = threadId();
130
- if (tid) {
131
- const controller = new AbortController();
132
- stream.fetchSubagentHistory(client.threads, tid, {
133
- messagesKey: options.messagesKey ?? "messages",
134
- signal: controller.signal
135
- });
136
- onCleanup(() => controller.abort());
137
- }
138
- }
139
- });
140
- function stop() {
141
- return stream.stop(historyValues(), { onStop: (args) => {
142
- if (runMetadataStorage && threadId()) {
143
- const tid = threadId();
144
- const runId = runMetadataStorage.getItem(`lg:stream:${tid}`);
145
- if (runId) client.runs.cancel(tid, runId);
146
- runMetadataStorage.removeItem(`lg:stream:${tid}`);
147
- }
148
- options.onStop?.(args);
149
- } });
150
- }
151
- function setBranch(value) {
152
- branch.set(value);
153
- }
154
- function submitDirect(values, submitOptions) {
155
- const currentBranchContext = branchContext();
156
- const checkpointId = submitOptions?.checkpoint?.checkpoint_id;
157
- branch.set(checkpointId != null ? currentBranchContext.branchByCheckpoint[checkpointId]?.branch ?? "" : "");
158
- const includeImplicitBranch = historyLimit === true || typeof historyLimit === "number";
159
- const shouldRefetch = options.onFinish != null || includeImplicitBranch;
160
- let checkpoint = submitOptions?.checkpoint ?? (includeImplicitBranch ? currentBranchContext.threadHead?.checkpoint : void 0) ?? void 0;
161
- if (submitOptions?.checkpoint === null) checkpoint = void 0;
162
- if (checkpoint != null) delete checkpoint.thread_id;
163
- const streamResumable = submitOptions?.streamResumable ?? !!runMetadataStorage;
164
- let callbackMeta;
165
- let rejoinKey;
166
- let usableThreadId;
167
- return stream.start(async (signal) => {
168
- usableThreadId = threadId();
169
- if (!usableThreadId) {
170
- const threadPromise = client.threads.create({
171
- threadId: submitOptions?.threadId,
172
- metadata: submitOptions?.metadata
173
- });
174
- threadIdPromise = threadPromise.then((t) => t.thread_id);
175
- usableThreadId = (await threadPromise).thread_id;
176
- threadId.set(usableThreadId);
177
- options.onThreadId?.(usableThreadId);
178
- }
179
- const streamMode = new Set([
180
- ...submitOptions?.streamMode ?? [],
181
- "values",
182
- "messages-tuple",
183
- "updates"
184
- ]);
185
- if (options.onUpdateEvent) streamMode.add("updates");
186
- if (options.onCustomEvent) streamMode.add("custom");
187
- if (options.onCheckpointEvent) streamMode.add("checkpoints");
188
- if (options.onTaskEvent) streamMode.add("tasks");
189
- if ("onDebugEvent" in options && options.onDebugEvent) streamMode.add("debug");
190
- if ("onLangChainEvent" in options && options.onLangChainEvent) streamMode.add("events");
191
- stream.setStreamValues(() => {
192
- const prev = {
193
- ...historyValues(),
194
- ...stream.values
195
- };
196
- if (submitOptions?.optimisticValues != null) return {
197
- ...prev,
198
- ...typeof submitOptions.optimisticValues === "function" ? submitOptions.optimisticValues(prev) : submitOptions.optimisticValues
199
- };
200
- return { ...prev };
201
- });
202
- return client.runs.stream(usableThreadId, options.assistantId, {
203
- input: values,
204
- config: submitOptions?.config,
205
- context: submitOptions?.context,
206
- command: submitOptions?.command,
207
- interruptBefore: submitOptions?.interruptBefore,
208
- interruptAfter: submitOptions?.interruptAfter,
209
- metadata: submitOptions?.metadata,
210
- multitaskStrategy: submitOptions?.multitaskStrategy,
211
- onCompletion: submitOptions?.onCompletion,
212
- onDisconnect: submitOptions?.onDisconnect ?? (streamResumable ? "continue" : "cancel"),
213
- signal,
214
- checkpoint,
215
- streamMode: [...streamMode],
216
- streamSubgraphs: submitOptions?.streamSubgraphs,
217
- streamResumable,
218
- durability: submitOptions?.durability,
219
- onRunCreated(params) {
220
- callbackMeta = {
221
- run_id: params.run_id,
222
- thread_id: params.thread_id ?? usableThreadId
223
- };
224
- if (runMetadataStorage) {
225
- rejoinKey = `lg:stream:${usableThreadId}`;
226
- runMetadataStorage.setItem(rejoinKey, callbackMeta.run_id);
227
- }
228
- options.onCreated?.(callbackMeta);
229
- }
230
- });
231
- }, {
232
- getMessages,
233
- setMessages,
234
- initialValues: historyValues(),
235
- callbacks: options,
236
- async onSuccess() {
237
- if (rejoinKey) runMetadataStorage?.removeItem(rejoinKey);
238
- if (shouldRefetch && usableThreadId) {
239
- const lastHead = (await mutate(usableThreadId))?.at(0);
240
- if (lastHead) {
241
- options.onFinish?.(lastHead, callbackMeta);
242
- return null;
243
- }
244
- }
245
- },
246
- onError: (error) => {
247
- options.onError?.(error, callbackMeta);
248
- submitOptions?.onError?.(error, callbackMeta);
249
- },
250
- onFinish: () => {}
251
- });
252
- }
253
- let submitting = false;
254
- function drainQueue() {
255
- if (!isLoading() && !submitting && pendingRuns.size > 0) {
256
- const next = pendingRuns.shift();
257
- if (next) {
258
- submitting = true;
259
- joinStream(next.id).finally(() => {
260
- submitting = false;
261
- drainQueue();
262
- });
263
- }
264
- }
265
- }
266
- (0, _angular_core.effect)(() => {
267
- drainQueue();
268
- });
269
- async function submit(values, submitOptions) {
270
- if (stream.isLoading || submitting) {
271
- if (submitOptions?.multitaskStrategy === "interrupt" || submitOptions?.multitaskStrategy === "rollback") {
272
- submitting = true;
273
- try {
274
- await submitDirect(values, submitOptions);
275
- } finally {
276
- submitting = false;
277
- }
278
- return;
279
- }
280
- let usableThreadId = threadId();
281
- if (!usableThreadId && threadIdPromise) usableThreadId = await threadIdPromise;
282
- if (usableThreadId) {
283
- try {
284
- const run = await client.runs.create(usableThreadId, options.assistantId, {
285
- input: values,
286
- config: submitOptions?.config,
287
- context: submitOptions?.context,
288
- command: submitOptions?.command,
289
- interruptBefore: submitOptions?.interruptBefore,
290
- interruptAfter: submitOptions?.interruptAfter,
291
- metadata: submitOptions?.metadata,
292
- multitaskStrategy: "enqueue",
293
- streamResumable: true,
294
- streamSubgraphs: submitOptions?.streamSubgraphs,
295
- durability: submitOptions?.durability
296
- });
297
- pendingRuns.add({
298
- id: run.run_id,
299
- values,
300
- options: submitOptions,
301
- createdAt: new Date(run.created_at)
302
- });
303
- } catch (error) {
304
- options.onError?.(error, void 0);
305
- submitOptions?.onError?.(error, void 0);
306
- }
307
- return;
308
- }
309
- }
310
- submitting = true;
311
- const result = submitDirect(values, submitOptions);
312
- Promise.resolve(result).finally(() => {
313
- submitting = false;
314
- drainQueue();
315
- });
316
- return result;
317
- }
318
- async function joinStream(runId, lastEventId, joinOptions) {
319
- lastEventId ??= "-1";
320
- const tid = threadId();
321
- if (!tid) return;
322
- const callbackMeta = {
323
- thread_id: tid,
324
- run_id: runId
325
- };
326
- await stream.start(async (signal) => {
327
- const rawStream = client.runs.joinStream(tid, runId, {
328
- signal,
329
- lastEventId,
330
- streamMode: joinOptions?.streamMode
331
- });
332
- return joinOptions?.filter != null ? (0, _langchain_langgraph_sdk_ui.filterStream)(rawStream, joinOptions.filter) : rawStream;
333
- }, {
334
- getMessages,
335
- setMessages,
336
- initialValues: historyValues(),
337
- callbacks: options,
338
- async onSuccess() {
339
- runMetadataStorage?.removeItem(`lg:stream:${tid}`);
340
- const lastHead = (await mutate(tid))?.at(0);
341
- if (lastHead) options.onFinish?.(lastHead, callbackMeta);
342
- },
343
- onError(error) {
344
- options.onError?.(error, callbackMeta);
345
- },
346
- onFinish() {}
347
- });
348
- }
349
- const shouldReconnect = !!runMetadataStorage;
350
- let hasReconnected = false;
351
- (0, _angular_core.effect)(() => {
352
- const tid = threadId();
353
- if (!hasReconnected && shouldReconnect && runMetadataStorage && tid && !isLoading()) {
354
- const runId = runMetadataStorage.getItem(`lg:stream:${tid}`);
355
- if (runId) {
356
- hasReconnected = true;
357
- joinStream(runId);
358
- }
359
- }
360
- });
361
- const messages = (0, _angular_core.computed)(() => (0, _langchain_langgraph_sdk_ui.ensureMessageInstances)(getMessages(values())));
362
- const toolCalls = (0, _angular_core.computed)(() => (0, _langchain_langgraph_sdk_utils.getToolCallsWithResults)(getMessages(values())));
363
- function getToolCalls(message) {
364
- return (0, _langchain_langgraph_sdk_utils.getToolCallsWithResults)(getMessages(values())).filter((tc) => tc.aiMessage.id === message.id);
365
- }
366
- const interrupt = (0, _angular_core.computed)(() => (0, _langchain_langgraph_sdk_ui.extractInterrupts)(values(), {
367
- isLoading: isLoading(),
368
- threadState: branchContext().threadHead,
369
- error: error()
370
- }));
371
- const interrupts = (0, _angular_core.computed)(() => {
372
- const vals = values();
373
- if (vals != null && "__interrupt__" in vals && Array.isArray(vals.__interrupt__)) {
374
- const valueInterrupts = vals.__interrupt__;
375
- if (valueInterrupts.length === 0) return [{ when: "breakpoint" }];
376
- return valueInterrupts;
377
- }
378
- if (isLoading()) return [];
379
- const allInterrupts = (branchContext().threadHead?.tasks ?? []).flatMap((t) => t.interrupts ?? []);
380
- if (allInterrupts.length > 0) return allInterrupts;
381
- if (!(branchContext().threadHead?.next ?? []).length || error() != null) return [];
382
- return [{ when: "breakpoint" }];
383
- });
384
- const historyList = (0, _angular_core.computed)(() => {
385
- if (historyLimit === false) throw new Error("`fetchStateHistory` must be set to `true` to use `history`");
386
- return (0, _langchain_langgraph_sdk_ui.ensureHistoryMessageInstances)(branchContext().flatHistory, options.messagesKey ?? "messages");
387
- });
388
- const isThreadLoading = (0, _angular_core.computed)(() => history().isLoading && history().data == null);
389
- const experimentalBranchTree = (0, _angular_core.computed)(() => {
390
- if (historyLimit === false) throw new Error("`fetchStateHistory` must be set to `true` to use `experimental_branchTree`");
391
- return branchContext().branchTree;
392
- });
393
- function getMessagesMetadata(message, index) {
394
- const streamMetadata = messageManager.get(message.id)?.metadata;
395
- const historyMetadata = messageMetadata().find((m) => m.messageId === (message.id ?? index));
396
- if (streamMetadata != null || historyMetadata != null) return {
397
- ...historyMetadata,
398
- streamMetadata
399
- };
400
- }
401
- return {
402
- assistantId: options.assistantId,
403
- client,
404
- values,
405
- error,
406
- isLoading,
407
- branch,
408
- setBranch,
409
- messages,
410
- toolCalls,
411
- getToolCalls,
412
- interrupt,
413
- interrupts,
414
- history: historyList,
415
- isThreadLoading,
416
- experimental_branchTree: experimentalBranchTree,
417
- getMessagesMetadata,
418
- submit,
419
- stop,
420
- joinStream,
421
- queue: {
422
- entries: queueEntries,
423
- size: queueSize,
424
- async cancel(id) {
425
- const tid = threadId();
426
- const removed = pendingRuns.remove(id);
427
- if (removed && tid) await client.runs.cancel(tid, id);
428
- return removed;
429
- },
430
- async clear() {
431
- const tid = threadId();
432
- const removed = pendingRuns.removeAll();
433
- if (tid && removed.length > 0) await Promise.all(removed.map((e) => client.runs.cancel(tid, e.id)));
434
- }
435
- },
436
- switchThread(newThreadId) {
437
- if (newThreadId !== (threadId() ?? null)) {
438
- const prevThreadId = threadId();
439
- threadId.set(newThreadId ?? void 0);
440
- stream.clear();
441
- const removed = pendingRuns.removeAll();
442
- if (prevThreadId && removed.length > 0) Promise.all(removed.map((e) => client.runs.cancel(prevThreadId, e.id)));
443
- if (newThreadId != null) options.onThreadId?.(newThreadId);
444
- }
445
- },
446
- get subagents() {
447
- subagentVersion();
448
- return stream.getSubagents();
449
- },
450
- get activeSubagents() {
451
- subagentVersion();
452
- return stream.getActiveSubagents();
453
- },
454
- getSubagent(toolCallId) {
455
- return stream.getSubagent(toolCallId);
456
- },
457
- getSubagentsByType(type) {
458
- return stream.getSubagentsByType(type);
459
- },
460
- getSubagentsByMessage(messageId) {
461
- return stream.getSubagentsByMessage(messageId);
462
- }
463
- };
9
+ /**
10
+ * @internal Merges DI, LangGraph Platform, and custom transport overloads.
11
+ */
12
+ function injectStream(options) {
13
+ if (arguments.length === 0) {
14
+ const instance = (0, _angular_core.inject)(require_context.STREAM_INSTANCE, { optional: true });
15
+ if (instance == null) throw new Error("injectStream() requires an ancestor component to provide a stream via provideStream(). Add provideStream({ assistantId: '...' }) to the providers array of a parent component, or use injectStream(options) directly.");
16
+ return instance;
17
+ }
18
+ if ("transport" in options) return require_stream_custom.injectStreamCustom(options);
19
+ return require_stream_lgp.useStreamLGP(options);
464
20
  }
21
+ /**
22
+ * @deprecated Use `injectStream` instead. `useStream` will be removed in a
23
+ * future major version. `injectStream` follows Angular's `inject*` naming
24
+ * convention for injection-based patterns.
25
+ */
26
+ const useStream = injectStream;
465
27
  let StreamService = class StreamService {
466
28
  _stream;
467
29
  constructor(options) {
468
- this._stream = useStream(options);
30
+ this._stream = injectStream(options);
469
31
  }
470
32
  get values() {
471
33
  return this._stream.values;
@@ -518,8 +80,8 @@ let StreamService = class StreamService {
518
80
  submit(values, options) {
519
81
  return this._stream.submit(values, options);
520
82
  }
521
- stop() {
522
- return this._stream.stop();
83
+ async stop() {
84
+ await this._stream.stop();
523
85
  }
524
86
  setBranch(value) {
525
87
  this._stream.setBranch(value);
@@ -586,7 +148,8 @@ Object.defineProperty(exports, "extractToolCallIdFromNamespace", {
586
148
  return _langchain_langgraph_sdk_ui.extractToolCallIdFromNamespace;
587
149
  }
588
150
  });
589
- exports.injectStream = require_context.injectStream;
151
+ exports.injectStream = injectStream;
152
+ exports.injectStreamCustom = require_stream_custom.injectStreamCustom;
590
153
  Object.defineProperty(exports, "isSubagentNamespace", {
591
154
  enumerable: true,
592
155
  get: function() {
@@ -596,6 +159,7 @@ Object.defineProperty(exports, "isSubagentNamespace", {
596
159
  exports.provideStream = require_context.provideStream;
597
160
  exports.provideStreamDefaults = require_context.provideStreamDefaults;
598
161
  exports.useStream = useStream;
599
- exports.useStreamLGP = useStreamLGP;
162
+ exports.useStreamCustom = require_stream_custom.useStreamCustom;
163
+ exports.useStreamLGP = require_stream_lgp.useStreamLGP;
600
164
 
601
165
  //# sourceMappingURL=index.cjs.map