@langchain/langgraph-sdk 1.7.5 → 1.8.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/dist/ui/index.cjs +4 -0
- package/dist/ui/index.d.cts +3 -1
- package/dist/ui/index.d.ts +3 -1
- package/dist/ui/index.js +3 -1
- package/dist/ui/orchestrator-custom.cjs +372 -0
- package/dist/ui/orchestrator-custom.cjs.map +1 -0
- package/dist/ui/orchestrator-custom.d.cts +185 -0
- package/dist/ui/orchestrator-custom.d.cts.map +1 -0
- package/dist/ui/orchestrator-custom.d.ts +185 -0
- package/dist/ui/orchestrator-custom.d.ts.map +1 -0
- package/dist/ui/orchestrator-custom.js +372 -0
- package/dist/ui/orchestrator-custom.js.map +1 -0
- package/dist/ui/orchestrator.cjs +866 -0
- package/dist/ui/orchestrator.cjs.map +1 -0
- package/dist/ui/orchestrator.d.cts +366 -0
- package/dist/ui/orchestrator.d.cts.map +1 -0
- package/dist/ui/orchestrator.d.ts +366 -0
- package/dist/ui/orchestrator.d.ts.map +1 -0
- package/dist/ui/orchestrator.js +866 -0
- package/dist/ui/orchestrator.js.map +1 -0
- package/package.json +1 -1
package/dist/ui/index.cjs
CHANGED
|
@@ -8,11 +8,15 @@ const require_branching = require("./branching.cjs");
|
|
|
8
8
|
const require_interrupts = require("./interrupts.cjs");
|
|
9
9
|
const require_transport = require("./transport.cjs");
|
|
10
10
|
const require_queue = require("./queue.cjs");
|
|
11
|
+
const require_orchestrator = require("./orchestrator.cjs");
|
|
12
|
+
const require_orchestrator_custom = require("./orchestrator-custom.cjs");
|
|
13
|
+
exports.CustomStreamOrchestrator = require_orchestrator_custom.CustomStreamOrchestrator;
|
|
11
14
|
exports.FetchStreamTransport = require_transport.FetchStreamTransport;
|
|
12
15
|
exports.MessageTupleManager = require_messages.MessageTupleManager;
|
|
13
16
|
exports.PendingRunsTracker = require_queue.PendingRunsTracker;
|
|
14
17
|
exports.StreamError = require_errors.StreamError;
|
|
15
18
|
exports.StreamManager = require_manager.StreamManager;
|
|
19
|
+
exports.StreamOrchestrator = require_orchestrator.StreamOrchestrator;
|
|
16
20
|
exports.SubagentManager = require_subagents.SubagentManager;
|
|
17
21
|
exports.calculateDepthFromNamespace = require_subagents.calculateDepthFromNamespace;
|
|
18
22
|
exports.ensureHistoryMessageInstances = require_messages.ensureHistoryMessageInstances;
|
package/dist/ui/index.d.cts
CHANGED
|
@@ -12,4 +12,6 @@ import { EventStreamEvent, StreamManager } from "./manager.cjs";
|
|
|
12
12
|
import { extractInterrupts } from "./interrupts.cjs";
|
|
13
13
|
import { FetchStreamTransport } from "./transport.cjs";
|
|
14
14
|
import { filterStream, findLast, unique } from "./utils.cjs";
|
|
15
|
-
|
|
15
|
+
import { OrchestratorAccessors, StreamOrchestrator } from "./orchestrator.cjs";
|
|
16
|
+
import { CustomStreamOrchestrator } from "./orchestrator-custom.cjs";
|
|
17
|
+
export { AcceptBaseMessages, AgentMiddlewareLike, AgentTypeConfigLike, AnyStreamCustomOptions, AnyStreamOptions, BaseStream, BaseSubagentState, CompiledSubAgentLike, CustomStreamOrchestrator, CustomSubmitOptions, DeepAgentTypeConfigLike, DefaultSubagentStates, type EventStreamEvent, ExtractAgentConfig, ExtractDeepAgentConfig, ExtractSubAgentMiddleware, ExtractToolCallsFromState, FetchStreamTransport, GetConfigurableType, GetCustomEventType, GetInterruptType, GetToolCallsType, GetUpdateType, type HistoryWithBaseMessages, InferAgentState, InferAgentToolCalls, InferBag, InferDeepAgentSubagents, InferMiddlewareStatesFromArray, InferNodeNames, InferNodeReturnTypes, InferStateType, InferSubagentByName, InferSubagentNames, InferSubagentState, InferSubagentStates, InferToolCalls, IsAgentLike, IsDeepAgentLike, MessageMetadata, MessageTupleManager, type OrchestratorAccessors, PendingRunsTracker, type QueueEntry, type QueueInterface, ResolveStreamInterface, ResolveStreamOptions, RunCallbackMeta, type Sequence, StreamBase, StreamError, StreamManager, StreamOrchestrator, SubAgentLike, SubagentApi, SubagentManager, SubagentStateMap, SubagentStatus, SubagentStream, SubagentStreamInterface, SubagentToolCall, SubmitOptions, UseAgentStream, UseAgentStreamOptions, UseDeepAgentStream, UseDeepAgentStreamOptions, UseStreamCustomOptions, UseStreamOptions, UseStreamThread, UseStreamTransport, UseStreamTransportPayload, calculateDepthFromNamespace, ensureHistoryMessageInstances, ensureMessageInstances, extractInterrupts, extractParentIdFromNamespace, extractToolCallIdFromNamespace, filterStream, findLast, getBranchContext, getMessagesMetadataMap, isSubagentNamespace, toMessageClass, toMessageDict, unique };
|
package/dist/ui/index.d.ts
CHANGED
|
@@ -12,4 +12,6 @@ import { EventStreamEvent, StreamManager } from "./manager.js";
|
|
|
12
12
|
import { extractInterrupts } from "./interrupts.js";
|
|
13
13
|
import { FetchStreamTransport } from "./transport.js";
|
|
14
14
|
import { filterStream, findLast, unique } from "./utils.js";
|
|
15
|
-
|
|
15
|
+
import { OrchestratorAccessors, StreamOrchestrator } from "./orchestrator.js";
|
|
16
|
+
import { CustomStreamOrchestrator } from "./orchestrator-custom.js";
|
|
17
|
+
export { AcceptBaseMessages, AgentMiddlewareLike, AgentTypeConfigLike, AnyStreamCustomOptions, AnyStreamOptions, BaseStream, BaseSubagentState, CompiledSubAgentLike, CustomStreamOrchestrator, CustomSubmitOptions, DeepAgentTypeConfigLike, DefaultSubagentStates, type EventStreamEvent, ExtractAgentConfig, ExtractDeepAgentConfig, ExtractSubAgentMiddleware, ExtractToolCallsFromState, FetchStreamTransport, GetConfigurableType, GetCustomEventType, GetInterruptType, GetToolCallsType, GetUpdateType, type HistoryWithBaseMessages, InferAgentState, InferAgentToolCalls, InferBag, InferDeepAgentSubagents, InferMiddlewareStatesFromArray, InferNodeNames, InferNodeReturnTypes, InferStateType, InferSubagentByName, InferSubagentNames, InferSubagentState, InferSubagentStates, InferToolCalls, IsAgentLike, IsDeepAgentLike, MessageMetadata, MessageTupleManager, type OrchestratorAccessors, PendingRunsTracker, type QueueEntry, type QueueInterface, ResolveStreamInterface, ResolveStreamOptions, RunCallbackMeta, type Sequence, StreamBase, StreamError, StreamManager, StreamOrchestrator, SubAgentLike, SubagentApi, SubagentManager, SubagentStateMap, SubagentStatus, SubagentStream, SubagentStreamInterface, SubagentToolCall, SubmitOptions, UseAgentStream, UseAgentStreamOptions, UseDeepAgentStream, UseDeepAgentStreamOptions, UseStreamCustomOptions, UseStreamOptions, UseStreamThread, UseStreamTransport, UseStreamTransportPayload, calculateDepthFromNamespace, ensureHistoryMessageInstances, ensureMessageInstances, extractInterrupts, extractParentIdFromNamespace, extractToolCallIdFromNamespace, filterStream, findLast, getBranchContext, getMessagesMetadataMap, isSubagentNamespace, toMessageClass, toMessageDict, unique };
|
package/dist/ui/index.js
CHANGED
|
@@ -7,4 +7,6 @@ import { getBranchContext, getMessagesMetadataMap } from "./branching.js";
|
|
|
7
7
|
import { extractInterrupts } from "./interrupts.js";
|
|
8
8
|
import { FetchStreamTransport } from "./transport.js";
|
|
9
9
|
import { PendingRunsTracker } from "./queue.js";
|
|
10
|
-
|
|
10
|
+
import { StreamOrchestrator } from "./orchestrator.js";
|
|
11
|
+
import { CustomStreamOrchestrator } from "./orchestrator-custom.js";
|
|
12
|
+
export { CustomStreamOrchestrator, FetchStreamTransport, MessageTupleManager, PendingRunsTracker, StreamError, StreamManager, StreamOrchestrator, SubagentManager, calculateDepthFromNamespace, ensureHistoryMessageInstances, ensureMessageInstances, extractInterrupts, extractParentIdFromNamespace, extractToolCallIdFromNamespace, filterStream, findLast, getBranchContext, getMessagesMetadataMap, isSubagentNamespace, toMessageClass, toMessageDict, unique };
|
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
const require_messages = require("./messages.cjs");
|
|
2
|
+
const require_tools = require("../utils/tools.cjs");
|
|
3
|
+
const require_manager = require("./manager.cjs");
|
|
4
|
+
const require_interrupts = require("./interrupts.cjs");
|
|
5
|
+
//#region src/ui/orchestrator-custom.ts
|
|
6
|
+
/**
|
|
7
|
+
* Create a custom transport thread state.
|
|
8
|
+
* @param values - The values to use.
|
|
9
|
+
* @param threadId - The ID of the thread to use.
|
|
10
|
+
* @returns The custom transport thread state.
|
|
11
|
+
*/
|
|
12
|
+
function createCustomTransportThreadState(values, threadId) {
|
|
13
|
+
return {
|
|
14
|
+
values,
|
|
15
|
+
next: [],
|
|
16
|
+
tasks: [],
|
|
17
|
+
metadata: void 0,
|
|
18
|
+
created_at: null,
|
|
19
|
+
checkpoint: {
|
|
20
|
+
thread_id: threadId,
|
|
21
|
+
checkpoint_id: null,
|
|
22
|
+
checkpoint_ns: "",
|
|
23
|
+
checkpoint_map: null
|
|
24
|
+
},
|
|
25
|
+
parent_checkpoint: null
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Framework-agnostic orchestrator for custom transport streams.
|
|
30
|
+
*
|
|
31
|
+
* Encapsulates all business logic shared across React, Vue, Svelte, and Angular
|
|
32
|
+
* for custom transport (non-LGP) streaming.
|
|
33
|
+
*/
|
|
34
|
+
var CustomStreamOrchestrator = class {
|
|
35
|
+
stream;
|
|
36
|
+
messageManager;
|
|
37
|
+
#options;
|
|
38
|
+
#historyValues;
|
|
39
|
+
#threadId;
|
|
40
|
+
#branch = "";
|
|
41
|
+
#listeners = /* @__PURE__ */ new Set();
|
|
42
|
+
#version = 0;
|
|
43
|
+
#streamUnsub = null;
|
|
44
|
+
#disposed = false;
|
|
45
|
+
/**
|
|
46
|
+
* Create a new {@link CustomStreamOrchestrator} instance.
|
|
47
|
+
*
|
|
48
|
+
* @param options - Configuration options for the custom transport stream,
|
|
49
|
+
* including thread ID, transport, callbacks, and subagent settings.
|
|
50
|
+
*/
|
|
51
|
+
constructor(options) {
|
|
52
|
+
this.#options = options;
|
|
53
|
+
this.#threadId = options.threadId ?? null;
|
|
54
|
+
this.messageManager = new require_messages.MessageTupleManager();
|
|
55
|
+
this.stream = new require_manager.StreamManager(this.messageManager, {
|
|
56
|
+
throttle: options.throttle ?? false,
|
|
57
|
+
subagentToolNames: options.subagentToolNames,
|
|
58
|
+
filterSubagentMessages: options.filterSubagentMessages,
|
|
59
|
+
toMessage: options.toMessage ?? require_messages.toMessageClass
|
|
60
|
+
});
|
|
61
|
+
this.#historyValues = options.initialValues ?? {};
|
|
62
|
+
this.#streamUnsub = this.stream.subscribe(() => {
|
|
63
|
+
this.#notify();
|
|
64
|
+
});
|
|
65
|
+
const historyMessages = this.#getMessages(this.#historyValues);
|
|
66
|
+
if (options.filterSubagentMessages && !this.stream.isLoading && historyMessages.length > 0) this.stream.reconstructSubagents(historyMessages, { skipIfPopulated: true });
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Register a listener that is called whenever the orchestrator state changes.
|
|
70
|
+
*
|
|
71
|
+
* @param listener - Callback invoked on each state change.
|
|
72
|
+
* @returns An unsubscribe function that removes the listener.
|
|
73
|
+
*/
|
|
74
|
+
subscribe = (listener) => {
|
|
75
|
+
this.#listeners.add(listener);
|
|
76
|
+
return () => {
|
|
77
|
+
this.#listeners.delete(listener);
|
|
78
|
+
};
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Return the current version number, incremented on each state change.
|
|
82
|
+
* Useful as a cache key for external sync (e.g. `useSyncExternalStore`).
|
|
83
|
+
*
|
|
84
|
+
* @returns The current version counter.
|
|
85
|
+
*/
|
|
86
|
+
getSnapshot = () => this.#version;
|
|
87
|
+
#notify() {
|
|
88
|
+
if (this.#disposed) return;
|
|
89
|
+
this.#version += 1;
|
|
90
|
+
for (const listener of this.#listeners) listener();
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Synchronize the external thread ID with the orchestrator.
|
|
94
|
+
* If the ID has changed, the current stream is cleared and listeners
|
|
95
|
+
* are notified.
|
|
96
|
+
*
|
|
97
|
+
* @param newId - The new thread ID, or `null` to clear.
|
|
98
|
+
*/
|
|
99
|
+
syncThreadId(newId) {
|
|
100
|
+
if (newId !== this.#threadId) {
|
|
101
|
+
this.#threadId = newId;
|
|
102
|
+
this.stream.clear();
|
|
103
|
+
this.#notify();
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
#getMessages = (value) => {
|
|
107
|
+
const messagesKey = this.#options.messagesKey ?? "messages";
|
|
108
|
+
return Array.isArray(value[messagesKey]) ? value[messagesKey] : [];
|
|
109
|
+
};
|
|
110
|
+
#setMessages = (current, messages) => {
|
|
111
|
+
const messagesKey = this.#options.messagesKey ?? "messages";
|
|
112
|
+
return {
|
|
113
|
+
...current,
|
|
114
|
+
[messagesKey]: messages
|
|
115
|
+
};
|
|
116
|
+
};
|
|
117
|
+
/**
|
|
118
|
+
* The current stream state values, falling back to an empty object
|
|
119
|
+
* when no stream values are available.
|
|
120
|
+
*/
|
|
121
|
+
get values() {
|
|
122
|
+
return this.stream.values ?? {};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The raw stream state values, or `null` if no stream has been started
|
|
126
|
+
* or values have not yet been received.
|
|
127
|
+
*/
|
|
128
|
+
get streamValues() {
|
|
129
|
+
return this.stream.values;
|
|
130
|
+
}
|
|
131
|
+
/** The most recent stream error, or `undefined` if no error occurred. */
|
|
132
|
+
get error() {
|
|
133
|
+
return this.stream.error;
|
|
134
|
+
}
|
|
135
|
+
/** Whether a stream is currently in progress. */
|
|
136
|
+
get isLoading() {
|
|
137
|
+
return this.stream.isLoading;
|
|
138
|
+
}
|
|
139
|
+
/** The current branch identifier. */
|
|
140
|
+
get branch() {
|
|
141
|
+
return this.#branch;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Update the current branch and notify listeners.
|
|
145
|
+
*
|
|
146
|
+
* @param value - The new branch identifier.
|
|
147
|
+
*/
|
|
148
|
+
setBranch(value) {
|
|
149
|
+
this.#branch = value;
|
|
150
|
+
this.#notify();
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* All messages from the current stream values, converted to
|
|
154
|
+
* {@link BaseMessage} instances. Returns an empty array when no
|
|
155
|
+
* stream values are available.
|
|
156
|
+
*/
|
|
157
|
+
get messages() {
|
|
158
|
+
if (!this.stream.values) return [];
|
|
159
|
+
return require_messages.ensureMessageInstances(this.#getMessages(this.stream.values));
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* All tool calls paired with their results extracted from the
|
|
163
|
+
* current stream messages.
|
|
164
|
+
*/
|
|
165
|
+
get toolCalls() {
|
|
166
|
+
if (!this.stream.values) return [];
|
|
167
|
+
return require_tools.getToolCallsWithResults(this.#getMessages(this.stream.values));
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Get tool calls (with results) that belong to a specific AI message.
|
|
171
|
+
*
|
|
172
|
+
* @param message - The AI message whose tool calls to retrieve.
|
|
173
|
+
* @returns Tool calls associated with the given message.
|
|
174
|
+
*/
|
|
175
|
+
getToolCalls(message) {
|
|
176
|
+
if (!this.stream.values) return [];
|
|
177
|
+
return require_tools.getToolCallsWithResults(this.#getMessages(this.stream.values)).filter((tc) => tc.aiMessage.id === message.id);
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* All active interrupts from the current stream values.
|
|
181
|
+
* Returns a single breakpoint interrupt when the interrupt array is
|
|
182
|
+
* present but empty, or an empty array when no interrupts exist.
|
|
183
|
+
*/
|
|
184
|
+
get interrupts() {
|
|
185
|
+
if (this.stream.values != null && "__interrupt__" in this.stream.values && Array.isArray(this.stream.values.__interrupt__)) {
|
|
186
|
+
const valueInterrupts = this.stream.values.__interrupt__;
|
|
187
|
+
if (valueInterrupts.length === 0) return [{ when: "breakpoint" }];
|
|
188
|
+
return valueInterrupts;
|
|
189
|
+
}
|
|
190
|
+
return [];
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* The first active interrupt extracted from the current stream values,
|
|
194
|
+
* or `undefined` if there are no interrupts.
|
|
195
|
+
*/
|
|
196
|
+
get interrupt() {
|
|
197
|
+
return require_interrupts.extractInterrupts(this.stream.values);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Retrieve stream-level metadata for a given message.
|
|
201
|
+
*
|
|
202
|
+
* @param message - The message to look up metadata for.
|
|
203
|
+
* @param index - Optional positional index used as fallback message ID.
|
|
204
|
+
* @returns The metadata associated with the message, or `undefined`
|
|
205
|
+
* if no stream metadata is available.
|
|
206
|
+
*/
|
|
207
|
+
getMessagesMetadata(message, index) {
|
|
208
|
+
const streamMetadata = this.messageManager.get(message.id)?.metadata;
|
|
209
|
+
if (streamMetadata != null) return {
|
|
210
|
+
messageId: message.id ?? String(index),
|
|
211
|
+
firstSeenState: void 0,
|
|
212
|
+
branch: void 0,
|
|
213
|
+
branchOptions: void 0,
|
|
214
|
+
streamMetadata
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
/** A map of all tracked subagent streams, keyed by tool call ID. */
|
|
218
|
+
get subagents() {
|
|
219
|
+
return this.stream.getSubagents();
|
|
220
|
+
}
|
|
221
|
+
/** The subset of subagent streams that are currently active (loading). */
|
|
222
|
+
get activeSubagents() {
|
|
223
|
+
return this.stream.getActiveSubagents();
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Look up a single subagent stream by its tool call ID.
|
|
227
|
+
*
|
|
228
|
+
* @param toolCallId - The tool call ID that initiated the subagent.
|
|
229
|
+
* @returns The subagent stream, or `undefined` if not found.
|
|
230
|
+
*/
|
|
231
|
+
getSubagent(toolCallId) {
|
|
232
|
+
return this.stream.getSubagent(toolCallId);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Retrieve all subagent streams matching a given tool name / type.
|
|
236
|
+
*
|
|
237
|
+
* @param type - The subagent type (tool name) to filter by.
|
|
238
|
+
* @returns An array of matching subagent streams.
|
|
239
|
+
*/
|
|
240
|
+
getSubagentsByType(type) {
|
|
241
|
+
return this.stream.getSubagentsByType(type);
|
|
242
|
+
}
|
|
243
|
+
/**
|
|
244
|
+
* Retrieve all subagent streams associated with a specific AI message.
|
|
245
|
+
*
|
|
246
|
+
* @param messageId - The ID of the parent AI message.
|
|
247
|
+
* @returns An array of subagent streams linked to the message.
|
|
248
|
+
*/
|
|
249
|
+
getSubagentsByMessage(messageId) {
|
|
250
|
+
return this.stream.getSubagentsByMessage(messageId);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Reconstruct subagent streams from history values when subagent
|
|
254
|
+
* filtering is enabled and the stream is not currently loading.
|
|
255
|
+
* This is a no-op if subagents are already populated.
|
|
256
|
+
*/
|
|
257
|
+
reconstructSubagentsIfNeeded() {
|
|
258
|
+
const hvMessages = this.#getMessages(this.#historyValues);
|
|
259
|
+
if (this.#options.filterSubagentMessages && !this.stream.isLoading && hvMessages.length > 0) this.stream.reconstructSubagents(hvMessages, { skipIfPopulated: true });
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Abort the current stream and invoke the `onStop` callback
|
|
263
|
+
* if one was provided in the options.
|
|
264
|
+
*/
|
|
265
|
+
stop() {
|
|
266
|
+
this.stream.stop(this.#historyValues, { onStop: this.#options.onStop });
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* Switch to a different thread. If the thread ID actually changed,
|
|
270
|
+
* the current stream is cleared and listeners are notified.
|
|
271
|
+
*
|
|
272
|
+
* @param newThreadId - The thread ID to switch to, or `null` to clear.
|
|
273
|
+
*/
|
|
274
|
+
switchThread(newThreadId) {
|
|
275
|
+
if (newThreadId !== this.#threadId) {
|
|
276
|
+
this.#threadId = newThreadId;
|
|
277
|
+
this.stream.clear();
|
|
278
|
+
this.#notify();
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Start a new stream run against the custom transport.
|
|
283
|
+
*
|
|
284
|
+
* This is the low-level submit entry point that handles thread ID
|
|
285
|
+
* resolution, optimistic value merging, and transport invocation.
|
|
286
|
+
* Prefer {@link submit} unless you need to bypass higher-level wrappers.
|
|
287
|
+
*
|
|
288
|
+
* @param values - The input values to send, or `null`/`undefined` for
|
|
289
|
+
* a resume-style invocation.
|
|
290
|
+
* @param submitOptions - Optional per-call overrides such as
|
|
291
|
+
* `optimisticValues`, `config`, `command`, and error callbacks.
|
|
292
|
+
*/
|
|
293
|
+
async submitDirect(values, submitOptions) {
|
|
294
|
+
const currentThreadId = this.#options.threadId ?? null;
|
|
295
|
+
if (currentThreadId !== this.#threadId) {
|
|
296
|
+
this.#threadId = currentThreadId;
|
|
297
|
+
this.stream.clear();
|
|
298
|
+
}
|
|
299
|
+
let usableThreadId = this.#threadId ?? submitOptions?.threadId;
|
|
300
|
+
this.stream.setStreamValues(() => {
|
|
301
|
+
if (submitOptions?.optimisticValues != null) return {
|
|
302
|
+
...this.#historyValues,
|
|
303
|
+
...typeof submitOptions.optimisticValues === "function" ? submitOptions.optimisticValues(this.#historyValues) : submitOptions.optimisticValues
|
|
304
|
+
};
|
|
305
|
+
return { ...this.#historyValues };
|
|
306
|
+
});
|
|
307
|
+
await this.stream.start(async (signal) => {
|
|
308
|
+
if (!usableThreadId) {
|
|
309
|
+
usableThreadId = crypto.randomUUID();
|
|
310
|
+
this.#threadId = usableThreadId;
|
|
311
|
+
this.#options.onThreadId?.(usableThreadId);
|
|
312
|
+
}
|
|
313
|
+
if (!usableThreadId) throw new Error("Failed to obtain valid thread ID.");
|
|
314
|
+
return this.#options.transport.stream({
|
|
315
|
+
input: values,
|
|
316
|
+
context: submitOptions?.context,
|
|
317
|
+
command: submitOptions?.command,
|
|
318
|
+
streamSubgraphs: submitOptions?.streamSubgraphs,
|
|
319
|
+
signal,
|
|
320
|
+
config: {
|
|
321
|
+
...submitOptions?.config,
|
|
322
|
+
configurable: {
|
|
323
|
+
thread_id: usableThreadId,
|
|
324
|
+
...submitOptions?.config?.configurable
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
});
|
|
328
|
+
}, {
|
|
329
|
+
getMessages: this.#getMessages,
|
|
330
|
+
setMessages: this.#setMessages,
|
|
331
|
+
initialValues: {},
|
|
332
|
+
callbacks: this.#options,
|
|
333
|
+
onSuccess: () => {
|
|
334
|
+
if (!usableThreadId) return void 0;
|
|
335
|
+
const finalValues = this.stream.values ?? this.#historyValues;
|
|
336
|
+
this.#options.onFinish?.(createCustomTransportThreadState(finalValues, usableThreadId), void 0);
|
|
337
|
+
},
|
|
338
|
+
onError: (error) => {
|
|
339
|
+
this.#options.onError?.(error, void 0);
|
|
340
|
+
submitOptions?.onError?.(error, void 0);
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Submit input values and start a new stream run.
|
|
346
|
+
*
|
|
347
|
+
* Delegates to {@link submitDirect}. Override or wrap this method
|
|
348
|
+
* in framework adapters to add queuing or other middleware.
|
|
349
|
+
*
|
|
350
|
+
* @param values - The input values to send, or `null`/`undefined` for
|
|
351
|
+
* a resume-style invocation.
|
|
352
|
+
* @param submitOptions - Optional per-call overrides.
|
|
353
|
+
*/
|
|
354
|
+
async submit(values, submitOptions) {
|
|
355
|
+
await this.submitDirect(values, submitOptions);
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Tear down the orchestrator. Marks the instance as disposed,
|
|
359
|
+
* unsubscribes from the stream, and aborts any in-progress stream.
|
|
360
|
+
* After calling this method, no further notifications will be emitted.
|
|
361
|
+
*/
|
|
362
|
+
dispose() {
|
|
363
|
+
this.#disposed = true;
|
|
364
|
+
this.#streamUnsub?.();
|
|
365
|
+
this.#streamUnsub = null;
|
|
366
|
+
this.stream.stop(this.#historyValues, { onStop: this.#options.onStop });
|
|
367
|
+
}
|
|
368
|
+
};
|
|
369
|
+
//#endregion
|
|
370
|
+
exports.CustomStreamOrchestrator = CustomStreamOrchestrator;
|
|
371
|
+
|
|
372
|
+
//# sourceMappingURL=orchestrator-custom.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator-custom.cjs","names":["#options","#historyValues","#threadId","MessageTupleManager","StreamManager","toMessageClass","#streamUnsub","#notify","#getMessages","#listeners","#version","#disposed","#branch","ensureMessageInstances","getToolCallsWithResults","extractInterrupts","#setMessages"],"sources":["../../src/ui/orchestrator-custom.ts"],"sourcesContent":["import type { BaseMessage } from \"@langchain/core/messages\";\n\nimport type { ThreadState, Interrupt } from \"../schema.js\";\nimport type { Message } from \"../types.messages.js\";\nimport type { BagTemplate } from \"../types.template.js\";\nimport { StreamManager, type EventStreamEvent } from \"./manager.js\";\nimport {\n MessageTupleManager,\n toMessageClass,\n ensureMessageInstances,\n} from \"./messages.js\";\nimport { extractInterrupts } from \"./interrupts.js\";\nimport { getToolCallsWithResults } from \"../utils/tools.js\";\nimport type {\n AnyStreamCustomOptions,\n CustomSubmitOptions,\n MessageMetadata,\n GetUpdateType,\n GetCustomEventType,\n GetInterruptType,\n GetConfigurableType,\n SubagentStreamInterface,\n} from \"./types.js\";\n\n/**\n * Create a custom transport thread state.\n * @param values - The values to use.\n * @param threadId - The ID of the thread to use.\n * @returns The custom transport thread state.\n */\nfunction createCustomTransportThreadState<\n StateType extends Record<string, unknown>\n>(values: StateType, threadId: string): ThreadState<StateType> {\n return {\n values,\n next: [],\n tasks: [],\n metadata: undefined,\n created_at: null,\n checkpoint: {\n thread_id: threadId,\n checkpoint_id: null,\n checkpoint_ns: \"\",\n checkpoint_map: null,\n },\n parent_checkpoint: null,\n };\n}\n\n/**\n * Framework-agnostic orchestrator for custom transport streams.\n *\n * Encapsulates all business logic shared across React, Vue, Svelte, and Angular\n * for custom transport (non-LGP) streaming.\n */\nexport class CustomStreamOrchestrator<\n StateType extends Record<string, unknown> = Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate\n> {\n readonly stream: StreamManager<StateType, Bag>;\n\n readonly messageManager: MessageTupleManager;\n\n readonly #options: AnyStreamCustomOptions<StateType, Bag>;\n\n readonly #historyValues: StateType;\n\n #threadId: string | null;\n\n #branch: string = \"\";\n\n #listeners = new Set<() => void>();\n\n #version = 0;\n\n #streamUnsub: (() => void) | null = null;\n\n #disposed = false;\n\n /**\n * Create a new {@link CustomStreamOrchestrator} instance.\n *\n * @param options - Configuration options for the custom transport stream,\n * including thread ID, transport, callbacks, and subagent settings.\n */\n constructor(options: AnyStreamCustomOptions<StateType, Bag>) {\n this.#options = options;\n\n this.#threadId = options.threadId ?? null;\n\n this.messageManager = new MessageTupleManager();\n this.stream = new StreamManager<StateType, Bag>(this.messageManager, {\n throttle: options.throttle ?? false,\n subagentToolNames: options.subagentToolNames,\n filterSubagentMessages: options.filterSubagentMessages,\n toMessage: options.toMessage ?? toMessageClass,\n });\n\n this.#historyValues = options.initialValues ?? ({} as StateType);\n\n this.#streamUnsub = this.stream.subscribe(() => {\n this.#notify();\n });\n\n const historyMessages = this.#getMessages(this.#historyValues);\n if (\n options.filterSubagentMessages &&\n !this.stream.isLoading &&\n historyMessages.length > 0\n ) {\n this.stream.reconstructSubagents(historyMessages, {\n skipIfPopulated: true,\n });\n }\n }\n\n /**\n * Register a listener that is called whenever the orchestrator state changes.\n *\n * @param listener - Callback invoked on each state change.\n * @returns An unsubscribe function that removes the listener.\n */\n subscribe = (listener: () => void): (() => void) => {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n };\n\n /**\n * Return the current version number, incremented on each state change.\n * Useful as a cache key for external sync (e.g. `useSyncExternalStore`).\n *\n * @returns The current version counter.\n */\n getSnapshot = (): number => this.#version;\n\n #notify(): void {\n if (this.#disposed) return;\n this.#version += 1;\n for (const listener of this.#listeners) {\n listener();\n }\n }\n\n /**\n * Synchronize the external thread ID with the orchestrator.\n * If the ID has changed, the current stream is cleared and listeners\n * are notified.\n *\n * @param newId - The new thread ID, or `null` to clear.\n */\n syncThreadId(newId: string | null): void {\n if (newId !== this.#threadId) {\n this.#threadId = newId;\n this.stream.clear();\n this.#notify();\n }\n }\n\n #getMessages = (value: StateType): Message[] => {\n const messagesKey = this.#options.messagesKey ?? \"messages\";\n return Array.isArray(value[messagesKey])\n ? (value[messagesKey] as Message[])\n : [];\n };\n\n #setMessages = (current: StateType, messages: Message[]): StateType => {\n const messagesKey = this.#options.messagesKey ?? \"messages\";\n return { ...current, [messagesKey]: messages };\n };\n\n /**\n * The current stream state values, falling back to an empty object\n * when no stream values are available.\n */\n get values(): StateType {\n return this.stream.values ?? ({} as StateType);\n }\n\n /**\n * The raw stream state values, or `null` if no stream has been started\n * or values have not yet been received.\n */\n get streamValues(): StateType | null {\n return this.stream.values;\n }\n\n /** The most recent stream error, or `undefined` if no error occurred. */\n get error(): unknown {\n return this.stream.error;\n }\n\n /** Whether a stream is currently in progress. */\n get isLoading(): boolean {\n return this.stream.isLoading;\n }\n\n /** The current branch identifier. */\n get branch(): string {\n return this.#branch;\n }\n\n /**\n * Update the current branch and notify listeners.\n *\n * @param value - The new branch identifier.\n */\n setBranch(value: string): void {\n this.#branch = value;\n this.#notify();\n }\n\n /**\n * All messages from the current stream values, converted to\n * {@link BaseMessage} instances. Returns an empty array when no\n * stream values are available.\n */\n get messages(): BaseMessage[] {\n if (!this.stream.values) return [];\n return ensureMessageInstances(\n this.#getMessages(this.stream.values)\n ) as BaseMessage[];\n }\n\n /**\n * All tool calls paired with their results extracted from the\n * current stream messages.\n */\n get toolCalls() {\n if (!this.stream.values) return [];\n return getToolCallsWithResults(this.#getMessages(this.stream.values));\n }\n\n /**\n * Get tool calls (with results) that belong to a specific AI message.\n *\n * @param message - The AI message whose tool calls to retrieve.\n * @returns Tool calls associated with the given message.\n */\n getToolCalls(message: Message) {\n if (!this.stream.values) return [];\n const allToolCalls = getToolCallsWithResults(\n this.#getMessages(this.stream.values)\n );\n return allToolCalls.filter((tc) => tc.aiMessage.id === message.id);\n }\n\n /**\n * All active interrupts from the current stream values.\n * Returns a single breakpoint interrupt when the interrupt array is\n * present but empty, or an empty array when no interrupts exist.\n */\n get interrupts(): Interrupt<GetInterruptType<Bag>>[] {\n if (\n this.stream.values != null &&\n \"__interrupt__\" in this.stream.values &&\n Array.isArray(this.stream.values.__interrupt__)\n ) {\n const valueInterrupts = this.stream.values.__interrupt__;\n if (valueInterrupts.length === 0) return [{ when: \"breakpoint\" }];\n return valueInterrupts;\n }\n return [];\n }\n\n /**\n * The first active interrupt extracted from the current stream values,\n * or `undefined` if there are no interrupts.\n */\n get interrupt(): Interrupt<GetInterruptType<Bag>> | undefined {\n return extractInterrupts<GetInterruptType<Bag>>(this.stream.values);\n }\n\n /**\n * Retrieve stream-level metadata for a given message.\n *\n * @param message - The message to look up metadata for.\n * @param index - Optional positional index used as fallback message ID.\n * @returns The metadata associated with the message, or `undefined`\n * if no stream metadata is available.\n */\n getMessagesMetadata(\n message: Message,\n index?: number\n ): MessageMetadata<StateType> | undefined {\n const streamMetadata = this.messageManager.get(message.id)?.metadata;\n if (streamMetadata != null) {\n return {\n messageId: message.id ?? String(index),\n firstSeenState: undefined,\n branch: undefined,\n branchOptions: undefined,\n streamMetadata,\n } as MessageMetadata<StateType>;\n }\n return undefined;\n }\n\n /** A map of all tracked subagent streams, keyed by tool call ID. */\n get subagents(): Map<string, SubagentStreamInterface> {\n return this.stream.getSubagents();\n }\n\n /** The subset of subagent streams that are currently active (loading). */\n get activeSubagents(): SubagentStreamInterface[] {\n return this.stream.getActiveSubagents();\n }\n\n /**\n * Look up a single subagent stream by its tool call ID.\n *\n * @param toolCallId - The tool call ID that initiated the subagent.\n * @returns The subagent stream, or `undefined` if not found.\n */\n getSubagent(toolCallId: string) {\n return this.stream.getSubagent(toolCallId);\n }\n\n /**\n * Retrieve all subagent streams matching a given tool name / type.\n *\n * @param type - The subagent type (tool name) to filter by.\n * @returns An array of matching subagent streams.\n */\n getSubagentsByType(type: string) {\n return this.stream.getSubagentsByType(type);\n }\n\n /**\n * Retrieve all subagent streams associated with a specific AI message.\n *\n * @param messageId - The ID of the parent AI message.\n * @returns An array of subagent streams linked to the message.\n */\n getSubagentsByMessage(messageId: string) {\n return this.stream.getSubagentsByMessage(messageId);\n }\n\n /**\n * Reconstruct subagent streams from history values when subagent\n * filtering is enabled and the stream is not currently loading.\n * This is a no-op if subagents are already populated.\n */\n reconstructSubagentsIfNeeded(): void {\n const hvMessages = this.#getMessages(this.#historyValues);\n if (\n this.#options.filterSubagentMessages &&\n !this.stream.isLoading &&\n hvMessages.length > 0\n ) {\n this.stream.reconstructSubagents(hvMessages, { skipIfPopulated: true });\n }\n }\n\n /**\n * Abort the current stream and invoke the `onStop` callback\n * if one was provided in the options.\n */\n stop(): void {\n void this.stream.stop(this.#historyValues, {\n onStop: this.#options.onStop,\n });\n }\n\n /**\n * Switch to a different thread. If the thread ID actually changed,\n * the current stream is cleared and listeners are notified.\n *\n * @param newThreadId - The thread ID to switch to, or `null` to clear.\n */\n switchThread(newThreadId: string | null): void {\n if (newThreadId !== this.#threadId) {\n this.#threadId = newThreadId;\n this.stream.clear();\n this.#notify();\n }\n }\n\n /**\n * Start a new stream run against the custom transport.\n *\n * This is the low-level submit entry point that handles thread ID\n * resolution, optimistic value merging, and transport invocation.\n * Prefer {@link submit} unless you need to bypass higher-level wrappers.\n *\n * @param values - The input values to send, or `null`/`undefined` for\n * a resume-style invocation.\n * @param submitOptions - Optional per-call overrides such as\n * `optimisticValues`, `config`, `command`, and error callbacks.\n */\n async submitDirect(\n values: GetUpdateType<Bag, StateType> | null | undefined,\n submitOptions?: CustomSubmitOptions<StateType, GetConfigurableType<Bag>>\n ): Promise<void> {\n type UpdateType = GetUpdateType<Bag, StateType>;\n type CustomType = GetCustomEventType<Bag>;\n\n const currentThreadId = this.#options.threadId ?? null;\n if (currentThreadId !== this.#threadId) {\n this.#threadId = currentThreadId;\n this.stream.clear();\n }\n\n let usableThreadId = this.#threadId ?? submitOptions?.threadId;\n\n this.stream.setStreamValues(() => {\n if (submitOptions?.optimisticValues != null) {\n return {\n ...this.#historyValues,\n ...(typeof submitOptions.optimisticValues === \"function\"\n ? submitOptions.optimisticValues(this.#historyValues)\n : submitOptions.optimisticValues),\n };\n }\n\n return { ...this.#historyValues };\n });\n\n await this.stream.start(\n async (signal: AbortSignal) => {\n if (!usableThreadId) {\n usableThreadId = crypto.randomUUID();\n this.#threadId = usableThreadId;\n this.#options.onThreadId?.(usableThreadId);\n }\n\n if (!usableThreadId) {\n throw new Error(\"Failed to obtain valid thread ID.\");\n }\n\n return this.#options.transport.stream({\n input: values,\n context: submitOptions?.context,\n command: submitOptions?.command,\n streamSubgraphs: submitOptions?.streamSubgraphs,\n signal,\n config: {\n ...submitOptions?.config,\n configurable: {\n thread_id: usableThreadId,\n ...submitOptions?.config?.configurable,\n } as unknown as GetConfigurableType<Bag>,\n },\n }) as Promise<\n AsyncGenerator<EventStreamEvent<StateType, UpdateType, CustomType>>\n >;\n },\n {\n getMessages: this.#getMessages,\n setMessages: this.#setMessages,\n initialValues: {} as StateType,\n callbacks: this.#options,\n onSuccess: () => {\n if (!usableThreadId) return undefined;\n\n const finalValues = this.stream.values ?? this.#historyValues;\n this.#options.onFinish?.(\n createCustomTransportThreadState(finalValues, usableThreadId),\n undefined\n );\n\n return undefined;\n },\n onError: (error) => {\n this.#options.onError?.(error, undefined);\n submitOptions?.onError?.(error, undefined);\n },\n }\n );\n }\n\n /**\n * Submit input values and start a new stream run.\n *\n * Delegates to {@link submitDirect}. Override or wrap this method\n * in framework adapters to add queuing or other middleware.\n *\n * @param values - The input values to send, or `null`/`undefined` for\n * a resume-style invocation.\n * @param submitOptions - Optional per-call overrides.\n */\n async submit(\n values: GetUpdateType<Bag, StateType> | null | undefined,\n submitOptions?: CustomSubmitOptions<StateType, GetConfigurableType<Bag>>\n ): Promise<void> {\n await this.submitDirect(values, submitOptions);\n }\n\n /**\n * Tear down the orchestrator. Marks the instance as disposed,\n * unsubscribes from the stream, and aborts any in-progress stream.\n * After calling this method, no further notifications will be emitted.\n */\n dispose(): void {\n this.#disposed = true;\n this.#streamUnsub?.();\n this.#streamUnsub = null;\n void this.stream.stop(this.#historyValues, {\n onStop: this.#options.onStop,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AA8BA,SAAS,iCAEP,QAAmB,UAA0C;AAC7D,QAAO;EACL;EACA,MAAM,EAAE;EACR,OAAO,EAAE;EACT,UAAU,KAAA;EACV,YAA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ema.cjs";
|
|
2
|
+
import { DefaultToolCall, Message, ToolCallWithResult } from "../types.messages.cjs";
|
|
3
|
+
import { BagTemplate } from "../types.template.cjs";
|
|
4
|
+
import { AnyStreamCustomOptions, CustomSubmitOptions, GetConfigurableType, GetInterruptType, GetUpdateType, MessageMetadata, SubagentStreamInterface } from "./types.cjs";
|
|
5
|
+
import { MessageTupleManager } from "./messages.cjs";
|
|
6
|
+
import { StreamManager } from "./manager.cjs";
|
|
7
|
+
import { BaseMessage } from "@langchain/core/messages";
|
|
8
|
+
|
|
9
|
+
//#region src/ui/orchestrator-custom.d.ts
|
|
10
|
+
/**
|
|
11
|
+
* Framework-agnostic orchestrator for custom transport streams.
|
|
12
|
+
*
|
|
13
|
+
* Encapsulates all business logic shared across React, Vue, Svelte, and Angular
|
|
14
|
+
* for custom transport (non-LGP) streaming.
|
|
15
|
+
*/
|
|
16
|
+
declare class CustomStreamOrchestrator<StateType extends Record<string, unknown> = Record<string, unknown>, Bag extends BagTemplate = BagTemplate> {
|
|
17
|
+
#private;
|
|
18
|
+
readonly stream: StreamManager<StateType, Bag>;
|
|
19
|
+
readonly messageManager: MessageTupleManager;
|
|
20
|
+
/**
|
|
21
|
+
* Create a new {@link CustomStreamOrchestrator} instance.
|
|
22
|
+
*
|
|
23
|
+
* @param options - Configuration options for the custom transport stream,
|
|
24
|
+
* including thread ID, transport, callbacks, and subagent settings.
|
|
25
|
+
*/
|
|
26
|
+
constructor(options: AnyStreamCustomOptions<StateType, Bag>);
|
|
27
|
+
/**
|
|
28
|
+
* Register a listener that is called whenever the orchestrator state changes.
|
|
29
|
+
*
|
|
30
|
+
* @param listener - Callback invoked on each state change.
|
|
31
|
+
* @returns An unsubscribe function that removes the listener.
|
|
32
|
+
*/
|
|
33
|
+
subscribe: (listener: () => void) => () => void;
|
|
34
|
+
/**
|
|
35
|
+
* Return the current version number, incremented on each state change.
|
|
36
|
+
* Useful as a cache key for external sync (e.g. `useSyncExternalStore`).
|
|
37
|
+
*
|
|
38
|
+
* @returns The current version counter.
|
|
39
|
+
*/
|
|
40
|
+
getSnapshot: () => number;
|
|
41
|
+
/**
|
|
42
|
+
* Synchronize the external thread ID with the orchestrator.
|
|
43
|
+
* If the ID has changed, the current stream is cleared and listeners
|
|
44
|
+
* are notified.
|
|
45
|
+
*
|
|
46
|
+
* @param newId - The new thread ID, or `null` to clear.
|
|
47
|
+
*/
|
|
48
|
+
syncThreadId(newId: string | null): void;
|
|
49
|
+
/**
|
|
50
|
+
* The current stream state values, falling back to an empty object
|
|
51
|
+
* when no stream values are available.
|
|
52
|
+
*/
|
|
53
|
+
get values(): StateType;
|
|
54
|
+
/**
|
|
55
|
+
* The raw stream state values, or `null` if no stream has been started
|
|
56
|
+
* or values have not yet been received.
|
|
57
|
+
*/
|
|
58
|
+
get streamValues(): StateType | null;
|
|
59
|
+
/** The most recent stream error, or `undefined` if no error occurred. */
|
|
60
|
+
get error(): unknown;
|
|
61
|
+
/** Whether a stream is currently in progress. */
|
|
62
|
+
get isLoading(): boolean;
|
|
63
|
+
/** The current branch identifier. */
|
|
64
|
+
get branch(): string;
|
|
65
|
+
/**
|
|
66
|
+
* Update the current branch and notify listeners.
|
|
67
|
+
*
|
|
68
|
+
* @param value - The new branch identifier.
|
|
69
|
+
*/
|
|
70
|
+
setBranch(value: string): void;
|
|
71
|
+
/**
|
|
72
|
+
* All messages from the current stream values, converted to
|
|
73
|
+
* {@link BaseMessage} instances. Returns an empty array when no
|
|
74
|
+
* stream values are available.
|
|
75
|
+
*/
|
|
76
|
+
get messages(): BaseMessage[];
|
|
77
|
+
/**
|
|
78
|
+
* All tool calls paired with their results extracted from the
|
|
79
|
+
* current stream messages.
|
|
80
|
+
*/
|
|
81
|
+
get toolCalls(): ToolCallWithResult<DefaultToolCall>[];
|
|
82
|
+
/**
|
|
83
|
+
* Get tool calls (with results) that belong to a specific AI message.
|
|
84
|
+
*
|
|
85
|
+
* @param message - The AI message whose tool calls to retrieve.
|
|
86
|
+
* @returns Tool calls associated with the given message.
|
|
87
|
+
*/
|
|
88
|
+
getToolCalls(message: Message): ToolCallWithResult<DefaultToolCall>[];
|
|
89
|
+
/**
|
|
90
|
+
* All active interrupts from the current stream values.
|
|
91
|
+
* Returns a single breakpoint interrupt when the interrupt array is
|
|
92
|
+
* present but empty, or an empty array when no interrupts exist.
|
|
93
|
+
*/
|
|
94
|
+
get interrupts(): Interrupt<GetInterruptType<Bag>>[];
|
|
95
|
+
/**
|
|
96
|
+
* The first active interrupt extracted from the current stream values,
|
|
97
|
+
* or `undefined` if there are no interrupts.
|
|
98
|
+
*/
|
|
99
|
+
get interrupt(): Interrupt<GetInterruptType<Bag>> | undefined;
|
|
100
|
+
/**
|
|
101
|
+
* Retrieve stream-level metadata for a given message.
|
|
102
|
+
*
|
|
103
|
+
* @param message - The message to look up metadata for.
|
|
104
|
+
* @param index - Optional positional index used as fallback message ID.
|
|
105
|
+
* @returns The metadata associated with the message, or `undefined`
|
|
106
|
+
* if no stream metadata is available.
|
|
107
|
+
*/
|
|
108
|
+
getMessagesMetadata(message: Message, index?: number): MessageMetadata<StateType> | undefined;
|
|
109
|
+
/** A map of all tracked subagent streams, keyed by tool call ID. */
|
|
110
|
+
get subagents(): Map<string, SubagentStreamInterface>;
|
|
111
|
+
/** The subset of subagent streams that are currently active (loading). */
|
|
112
|
+
get activeSubagents(): SubagentStreamInterface[];
|
|
113
|
+
/**
|
|
114
|
+
* Look up a single subagent stream by its tool call ID.
|
|
115
|
+
*
|
|
116
|
+
* @param toolCallId - The tool call ID that initiated the subagent.
|
|
117
|
+
* @returns The subagent stream, or `undefined` if not found.
|
|
118
|
+
*/
|
|
119
|
+
getSubagent(toolCallId: string): SubagentStreamInterface<Record<string, unknown>, DefaultToolCall, string> | undefined;
|
|
120
|
+
/**
|
|
121
|
+
* Retrieve all subagent streams matching a given tool name / type.
|
|
122
|
+
*
|
|
123
|
+
* @param type - The subagent type (tool name) to filter by.
|
|
124
|
+
* @returns An array of matching subagent streams.
|
|
125
|
+
*/
|
|
126
|
+
getSubagentsByType(type: string): SubagentStreamInterface<Record<string, unknown>, DefaultToolCall, string>[];
|
|
127
|
+
/**
|
|
128
|
+
* Retrieve all subagent streams associated with a specific AI message.
|
|
129
|
+
*
|
|
130
|
+
* @param messageId - The ID of the parent AI message.
|
|
131
|
+
* @returns An array of subagent streams linked to the message.
|
|
132
|
+
*/
|
|
133
|
+
getSubagentsByMessage(messageId: string): SubagentStreamInterface<Record<string, unknown>, DefaultToolCall, string>[];
|
|
134
|
+
/**
|
|
135
|
+
* Reconstruct subagent streams from history values when subagent
|
|
136
|
+
* filtering is enabled and the stream is not currently loading.
|
|
137
|
+
* This is a no-op if subagents are already populated.
|
|
138
|
+
*/
|
|
139
|
+
reconstructSubagentsIfNeeded(): void;
|
|
140
|
+
/**
|
|
141
|
+
* Abort the current stream and invoke the `onStop` callback
|
|
142
|
+
* if one was provided in the options.
|
|
143
|
+
*/
|
|
144
|
+
stop(): void;
|
|
145
|
+
/**
|
|
146
|
+
* Switch to a different thread. If the thread ID actually changed,
|
|
147
|
+
* the current stream is cleared and listeners are notified.
|
|
148
|
+
*
|
|
149
|
+
* @param newThreadId - The thread ID to switch to, or `null` to clear.
|
|
150
|
+
*/
|
|
151
|
+
switchThread(newThreadId: string | null): void;
|
|
152
|
+
/**
|
|
153
|
+
* Start a new stream run against the custom transport.
|
|
154
|
+
*
|
|
155
|
+
* This is the low-level submit entry point that handles thread ID
|
|
156
|
+
* resolution, optimistic value merging, and transport invocation.
|
|
157
|
+
* Prefer {@link submit} unless you need to bypass higher-level wrappers.
|
|
158
|
+
*
|
|
159
|
+
* @param values - The input values to send, or `null`/`undefined` for
|
|
160
|
+
* a resume-style invocation.
|
|
161
|
+
* @param submitOptions - Optional per-call overrides such as
|
|
162
|
+
* `optimisticValues`, `config`, `command`, and error callbacks.
|
|
163
|
+
*/
|
|
164
|
+
submitDirect(values: GetUpdateType<Bag, StateType> | null | undefined, submitOptions?: CustomSubmitOptions<StateType, GetConfigurableType<Bag>>): Promise<void>;
|
|
165
|
+
/**
|
|
166
|
+
* Submit input values and start a new stream run.
|
|
167
|
+
*
|
|
168
|
+
* Delegates to {@link submitDirect}. Override or wrap this method
|
|
169
|
+
* in framework adapters to add queuing or other middleware.
|
|
170
|
+
*
|
|
171
|
+
* @param values - The input values to send, or `null`/`undefined` for
|
|
172
|
+
* a resume-style invocation.
|
|
173
|
+
* @param submitOptions - Optional per-call overrides.
|
|
174
|
+
*/
|
|
175
|
+
submit(values: GetUpdateType<Bag, StateType> | null | undefined, submitOptions?: CustomSubmitOptions<StateType, GetConfigurableType<Bag>>): Promise<void>;
|
|
176
|
+
/**
|
|
177
|
+
* Tear down the orchestrator. Marks the instance as disposed,
|
|
178
|
+
* unsubscribes from the stream, and aborts any in-progress stream.
|
|
179
|
+
* After calling this method, no further notifications will be emitted.
|
|
180
|
+
*/
|
|
181
|
+
dispose(): void;
|
|
182
|
+
}
|
|
183
|
+
//#endregion
|
|
184
|
+
export { CustomStreamOrchestrator };
|
|
185
|
+
//# sourceMappingURL=orchestrator-custom.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrator-custom.d.cts","names":[],"sources":["../../src/ui/orchestrator-custom.ts"],"mappings":";;;;;;;;;;;AAuDA;;;;cAAa,wBAAA,mBACO,MAAA,oBAA0B,MAAA,+BAChC,WAAA,GAAc,WAAA;EAAA;WAEjB,MAAA,EAAQ,aAAA,CAAc,SAAA,EAAW,GAAA;EAAA,SAEjC,cAAA,EAAgB,mBAAA;EAFiB;;;;;;EA0B1C,WAAA,CAAY,OAAA,EAAS,sBAAA,CAAuB,SAAA,EAAW,GAAA;EAmGnC;;;;;;EA9DpB,SAAA,GAAS,QAAA;EAmIoC;;;;;;EAtH7C,WAAA;EAsJmB;;;;;;;EArInB,YAAA,CAAa,KAAA;EA6KkB;;;;EAAA,IArJ3B,MAAA,CAAA,GAAU,SAAA;EA+JyB;;;;EAAA,IAvJnC,YAAA,CAAA,GAAgB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