@langchain/langgraph-sdk 1.3.1 → 1.4.4
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/package.json +5 -5
- package/CHANGELOG.md +0 -281
- package/dist/_virtual/rolldown_runtime.cjs +0 -25
- package/dist/auth/error.cjs +0 -79
- package/dist/auth/error.cjs.map +0 -1
- package/dist/auth/error.d.cts +0 -13
- package/dist/auth/error.d.cts.map +0 -1
- package/dist/auth/error.d.ts +0 -13
- package/dist/auth/error.d.ts.map +0 -1
- package/dist/auth/error.js +0 -78
- package/dist/auth/error.js.map +0 -1
- package/dist/auth/index.cjs +0 -39
- package/dist/auth/index.cjs.map +0 -1
- package/dist/auth/index.d.cts +0 -31
- package/dist/auth/index.d.cts.map +0 -1
- package/dist/auth/index.d.ts +0 -31
- package/dist/auth/index.d.ts.map +0 -1
- package/dist/auth/index.js +0 -37
- package/dist/auth/index.js.map +0 -1
- package/dist/auth/types.d.cts +0 -294
- package/dist/auth/types.d.cts.map +0 -1
- package/dist/auth/types.d.ts +0 -294
- package/dist/auth/types.d.ts.map +0 -1
- package/dist/client.cjs +0 -1219
- package/dist/client.cjs.map +0 -1
- package/dist/client.d.cts +0 -803
- package/dist/client.d.cts.map +0 -1
- package/dist/client.d.ts +0 -803
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -1212
- package/dist/client.js.map +0 -1
- package/dist/index.cjs +0 -6
- package/dist/index.d.cts +0 -7
- package/dist/index.d.ts +0 -7
- package/dist/index.js +0 -4
- package/dist/logging/index.cjs +0 -35
- package/dist/logging/index.cjs.map +0 -1
- package/dist/logging/index.d.cts +0 -47
- package/dist/logging/index.d.cts.map +0 -1
- package/dist/logging/index.d.ts +0 -47
- package/dist/logging/index.d.ts.map +0 -1
- package/dist/logging/index.js +0 -34
- package/dist/logging/index.js.map +0 -1
- package/dist/react/index.cjs +0 -5
- package/dist/react/index.d.cts +0 -4
- package/dist/react/index.d.ts +0 -4
- package/dist/react/index.js +0 -4
- package/dist/react/stream.cjs +0 -18
- package/dist/react/stream.cjs.map +0 -1
- package/dist/react/stream.custom.cjs +0 -129
- package/dist/react/stream.custom.cjs.map +0 -1
- package/dist/react/stream.custom.d.cts +0 -39
- package/dist/react/stream.custom.d.cts.map +0 -1
- package/dist/react/stream.custom.d.ts +0 -39
- package/dist/react/stream.custom.d.ts.map +0 -1
- package/dist/react/stream.custom.js +0 -127
- package/dist/react/stream.custom.js.map +0 -1
- package/dist/react/stream.d.cts +0 -73
- package/dist/react/stream.d.cts.map +0 -1
- package/dist/react/stream.d.ts +0 -73
- package/dist/react/stream.d.ts.map +0 -1
- package/dist/react/stream.js +0 -17
- package/dist/react/stream.js.map +0 -1
- package/dist/react/stream.lgp.cjs +0 -446
- package/dist/react/stream.lgp.cjs.map +0 -1
- package/dist/react/stream.lgp.js +0 -445
- package/dist/react/stream.lgp.js.map +0 -1
- package/dist/react/thread.cjs +0 -22
- package/dist/react/thread.cjs.map +0 -1
- package/dist/react/thread.js +0 -21
- package/dist/react/thread.js.map +0 -1
- package/dist/react/types.d.cts +0 -363
- package/dist/react/types.d.cts.map +0 -1
- package/dist/react/types.d.ts +0 -363
- package/dist/react/types.d.ts.map +0 -1
- package/dist/react-ui/client.cjs +0 -137
- package/dist/react-ui/client.cjs.map +0 -1
- package/dist/react-ui/client.d.cts +0 -90
- package/dist/react-ui/client.d.cts.map +0 -1
- package/dist/react-ui/client.d.ts +0 -90
- package/dist/react-ui/client.d.ts.map +0 -1
- package/dist/react-ui/client.js +0 -134
- package/dist/react-ui/client.js.map +0 -1
- package/dist/react-ui/index.cjs +0 -14
- package/dist/react-ui/index.cjs.map +0 -1
- package/dist/react-ui/index.d.cts +0 -3
- package/dist/react-ui/index.d.ts +0 -3
- package/dist/react-ui/index.js +0 -9
- package/dist/react-ui/index.js.map +0 -1
- package/dist/react-ui/server/index.cjs +0 -5
- package/dist/react-ui/server/index.d.cts +0 -3
- package/dist/react-ui/server/index.d.ts +0 -3
- package/dist/react-ui/server/index.js +0 -4
- package/dist/react-ui/server/server.cjs +0 -57
- package/dist/react-ui/server/server.cjs.map +0 -1
- package/dist/react-ui/server/server.d.cts +0 -55
- package/dist/react-ui/server/server.d.cts.map +0 -1
- package/dist/react-ui/server/server.d.ts +0 -55
- package/dist/react-ui/server/server.d.ts.map +0 -1
- package/dist/react-ui/server/server.js +0 -56
- package/dist/react-ui/server/server.js.map +0 -1
- package/dist/react-ui/types.cjs +0 -38
- package/dist/react-ui/types.cjs.map +0 -1
- package/dist/react-ui/types.d.cts +0 -25
- package/dist/react-ui/types.d.cts.map +0 -1
- package/dist/react-ui/types.d.ts +0 -25
- package/dist/react-ui/types.d.ts.map +0 -1
- package/dist/react-ui/types.js +0 -35
- package/dist/react-ui/types.js.map +0 -1
- package/dist/schema.d.cts +0 -284
- package/dist/schema.d.cts.map +0 -1
- package/dist/schema.d.ts +0 -284
- package/dist/schema.d.ts.map +0 -1
- package/dist/singletons/fetch.cjs +0 -24
- package/dist/singletons/fetch.cjs.map +0 -1
- package/dist/singletons/fetch.d.cts +0 -14
- package/dist/singletons/fetch.d.cts.map +0 -1
- package/dist/singletons/fetch.d.ts +0 -14
- package/dist/singletons/fetch.d.ts.map +0 -1
- package/dist/singletons/fetch.js +0 -22
- package/dist/singletons/fetch.js.map +0 -1
- package/dist/types.d.cts +0 -187
- package/dist/types.d.cts.map +0 -1
- package/dist/types.d.ts +0 -187
- package/dist/types.d.ts.map +0 -1
- package/dist/types.messages.d.cts +0 -91
- package/dist/types.messages.d.cts.map +0 -1
- package/dist/types.messages.d.ts +0 -91
- package/dist/types.messages.d.ts.map +0 -1
- package/dist/types.stream.d.cts +0 -235
- package/dist/types.stream.d.cts.map +0 -1
- package/dist/types.stream.d.ts +0 -235
- package/dist/types.stream.d.ts.map +0 -1
- package/dist/ui/branching.cjs +0 -153
- package/dist/ui/branching.cjs.map +0 -1
- package/dist/ui/branching.d.cts +0 -22
- package/dist/ui/branching.d.cts.map +0 -1
- package/dist/ui/branching.d.ts +0 -22
- package/dist/ui/branching.d.ts.map +0 -1
- package/dist/ui/branching.js +0 -152
- package/dist/ui/branching.js.map +0 -1
- package/dist/ui/errors.cjs +0 -15
- package/dist/ui/errors.cjs.map +0 -1
- package/dist/ui/errors.js +0 -14
- package/dist/ui/errors.js.map +0 -1
- package/dist/ui/manager.cjs +0 -182
- package/dist/ui/manager.cjs.map +0 -1
- package/dist/ui/manager.js +0 -182
- package/dist/ui/manager.js.map +0 -1
- package/dist/ui/messages.cjs +0 -70
- package/dist/ui/messages.cjs.map +0 -1
- package/dist/ui/messages.js +0 -68
- package/dist/ui/messages.js.map +0 -1
- package/dist/ui/utils.cjs +0 -14
- package/dist/ui/utils.cjs.map +0 -1
- package/dist/ui/utils.js +0 -12
- package/dist/ui/utils.js.map +0 -1
- package/dist/utils/async_caller.cjs +0 -111
- package/dist/utils/async_caller.cjs.map +0 -1
- package/dist/utils/async_caller.d.cts +0 -53
- package/dist/utils/async_caller.d.cts.map +0 -1
- package/dist/utils/async_caller.d.ts +0 -53
- package/dist/utils/async_caller.d.ts.map +0 -1
- package/dist/utils/async_caller.js +0 -110
- package/dist/utils/async_caller.js.map +0 -1
- package/dist/utils/env.cjs +0 -13
- package/dist/utils/env.cjs.map +0 -1
- package/dist/utils/env.js +0 -12
- package/dist/utils/env.js.map +0 -1
- package/dist/utils/error.cjs +0 -17
- package/dist/utils/error.cjs.map +0 -1
- package/dist/utils/error.js +0 -16
- package/dist/utils/error.js.map +0 -1
- package/dist/utils/signals.cjs +0 -20
- package/dist/utils/signals.cjs.map +0 -1
- package/dist/utils/signals.js +0 -19
- package/dist/utils/signals.js.map +0 -1
- package/dist/utils/sse.cjs +0 -124
- package/dist/utils/sse.cjs.map +0 -1
- package/dist/utils/sse.js +0 -122
- package/dist/utils/sse.js.map +0 -1
- package/dist/utils/stream.cjs +0 -176
- package/dist/utils/stream.cjs.map +0 -1
- package/dist/utils/stream.js +0 -175
- package/dist/utils/stream.js.map +0 -1
package/dist/ui/branching.js
DELETED
|
@@ -1,152 +0,0 @@
|
|
|
1
|
-
//#region src/ui/branching.ts
|
|
2
|
-
function getBranchSequence(history) {
|
|
3
|
-
const nodeIds = /* @__PURE__ */ new Set();
|
|
4
|
-
const childrenMap = {};
|
|
5
|
-
if (history.length <= 1) return {
|
|
6
|
-
rootSequence: {
|
|
7
|
-
type: "sequence",
|
|
8
|
-
items: history.map((value) => ({
|
|
9
|
-
type: "node",
|
|
10
|
-
value,
|
|
11
|
-
path: []
|
|
12
|
-
}))
|
|
13
|
-
},
|
|
14
|
-
paths: []
|
|
15
|
-
};
|
|
16
|
-
history.forEach((state) => {
|
|
17
|
-
const checkpointId = state.parent_checkpoint?.checkpoint_id ?? "$";
|
|
18
|
-
childrenMap[checkpointId] ??= [];
|
|
19
|
-
childrenMap[checkpointId].push(state);
|
|
20
|
-
if (state.checkpoint?.checkpoint_id != null) nodeIds.add(state.checkpoint.checkpoint_id);
|
|
21
|
-
});
|
|
22
|
-
const maxId = (...ids) => ids.filter((i) => i != null).sort((a, b) => a.localeCompare(b)).at(-1);
|
|
23
|
-
const lastOrphanedNode = childrenMap.$ == null ? Object.keys(childrenMap).filter((parentId) => !nodeIds.has(parentId)).map((parentId) => {
|
|
24
|
-
const queue$1 = [parentId];
|
|
25
|
-
const seen = /* @__PURE__ */ new Set();
|
|
26
|
-
let lastId = parentId;
|
|
27
|
-
while (queue$1.length > 0) {
|
|
28
|
-
const current = queue$1.shift();
|
|
29
|
-
if (seen.has(current)) continue;
|
|
30
|
-
seen.add(current);
|
|
31
|
-
const children = (childrenMap[current] ?? []).flatMap((i) => i.checkpoint?.checkpoint_id ?? []);
|
|
32
|
-
lastId = maxId(lastId, ...children);
|
|
33
|
-
queue$1.push(...children);
|
|
34
|
-
}
|
|
35
|
-
return {
|
|
36
|
-
parentId,
|
|
37
|
-
lastId
|
|
38
|
-
};
|
|
39
|
-
}).sort((a, b) => a.lastId.localeCompare(b.lastId)).at(-1)?.parentId : void 0;
|
|
40
|
-
if (lastOrphanedNode != null) childrenMap.$ = childrenMap[lastOrphanedNode];
|
|
41
|
-
const rootSequence = {
|
|
42
|
-
type: "sequence",
|
|
43
|
-
items: []
|
|
44
|
-
};
|
|
45
|
-
const queue = [{
|
|
46
|
-
id: "$",
|
|
47
|
-
sequence: rootSequence,
|
|
48
|
-
path: []
|
|
49
|
-
}];
|
|
50
|
-
const paths = [];
|
|
51
|
-
const visited = /* @__PURE__ */ new Set();
|
|
52
|
-
while (queue.length > 0) {
|
|
53
|
-
const task = queue.shift();
|
|
54
|
-
if (visited.has(task.id)) continue;
|
|
55
|
-
visited.add(task.id);
|
|
56
|
-
const children = childrenMap[task.id];
|
|
57
|
-
if (children == null || children.length === 0) continue;
|
|
58
|
-
let fork;
|
|
59
|
-
if (children.length > 1) {
|
|
60
|
-
fork = {
|
|
61
|
-
type: "fork",
|
|
62
|
-
items: []
|
|
63
|
-
};
|
|
64
|
-
task.sequence.items.push(fork);
|
|
65
|
-
}
|
|
66
|
-
for (const value of children) {
|
|
67
|
-
const id = value.checkpoint?.checkpoint_id;
|
|
68
|
-
if (id == null) continue;
|
|
69
|
-
let { sequence } = task;
|
|
70
|
-
let { path } = task;
|
|
71
|
-
if (fork != null) {
|
|
72
|
-
sequence = {
|
|
73
|
-
type: "sequence",
|
|
74
|
-
items: []
|
|
75
|
-
};
|
|
76
|
-
fork.items.unshift(sequence);
|
|
77
|
-
path = path.slice();
|
|
78
|
-
path.push(id);
|
|
79
|
-
paths.push(path);
|
|
80
|
-
}
|
|
81
|
-
sequence.items.push({
|
|
82
|
-
type: "node",
|
|
83
|
-
value,
|
|
84
|
-
path
|
|
85
|
-
});
|
|
86
|
-
queue.push({
|
|
87
|
-
id,
|
|
88
|
-
sequence,
|
|
89
|
-
path
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return {
|
|
94
|
-
rootSequence,
|
|
95
|
-
paths
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
const PATH_SEP = ">";
|
|
99
|
-
const ROOT_ID = "$";
|
|
100
|
-
function getBranchView(sequence, paths, branch) {
|
|
101
|
-
const path = branch.split(PATH_SEP);
|
|
102
|
-
const pathMap = {};
|
|
103
|
-
for (const path$1 of paths) {
|
|
104
|
-
const parent = path$1.at(-2) ?? ROOT_ID;
|
|
105
|
-
pathMap[parent] ??= [];
|
|
106
|
-
pathMap[parent].unshift(path$1);
|
|
107
|
-
}
|
|
108
|
-
const history = [];
|
|
109
|
-
const branchByCheckpoint = {};
|
|
110
|
-
const forkStack = path.slice();
|
|
111
|
-
const queue = [...sequence.items];
|
|
112
|
-
while (queue.length > 0) {
|
|
113
|
-
const item = queue.shift();
|
|
114
|
-
if (item.type === "node") {
|
|
115
|
-
history.push(item.value);
|
|
116
|
-
const checkpointId = item.value.checkpoint?.checkpoint_id;
|
|
117
|
-
if (checkpointId == null) continue;
|
|
118
|
-
branchByCheckpoint[checkpointId] = {
|
|
119
|
-
branch: item.path.join(PATH_SEP),
|
|
120
|
-
branchOptions: (item.path.length > 0 ? pathMap[item.path.at(-2) ?? ROOT_ID] ?? [] : []).map((p) => p.join(PATH_SEP))
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
if (item.type === "fork") {
|
|
124
|
-
const forkId = forkStack.shift();
|
|
125
|
-
const index = forkId != null ? item.items.findIndex((value) => {
|
|
126
|
-
const firstItem = value.items.at(0);
|
|
127
|
-
if (!firstItem || firstItem.type !== "node") return false;
|
|
128
|
-
return firstItem.value.checkpoint?.checkpoint_id === forkId;
|
|
129
|
-
}) : -1;
|
|
130
|
-
const nextItems = item.items.at(index)?.items ?? [];
|
|
131
|
-
queue.push(...nextItems);
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
return {
|
|
135
|
-
history,
|
|
136
|
-
branchByCheckpoint
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
function getBranchContext(branch, history) {
|
|
140
|
-
const { rootSequence: branchTree, paths } = getBranchSequence(history ?? []);
|
|
141
|
-
const { history: flatHistory, branchByCheckpoint } = getBranchView(branchTree, paths, branch);
|
|
142
|
-
return {
|
|
143
|
-
branchTree,
|
|
144
|
-
flatHistory,
|
|
145
|
-
branchByCheckpoint,
|
|
146
|
-
threadHead: flatHistory.at(-1)
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
//#endregion
|
|
151
|
-
export { getBranchContext };
|
|
152
|
-
//# sourceMappingURL=branching.js.map
|
package/dist/ui/branching.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"branching.js","names":["childrenMap: Record<string, ThreadState<StateType>[]>","queue: string[]","queue","rootSequence: Sequence","queue: Task[]","paths: string[][]","fork: Fork | undefined","pathMap: Record<string, string[][]>","path","history: ThreadState<StateType>[]","branchByCheckpoint: Record<\n string,\n { branch: string | undefined; branchOptions: string[] | undefined }\n >","queue: (Node<StateType> | Fork<StateType>)[]"],"sources":["../../src/ui/branching.ts"],"sourcesContent":["import type { ThreadState } from \"../schema.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface Node<StateType = any> {\n type: \"node\";\n value: ThreadState<StateType>;\n path: string[];\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface Fork<StateType = any> {\n type: \"fork\";\n items: Array<Sequence<StateType>>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport interface Sequence<StateType = any> {\n type: \"sequence\";\n items: Array<Node<StateType> | Fork<StateType>>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ValidFork<StateType = any> {\n type: \"fork\";\n items: Array<ValidSequence<StateType>>;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ninterface ValidSequence<StateType = any> {\n type: \"sequence\";\n items: [Node<StateType>, ...(Node<StateType> | ValidFork<StateType>)[]];\n}\n\nexport function getBranchSequence<StateType extends Record<string, unknown>>(\n history: ThreadState<StateType>[]\n) {\n const nodeIds = new Set<string>();\n const childrenMap: Record<string, ThreadState<StateType>[]> = {};\n\n // Short circuit if there's only a singular one state\n if (history.length <= 1) {\n return {\n rootSequence: {\n type: \"sequence\",\n items: history.map((value) => ({ type: \"node\", value, path: [] })),\n } satisfies Sequence<StateType>,\n paths: [],\n };\n }\n\n // First pass - collect nodes for each checkpoint\n history.forEach((state) => {\n const checkpointId = state.parent_checkpoint?.checkpoint_id ?? \"$\";\n childrenMap[checkpointId] ??= [];\n childrenMap[checkpointId].push(state);\n\n if (state.checkpoint?.checkpoint_id != null) {\n nodeIds.add(state.checkpoint.checkpoint_id);\n }\n });\n\n // If dealing with partial history, take the branch\n // with the latest checkpoint and mark it as the root.\n const maxId = (...ids: (string | null)[]) =>\n ids\n .filter((i) => i != null)\n .sort((a, b) => a.localeCompare(b))\n .at(-1)!;\n\n const lastOrphanedNode =\n childrenMap.$ == null\n ? Object.keys(childrenMap)\n .filter((parentId) => !nodeIds.has(parentId))\n .map((parentId) => {\n const queue: string[] = [parentId];\n const seen = new Set<string>();\n\n let lastId = parentId;\n\n while (queue.length > 0) {\n const current = queue.shift()!;\n\n if (seen.has(current)) continue;\n seen.add(current);\n\n const children = (childrenMap[current] ?? []).flatMap(\n (i) => i.checkpoint?.checkpoint_id ?? []\n );\n\n lastId = maxId(lastId, ...children);\n queue.push(...children);\n }\n\n return { parentId, lastId };\n })\n .sort((a, b) => a.lastId.localeCompare(b.lastId))\n .at(-1)?.parentId\n : undefined;\n\n if (lastOrphanedNode != null) childrenMap.$ = childrenMap[lastOrphanedNode];\n\n // Second pass - create a tree of sequences\n type Task = { id: string; sequence: Sequence; path: string[] };\n const rootSequence: Sequence = { type: \"sequence\", items: [] };\n const queue: Task[] = [{ id: \"$\", sequence: rootSequence, path: [] }];\n\n const paths: string[][] = [];\n\n const visited = new Set<string>();\n while (queue.length > 0) {\n const task = queue.shift()!;\n if (visited.has(task.id)) continue;\n visited.add(task.id);\n\n const children = childrenMap[task.id];\n if (children == null || children.length === 0) continue;\n\n // If we've encountered a fork (2+ children), push the fork\n // to the sequence and add a new sequence for each child\n let fork: Fork | undefined;\n if (children.length > 1) {\n fork = { type: \"fork\", items: [] };\n task.sequence.items.push(fork);\n }\n\n for (const value of children) {\n const id = value.checkpoint?.checkpoint_id;\n if (id == null) continue;\n\n let { sequence } = task;\n let { path } = task;\n if (fork != null) {\n sequence = { type: \"sequence\", items: [] };\n fork.items.unshift(sequence);\n\n path = path.slice();\n path.push(id);\n paths.push(path);\n }\n\n sequence.items.push({ type: \"node\", value, path });\n queue.push({ id, sequence, path });\n }\n }\n\n return { rootSequence, paths };\n}\n\nconst PATH_SEP = \">\";\nconst ROOT_ID = \"$\";\n\n// Get flat view\nexport function getBranchView<StateType extends Record<string, unknown>>(\n sequence: Sequence<StateType>,\n paths: string[][],\n branch: string\n) {\n const path = branch.split(PATH_SEP);\n const pathMap: Record<string, string[][]> = {};\n\n for (const path of paths) {\n const parent = path.at(-2) ?? ROOT_ID;\n pathMap[parent] ??= [];\n pathMap[parent].unshift(path);\n }\n\n const history: ThreadState<StateType>[] = [];\n const branchByCheckpoint: Record<\n string,\n { branch: string | undefined; branchOptions: string[] | undefined }\n > = {};\n\n const forkStack = path.slice();\n const queue: (Node<StateType> | Fork<StateType>)[] = [...sequence.items];\n\n while (queue.length > 0) {\n const item = queue.shift()!;\n\n if (item.type === \"node\") {\n history.push(item.value);\n const checkpointId = item.value.checkpoint?.checkpoint_id;\n if (checkpointId == null) continue;\n\n branchByCheckpoint[checkpointId] = {\n branch: item.path.join(PATH_SEP),\n branchOptions: (item.path.length > 0\n ? pathMap[item.path.at(-2) ?? ROOT_ID] ?? []\n : []\n ).map((p) => p.join(PATH_SEP)),\n };\n }\n if (item.type === \"fork\") {\n const forkId = forkStack.shift();\n const index =\n forkId != null\n ? item.items.findIndex((value) => {\n const firstItem = value.items.at(0);\n if (!firstItem || firstItem.type !== \"node\") return false;\n return firstItem.value.checkpoint?.checkpoint_id === forkId;\n })\n : -1;\n\n const nextItems = item.items.at(index)?.items ?? [];\n queue.push(...nextItems);\n }\n }\n\n return { history, branchByCheckpoint };\n}\n\nexport function getBranchContext<StateType extends Record<string, unknown>>(\n branch: string,\n history: ThreadState<StateType>[] | undefined\n) {\n const { rootSequence: branchTree, paths } = getBranchSequence(history ?? []);\n const { history: flatHistory, branchByCheckpoint } = getBranchView(\n branchTree,\n paths,\n branch\n );\n\n return {\n branchTree,\n flatHistory,\n branchByCheckpoint,\n threadHead: flatHistory.at(-1),\n };\n}\n"],"mappings":";AAiCA,SAAgB,kBACd,SACA;CACA,MAAM,0BAAU,IAAI;CACpB,MAAMA,cAAwD;AAG9D,KAAI,QAAQ,UAAU,EACpB,QAAO;EACL,cAAc;GACZ,MAAM;GACN,OAAO,QAAQ,KAAK,WAAW;IAAE,MAAM;IAAQ;IAAO,MAAM;;;EAE9D,OAAO;;AAKX,SAAQ,SAAS,UAAU;EACzB,MAAM,eAAe,MAAM,mBAAmB,iBAAiB;AAC/D,cAAY,kBAAkB;AAC9B,cAAY,cAAc,KAAK;AAE/B,MAAI,MAAM,YAAY,iBAAiB,KACrC,SAAQ,IAAI,MAAM,WAAW;;CAMjC,MAAM,SAAS,GAAG,QAChB,IACG,QAAQ,MAAM,KAAK,MACnB,MAAM,GAAG,MAAM,EAAE,cAAc,IAC/B,GAAG;CAER,MAAM,mBACJ,YAAY,KAAK,OACb,OAAO,KAAK,aACT,QAAQ,aAAa,CAAC,QAAQ,IAAI,WAClC,KAAK,aAAa;EACjB,MAAMC,UAAkB,CAAC;EACzB,MAAM,uBAAO,IAAI;EAEjB,IAAI,SAAS;AAEb,SAAOC,QAAM,SAAS,GAAG;GACvB,MAAM,UAAUA,QAAM;AAEtB,OAAI,KAAK,IAAI,SAAU;AACvB,QAAK,IAAI;GAET,MAAM,YAAY,YAAY,YAAY,IAAI,SAC3C,MAAM,EAAE,YAAY,iBAAiB;AAGxC,YAAS,MAAM,QAAQ,GAAG;AAC1B,WAAM,KAAK,GAAG;;AAGhB,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,QAAQA;;CAG1B,MAAMC,UAAoC;CAC1C,MAAMC,qBAGF;CAEJ,MAAM,YAAY,KAAK;CACvB,MAAMC,QAA+C,CAAC,GAAG,SAAS;AAElE,QAAO,MAAM,SAAS,GAAG;EACvB,MAAM,OAAO,MAAM;AAEnB,MAAI,KAAK,SAAS,QAAQ;AACxB,WAAQ,KAAK,KAAK;GAClB,MAAM,eAAe,KAAK,MAAM,YAAY;AAC5C,OAAI,gBAAgB,KAAM;AAE1B,sBAAmB,gBAAgB;IACjC,QAAQ,KAAK,KAAK,KAAK;IACvB,gBAAgB,KAAK,KAAK,SAAS,IAC/B,QAAQ,KAAK,KAAK,GAAG,OAAO,YAAY,KACxC,IACF,KAAK,MAAM,EAAE,KAAK;;;AAGxB,MAAI,KAAK,SAAS,QAAQ;GACxB,MAAM,SAAS,UAAU;GACzB,MAAM,QACJ,UAAU,OACN,KAAK,MAAM,WAAW,UAAU;IAC9B,MAAM,YAAY,MAAM,MAAM,GAAG;AACjC,QAAI,CAAC,aAAa,UAAU,SAAS,OAAQ,QAAO;AACpD,WAAO,UAAU,MAAM,YAAY,kBAAkB;QAEvD;GAEN,MAAM,YAAY,KAAK,MAAM,GAAG,QAAQ,SAAS;AACjD,SAAM,KAAK,GAAG;;;AAIlB,QAAO;EAAE;EAAS;;;AAGpB,SAAgB,iBACd,QACA,SACA;CACA,MAAM,EAAE,cAAc,YAAY,UAAU,kBAAkB,WAAW;CACzE,MAAM,EAAE,SAAS,aAAa,uBAAuB,cACnD,YACA,OACA;AAGF,QAAO;EACL;EACA;EACA;EACA,YAAY,YAAY,GAAG"}
|
package/dist/ui/errors.cjs
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
//#region src/ui/errors.ts
|
|
3
|
-
var StreamError = class extends Error {
|
|
4
|
-
constructor(data) {
|
|
5
|
-
super(data.message);
|
|
6
|
-
this.name = data.name ?? data.error ?? "StreamError";
|
|
7
|
-
}
|
|
8
|
-
static isStructuredError(error) {
|
|
9
|
-
return typeof error === "object" && error != null && "message" in error;
|
|
10
|
-
}
|
|
11
|
-
};
|
|
12
|
-
|
|
13
|
-
//#endregion
|
|
14
|
-
exports.StreamError = StreamError;
|
|
15
|
-
//# sourceMappingURL=errors.cjs.map
|
package/dist/ui/errors.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":[],"sources":["../../src/ui/errors.ts"],"sourcesContent":["export class StreamError extends Error {\n constructor(data: { error?: string; name?: string; message: string }) {\n super(data.message);\n this.name = data.name ?? data.error ?? \"StreamError\";\n }\n\n static isStructuredError(error: unknown): error is {\n error?: string;\n name?: string;\n message: string;\n } {\n return typeof error === \"object\" && error != null && \"message\" in error;\n }\n}\n"],"mappings":";;AAAA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,MAA0D;AACpE,QAAM,KAAK;AACX,OAAK,OAAO,KAAK,QAAQ,KAAK,SAAS;;CAGzC,OAAO,kBAAkB,OAIvB;AACA,SAAO,OAAO,UAAU,YAAY,SAAS,QAAQ,aAAa"}
|
package/dist/ui/errors.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
//#region src/ui/errors.ts
|
|
2
|
-
var StreamError = class extends Error {
|
|
3
|
-
constructor(data) {
|
|
4
|
-
super(data.message);
|
|
5
|
-
this.name = data.name ?? data.error ?? "StreamError";
|
|
6
|
-
}
|
|
7
|
-
static isStructuredError(error) {
|
|
8
|
-
return typeof error === "object" && error != null && "message" in error;
|
|
9
|
-
}
|
|
10
|
-
};
|
|
11
|
-
|
|
12
|
-
//#endregion
|
|
13
|
-
export { StreamError };
|
|
14
|
-
//# sourceMappingURL=errors.js.map
|
package/dist/ui/errors.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":[],"sources":["../../src/ui/errors.ts"],"sourcesContent":["export class StreamError extends Error {\n constructor(data: { error?: string; name?: string; message: string }) {\n super(data.message);\n this.name = data.name ?? data.error ?? \"StreamError\";\n }\n\n static isStructuredError(error: unknown): error is {\n error?: string;\n name?: string;\n message: string;\n } {\n return typeof error === \"object\" && error != null && \"message\" in error;\n }\n}\n"],"mappings":";AAAA,IAAa,cAAb,cAAiC,MAAM;CACrC,YAAY,MAA0D;AACpE,QAAM,KAAK;AACX,OAAK,OAAO,KAAK,QAAQ,KAAK,SAAS;;CAGzC,OAAO,kBAAkB,OAIvB;AACA,SAAO,OAAO,UAAU,YAAY,SAAS,QAAQ,aAAa"}
|
package/dist/ui/manager.cjs
DELETED
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
const require_errors = require('./errors.cjs');
|
|
2
|
-
const require_messages = require('./messages.cjs');
|
|
3
|
-
|
|
4
|
-
//#region src/ui/manager.ts
|
|
5
|
-
var StreamManager = class {
|
|
6
|
-
abortRef = new AbortController();
|
|
7
|
-
messages;
|
|
8
|
-
listeners = /* @__PURE__ */ new Set();
|
|
9
|
-
throttle;
|
|
10
|
-
queue = Promise.resolve();
|
|
11
|
-
queueSize = 0;
|
|
12
|
-
state;
|
|
13
|
-
constructor(messages, options) {
|
|
14
|
-
this.messages = messages;
|
|
15
|
-
this.state = {
|
|
16
|
-
isLoading: false,
|
|
17
|
-
values: null,
|
|
18
|
-
error: void 0
|
|
19
|
-
};
|
|
20
|
-
this.throttle = options.throttle;
|
|
21
|
-
}
|
|
22
|
-
setState = (newState) => {
|
|
23
|
-
this.state = {
|
|
24
|
-
...this.state,
|
|
25
|
-
...newState
|
|
26
|
-
};
|
|
27
|
-
this.notifyListeners();
|
|
28
|
-
};
|
|
29
|
-
notifyListeners = () => {
|
|
30
|
-
this.listeners.forEach((listener) => listener());
|
|
31
|
-
};
|
|
32
|
-
subscribe = (listener) => {
|
|
33
|
-
if (this.throttle === false) {
|
|
34
|
-
this.listeners.add(listener);
|
|
35
|
-
return () => this.listeners.delete(listener);
|
|
36
|
-
}
|
|
37
|
-
const timeoutMs = this.throttle === true ? 0 : this.throttle;
|
|
38
|
-
let timeoutId;
|
|
39
|
-
const throttledListener = () => {
|
|
40
|
-
clearTimeout(timeoutId);
|
|
41
|
-
timeoutId = setTimeout(() => {
|
|
42
|
-
clearTimeout(timeoutId);
|
|
43
|
-
listener();
|
|
44
|
-
}, timeoutMs);
|
|
45
|
-
};
|
|
46
|
-
this.listeners.add(throttledListener);
|
|
47
|
-
return () => {
|
|
48
|
-
clearTimeout(timeoutId);
|
|
49
|
-
this.listeners.delete(throttledListener);
|
|
50
|
-
};
|
|
51
|
-
};
|
|
52
|
-
getSnapshot = () => this.state;
|
|
53
|
-
get isLoading() {
|
|
54
|
-
return this.state.isLoading;
|
|
55
|
-
}
|
|
56
|
-
get values() {
|
|
57
|
-
return this.state.values?.[0] ?? null;
|
|
58
|
-
}
|
|
59
|
-
get error() {
|
|
60
|
-
return this.state.error;
|
|
61
|
-
}
|
|
62
|
-
setStreamValues = (values, kind = "stream") => {
|
|
63
|
-
if (typeof values === "function") {
|
|
64
|
-
const [prevValues, prevKind] = this.state.values ?? [null, "stream"];
|
|
65
|
-
const nextValues = values(prevValues, prevKind);
|
|
66
|
-
this.setState({ values: nextValues != null ? [nextValues, kind] : null });
|
|
67
|
-
} else {
|
|
68
|
-
const nextValues = values != null ? [values, kind] : null;
|
|
69
|
-
this.setState({ values: nextValues });
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
getMutateFn = (kind, historyValues) => {
|
|
73
|
-
return (update) => {
|
|
74
|
-
const prev = {
|
|
75
|
-
...historyValues,
|
|
76
|
-
...(this.state.values ?? [null, "stream"])[0]
|
|
77
|
-
};
|
|
78
|
-
const next = typeof update === "function" ? update(prev) : update;
|
|
79
|
-
this.setStreamValues({
|
|
80
|
-
...prev,
|
|
81
|
-
...next
|
|
82
|
-
}, kind);
|
|
83
|
-
};
|
|
84
|
-
};
|
|
85
|
-
matchEventType = (expected, actual, _data) => {
|
|
86
|
-
return expected === actual || actual.startsWith(`${expected}|`);
|
|
87
|
-
};
|
|
88
|
-
enqueue = async (action, options) => {
|
|
89
|
-
try {
|
|
90
|
-
this.queueSize = Math.max(0, this.queueSize - 1);
|
|
91
|
-
this.setState({
|
|
92
|
-
isLoading: true,
|
|
93
|
-
error: void 0
|
|
94
|
-
});
|
|
95
|
-
this.abortRef = new AbortController();
|
|
96
|
-
const run = await action(this.abortRef.signal);
|
|
97
|
-
let streamError;
|
|
98
|
-
for await (const { event, data } of run) {
|
|
99
|
-
if (event === "error") {
|
|
100
|
-
streamError = new require_errors.StreamError(data);
|
|
101
|
-
break;
|
|
102
|
-
}
|
|
103
|
-
const namespace = event.includes("|") ? event.split("|").slice(1) : void 0;
|
|
104
|
-
const mutate = this.getMutateFn("stream", options.initialValues);
|
|
105
|
-
if (event === "metadata") options.callbacks.onMetadataEvent?.(data);
|
|
106
|
-
if (event === "events") options.callbacks.onLangChainEvent?.(data);
|
|
107
|
-
if (this.matchEventType("updates", event, data)) options.callbacks.onUpdateEvent?.(data, {
|
|
108
|
-
namespace,
|
|
109
|
-
mutate
|
|
110
|
-
});
|
|
111
|
-
if (this.matchEventType("custom", event, data)) options.callbacks.onCustomEvent?.(data, {
|
|
112
|
-
namespace,
|
|
113
|
-
mutate
|
|
114
|
-
});
|
|
115
|
-
if (this.matchEventType("checkpoints", event, data)) options.callbacks.onCheckpointEvent?.(data, { namespace });
|
|
116
|
-
if (this.matchEventType("tasks", event, data)) options.callbacks.onTaskEvent?.(data, { namespace });
|
|
117
|
-
if (this.matchEventType("debug", event, data)) options.callbacks.onDebugEvent?.(data, { namespace });
|
|
118
|
-
if (event === "values") if ("__interrupt__" in data) this.setStreamValues((prev) => ({
|
|
119
|
-
...prev,
|
|
120
|
-
...data
|
|
121
|
-
}));
|
|
122
|
-
else this.setStreamValues(data);
|
|
123
|
-
if (this.matchEventType("messages", event, data)) {
|
|
124
|
-
const [serialized, metadata] = data;
|
|
125
|
-
const messageId = this.messages.add(serialized, metadata);
|
|
126
|
-
if (!messageId) {
|
|
127
|
-
console.warn("Failed to add message to manager, no message ID found");
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
this.setStreamValues((streamValues) => {
|
|
131
|
-
const values$1 = {
|
|
132
|
-
...options.initialValues,
|
|
133
|
-
...streamValues
|
|
134
|
-
};
|
|
135
|
-
const messages = options.getMessages(values$1).slice();
|
|
136
|
-
const { chunk, index } = this.messages.get(messageId, messages.length) ?? {};
|
|
137
|
-
if (!chunk || index == null) return values$1;
|
|
138
|
-
if (chunk.getType() === "remove") messages.splice(index, 1);
|
|
139
|
-
else messages[index] = require_messages.toMessageDict(chunk);
|
|
140
|
-
return options.setMessages(values$1, messages);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (streamError != null) throw streamError;
|
|
145
|
-
const values = await options.onSuccess?.();
|
|
146
|
-
if (typeof values !== "undefined" && this.queueSize === 0) this.setStreamValues(values);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
if (!(error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError"))) {
|
|
149
|
-
console.error(error);
|
|
150
|
-
this.setState({ error });
|
|
151
|
-
await options.onError?.(error);
|
|
152
|
-
}
|
|
153
|
-
} finally {
|
|
154
|
-
this.setState({ isLoading: false });
|
|
155
|
-
this.abortRef = new AbortController();
|
|
156
|
-
options.onFinish?.();
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
start = async (action, options) => {
|
|
160
|
-
this.queueSize += 1;
|
|
161
|
-
this.queue = this.queue.then(() => this.enqueue(action, options));
|
|
162
|
-
};
|
|
163
|
-
stop = async (historyValues, options) => {
|
|
164
|
-
this.abortRef.abort();
|
|
165
|
-
this.abortRef = new AbortController();
|
|
166
|
-
options.onStop?.({ mutate: this.getMutateFn("stop", historyValues) });
|
|
167
|
-
};
|
|
168
|
-
clear = () => {
|
|
169
|
-
this.abortRef.abort();
|
|
170
|
-
this.abortRef = new AbortController();
|
|
171
|
-
this.setState({
|
|
172
|
-
error: void 0,
|
|
173
|
-
values: null,
|
|
174
|
-
isLoading: false
|
|
175
|
-
});
|
|
176
|
-
this.messages.clear();
|
|
177
|
-
};
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
//#endregion
|
|
181
|
-
exports.StreamManager = StreamManager;
|
|
182
|
-
//# sourceMappingURL=manager.cjs.map
|
package/dist/ui/manager.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"manager.cjs","names":["timeoutId: NodeJS.Timeout | number | undefined","streamError: StreamError | undefined","StreamError","values","toMessageDict"],"sources":["../../src/ui/manager.ts"],"sourcesContent":["import type {\n CheckpointsStreamEvent,\n CustomStreamEvent,\n DebugStreamEvent,\n ErrorStreamEvent,\n EventsStreamEvent,\n FeedbackStreamEvent,\n MessagesTupleStreamEvent,\n MetadataStreamEvent,\n TasksStreamEvent,\n UpdatesStreamEvent,\n ValuesStreamEvent,\n} from \"../types.stream.js\";\nimport { MessageTupleManager, toMessageDict } from \"./messages.js\";\nimport { StreamError } from \"./errors.js\";\nimport type { Message } from \"../types.messages.js\";\n\ntype BagTemplate = {\n ConfigurableType?: Record<string, unknown>;\n InterruptType?: unknown;\n CustomEventType?: unknown;\n UpdateType?: unknown;\n};\n\ntype GetUpdateType<\n Bag extends BagTemplate,\n StateType extends Record<string, unknown>\n> = Bag extends { UpdateType: unknown }\n ? Bag[\"UpdateType\"]\n : Partial<StateType>;\n\ntype GetCustomEventType<Bag extends BagTemplate> = Bag extends {\n CustomEventType: unknown;\n}\n ? Bag[\"CustomEventType\"]\n : unknown;\n\ntype EventStreamMap<StateType, UpdateType, CustomType> = {\n values: ValuesStreamEvent<StateType>;\n updates: UpdatesStreamEvent<UpdateType>;\n custom: CustomStreamEvent<CustomType>;\n debug: DebugStreamEvent;\n messages: MessagesTupleStreamEvent;\n events: EventsStreamEvent;\n metadata: MetadataStreamEvent;\n checkpoints: CheckpointsStreamEvent<StateType>;\n tasks: TasksStreamEvent<StateType, UpdateType>;\n error: ErrorStreamEvent;\n feedback: FeedbackStreamEvent;\n};\n\nexport type EventStreamEvent<StateType, UpdateType, CustomType> =\n EventStreamMap<StateType, UpdateType, CustomType>[keyof EventStreamMap<\n StateType,\n UpdateType,\n CustomType\n >];\n\ninterface StreamManagerEventCallbacks<\n StateType extends Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate\n> {\n onUpdateEvent?: (\n data: UpdatesStreamEvent<GetUpdateType<Bag, StateType>>[\"data\"],\n options: {\n namespace: string[] | undefined;\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }\n ) => void;\n onCustomEvent?: (\n data: GetCustomEventType<Bag>,\n options: {\n namespace: string[] | undefined;\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }\n ) => void;\n onMetadataEvent?: (data: MetadataStreamEvent[\"data\"]) => void;\n onLangChainEvent?: (data: EventsStreamEvent[\"data\"]) => void;\n onDebugEvent?: (\n data: DebugStreamEvent[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n onCheckpointEvent?: (\n data: CheckpointsStreamEvent<StateType>[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n onTaskEvent?: (\n data: TasksStreamEvent<StateType, GetUpdateType<Bag, StateType>>[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n}\n\nexport class StreamManager<\n StateType extends Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate\n> {\n private abortRef = new AbortController();\n\n private messages: MessageTupleManager;\n\n private listeners = new Set<() => void>();\n\n private throttle: number | boolean;\n\n private queue: Promise<unknown> = Promise.resolve();\n\n private queueSize: number = 0;\n\n private state: {\n isLoading: boolean;\n values: [values: StateType, kind: \"stream\" | \"stop\"] | null;\n error: unknown;\n };\n\n constructor(\n messages: MessageTupleManager,\n options: { throttle: number | boolean }\n ) {\n this.messages = messages;\n this.state = { isLoading: false, values: null, error: undefined };\n this.throttle = options.throttle;\n }\n\n private setState = (newState: Partial<typeof this.state>) => {\n this.state = { ...this.state, ...newState };\n this.notifyListeners();\n };\n\n private notifyListeners = () => {\n this.listeners.forEach((listener) => listener());\n };\n\n subscribe = (listener: () => void): (() => void) => {\n if (this.throttle === false) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n const timeoutMs = this.throttle === true ? 0 : this.throttle;\n let timeoutId: NodeJS.Timeout | number | undefined;\n\n const throttledListener = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n clearTimeout(timeoutId);\n listener();\n }, timeoutMs);\n };\n\n this.listeners.add(throttledListener);\n return () => {\n clearTimeout(timeoutId);\n this.listeners.delete(throttledListener);\n };\n };\n\n getSnapshot = () => this.state;\n\n get isLoading() {\n return this.state.isLoading;\n }\n\n get values() {\n return this.state.values?.[0] ?? null;\n }\n\n get error() {\n return this.state.error;\n }\n\n setStreamValues = (\n values:\n | (StateType | null)\n | ((prev: StateType | null, kind: \"stream\" | \"stop\") => StateType | null),\n kind: \"stream\" | \"stop\" = \"stream\"\n ) => {\n if (typeof values === \"function\") {\n const [prevValues, prevKind] = this.state.values ?? [null, \"stream\"];\n const nextValues = values(prevValues, prevKind);\n this.setState({ values: nextValues != null ? [nextValues, kind] : null });\n } else {\n const nextValues = values != null ? [values, kind] : null;\n this.setState({ values: nextValues as [StateType, \"stream\" | \"stop\"] });\n }\n };\n\n private getMutateFn = (kind: \"stream\" | \"stop\", historyValues: StateType) => {\n return (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => {\n const prev = {\n ...historyValues,\n ...(this.state.values ?? [null, \"stream\"])[0],\n };\n const next = typeof update === \"function\" ? update(prev) : update;\n this.setStreamValues({ ...prev, ...next }, kind);\n };\n };\n\n private matchEventType = <\n T extends keyof EventStreamMap<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >(\n expected: T,\n actual: EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[\"event\"],\n _data: EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[\"data\"]\n ): _data is EventStreamMap<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[T][\"data\"] => {\n return expected === actual || actual.startsWith(`${expected}|`);\n };\n\n protected enqueue = async (\n action: (\n signal: AbortSignal\n ) => Promise<\n AsyncGenerator<\n EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >\n >,\n options: {\n getMessages: (values: StateType) => Message[];\n\n setMessages: (current: StateType, messages: Message[]) => StateType;\n\n initialValues: StateType;\n\n callbacks: StreamManagerEventCallbacks<StateType, Bag>;\n\n onSuccess: () =>\n | StateType\n | null\n | undefined\n | void\n | Promise<StateType | null | undefined | void>;\n\n onError: (error: unknown) => void | Promise<void>;\n\n onFinish?: () => void;\n }\n ) => {\n try {\n this.queueSize = Math.max(0, this.queueSize - 1);\n this.setState({ isLoading: true, error: undefined });\n this.abortRef = new AbortController();\n\n const run = await action(this.abortRef.signal);\n\n let streamError: StreamError | undefined;\n for await (const { event, data } of run) {\n if (event === \"error\") {\n streamError = new StreamError(data);\n break;\n }\n\n const namespace = event.includes(\"|\")\n ? event.split(\"|\").slice(1)\n : undefined;\n\n const mutate = this.getMutateFn(\"stream\", options.initialValues);\n\n if (event === \"metadata\") options.callbacks.onMetadataEvent?.(data);\n if (event === \"events\") options.callbacks.onLangChainEvent?.(data);\n\n if (this.matchEventType(\"updates\", event, data)) {\n options.callbacks.onUpdateEvent?.(data, { namespace, mutate });\n }\n\n if (this.matchEventType(\"custom\", event, data)) {\n options.callbacks.onCustomEvent?.(data, { namespace, mutate });\n }\n\n if (this.matchEventType(\"checkpoints\", event, data)) {\n options.callbacks.onCheckpointEvent?.(data, { namespace });\n }\n\n if (this.matchEventType(\"tasks\", event, data)) {\n options.callbacks.onTaskEvent?.(data, { namespace });\n }\n\n if (this.matchEventType(\"debug\", event, data)) {\n options.callbacks.onDebugEvent?.(data, { namespace });\n }\n\n if (event === \"values\") {\n if (\"__interrupt__\" in data) {\n this.setStreamValues((prev) => ({ ...prev, ...data }));\n } else {\n this.setStreamValues(data);\n }\n }\n\n if (this.matchEventType(\"messages\", event, data)) {\n const [serialized, metadata] = data;\n\n const messageId = this.messages.add(serialized, metadata);\n if (!messageId) {\n console.warn(\n \"Failed to add message to manager, no message ID found\"\n );\n continue;\n }\n\n this.setStreamValues((streamValues) => {\n const values = { ...options.initialValues, ...streamValues };\n\n // Assumption: we're concatenating the message\n const messages = options.getMessages(values).slice();\n const { chunk, index } =\n this.messages.get(messageId, messages.length) ?? {};\n\n if (!chunk || index == null) return values;\n if (chunk.getType() === \"remove\") {\n messages.splice(index, 1);\n } else {\n messages[index] = toMessageDict(chunk);\n }\n\n return options.setMessages(values, messages);\n });\n }\n }\n\n if (streamError != null) throw streamError;\n\n const values = await options.onSuccess?.();\n if (typeof values !== \"undefined\" && this.queueSize === 0) {\n this.setStreamValues(values);\n }\n } catch (error) {\n if (\n !(\n error instanceof Error && // eslint-disable-line no-instanceof/no-instanceof\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n )\n ) {\n console.error(error);\n this.setState({ error });\n await options.onError?.(error);\n }\n } finally {\n this.setState({ isLoading: false });\n this.abortRef = new AbortController();\n options.onFinish?.();\n }\n };\n\n start = async (\n action: (\n signal: AbortSignal\n ) => Promise<\n AsyncGenerator<\n EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >\n >,\n options: {\n getMessages: (values: StateType) => Message[];\n\n setMessages: (current: StateType, messages: Message[]) => StateType;\n\n initialValues: StateType;\n\n callbacks: StreamManagerEventCallbacks<StateType, Bag>;\n\n onSuccess: () =>\n | StateType\n | null\n | undefined\n | void\n | Promise<StateType | null | undefined | void>;\n\n onError: (error: unknown) => void | Promise<void>;\n\n onFinish?: () => void;\n }\n ): Promise<void> => {\n this.queueSize += 1;\n this.queue = this.queue.then(() => this.enqueue(action, options));\n };\n\n stop = async (\n historyValues: StateType,\n options: {\n onStop?: (options: {\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }) => void;\n }\n ): Promise<void> => {\n this.abortRef.abort();\n this.abortRef = new AbortController();\n\n options.onStop?.({ mutate: this.getMutateFn(\"stop\", historyValues) });\n };\n\n clear = () => {\n // Cancel any running streams\n this.abortRef.abort();\n this.abortRef = new AbortController();\n\n // Set the stream state to null\n this.setState({ error: undefined, values: null, isLoading: false });\n\n // Clear any pending messages\n this.messages.clear();\n };\n}\n"],"mappings":";;;;AAgGA,IAAa,gBAAb,MAGE;CACA,AAAQ,WAAW,IAAI;CAEvB,AAAQ;CAER,AAAQ,4BAAY,IAAI;CAExB,AAAQ;CAER,AAAQ,QAA0B,QAAQ;CAE1C,AAAQ,YAAoB;CAE5B,AAAQ;CAMR,YACE,UACA,SACA;AACA,OAAK,WAAW;AAChB,OAAK,QAAQ;GAAE,WAAW;GAAO,QAAQ;GAAM,OAAO;;AACtD,OAAK,WAAW,QAAQ;;CAG1B,AAAQ,YAAY,aAAyC;AAC3D,OAAK,QAAQ;GAAE,GAAG,KAAK;GAAO,GAAG;;AACjC,OAAK;;CAGP,AAAQ,wBAAwB;AAC9B,OAAK,UAAU,SAAS,aAAa;;CAGvC,aAAa,aAAuC;AAClD,MAAI,KAAK,aAAa,OAAO;AAC3B,QAAK,UAAU,IAAI;AACnB,gBAAa,KAAK,UAAU,OAAO;;EAGrC,MAAM,YAAY,KAAK,aAAa,OAAO,IAAI,KAAK;EACpD,IAAIA;EAEJ,MAAM,0BAA0B;AAC9B,gBAAa;AACb,eAAY,iBAAiB;AAC3B,iBAAa;AACb;MACC;;AAGL,OAAK,UAAU,IAAI;AACnB,eAAa;AACX,gBAAa;AACb,QAAK,UAAU,OAAO;;;CAI1B,oBAAoB,KAAK;CAEzB,IAAI,YAAY;AACd,SAAO,KAAK,MAAM;;CAGpB,IAAI,SAAS;AACX,SAAO,KAAK,MAAM,SAA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K,SAAS,EAAE;AAChB,UAAM,QAAQ,UAAU;;YAElB;AACR,QAAK,SAAS,EAAE,WAAW;AAC3B,QAAK,WAAW,IAAI;AACpB,WAAQ;;;CAIZ,QAAQ,OACN,QAWA,YAoBkB;AAClB,OAAK,aAAa;AAClB,OAAK,QAAQ,KAAK,MAAM,WAAW,KAAK,QAAQ,QAAQ;;CAG1D,OAAO,OACL,eACA,YAOkB;AAClB,OAAK,SAAS;AACd,OAAK,WAAW,IAAI;AAEpB,UAAQ,SAAS,EAAE,QAAQ,KAAK,YAAY,QAAQ;;CAGtD,cAAc;AAEZ,OAAK,SAAS;AACd,OAAK,WAAW,IAAI;AAGpB,OAAK,SAAS;GAAE,OAAO;GAAW,QAAQ;GAAM,WAAW;;AAG3D,OAAK,SAAS"}
|
package/dist/ui/manager.js
DELETED
|
@@ -1,182 +0,0 @@
|
|
|
1
|
-
import { StreamError } from "./errors.js";
|
|
2
|
-
import { toMessageDict } from "./messages.js";
|
|
3
|
-
|
|
4
|
-
//#region src/ui/manager.ts
|
|
5
|
-
var StreamManager = class {
|
|
6
|
-
abortRef = new AbortController();
|
|
7
|
-
messages;
|
|
8
|
-
listeners = /* @__PURE__ */ new Set();
|
|
9
|
-
throttle;
|
|
10
|
-
queue = Promise.resolve();
|
|
11
|
-
queueSize = 0;
|
|
12
|
-
state;
|
|
13
|
-
constructor(messages, options) {
|
|
14
|
-
this.messages = messages;
|
|
15
|
-
this.state = {
|
|
16
|
-
isLoading: false,
|
|
17
|
-
values: null,
|
|
18
|
-
error: void 0
|
|
19
|
-
};
|
|
20
|
-
this.throttle = options.throttle;
|
|
21
|
-
}
|
|
22
|
-
setState = (newState) => {
|
|
23
|
-
this.state = {
|
|
24
|
-
...this.state,
|
|
25
|
-
...newState
|
|
26
|
-
};
|
|
27
|
-
this.notifyListeners();
|
|
28
|
-
};
|
|
29
|
-
notifyListeners = () => {
|
|
30
|
-
this.listeners.forEach((listener) => listener());
|
|
31
|
-
};
|
|
32
|
-
subscribe = (listener) => {
|
|
33
|
-
if (this.throttle === false) {
|
|
34
|
-
this.listeners.add(listener);
|
|
35
|
-
return () => this.listeners.delete(listener);
|
|
36
|
-
}
|
|
37
|
-
const timeoutMs = this.throttle === true ? 0 : this.throttle;
|
|
38
|
-
let timeoutId;
|
|
39
|
-
const throttledListener = () => {
|
|
40
|
-
clearTimeout(timeoutId);
|
|
41
|
-
timeoutId = setTimeout(() => {
|
|
42
|
-
clearTimeout(timeoutId);
|
|
43
|
-
listener();
|
|
44
|
-
}, timeoutMs);
|
|
45
|
-
};
|
|
46
|
-
this.listeners.add(throttledListener);
|
|
47
|
-
return () => {
|
|
48
|
-
clearTimeout(timeoutId);
|
|
49
|
-
this.listeners.delete(throttledListener);
|
|
50
|
-
};
|
|
51
|
-
};
|
|
52
|
-
getSnapshot = () => this.state;
|
|
53
|
-
get isLoading() {
|
|
54
|
-
return this.state.isLoading;
|
|
55
|
-
}
|
|
56
|
-
get values() {
|
|
57
|
-
return this.state.values?.[0] ?? null;
|
|
58
|
-
}
|
|
59
|
-
get error() {
|
|
60
|
-
return this.state.error;
|
|
61
|
-
}
|
|
62
|
-
setStreamValues = (values, kind = "stream") => {
|
|
63
|
-
if (typeof values === "function") {
|
|
64
|
-
const [prevValues, prevKind] = this.state.values ?? [null, "stream"];
|
|
65
|
-
const nextValues = values(prevValues, prevKind);
|
|
66
|
-
this.setState({ values: nextValues != null ? [nextValues, kind] : null });
|
|
67
|
-
} else {
|
|
68
|
-
const nextValues = values != null ? [values, kind] : null;
|
|
69
|
-
this.setState({ values: nextValues });
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
getMutateFn = (kind, historyValues) => {
|
|
73
|
-
return (update) => {
|
|
74
|
-
const prev = {
|
|
75
|
-
...historyValues,
|
|
76
|
-
...(this.state.values ?? [null, "stream"])[0]
|
|
77
|
-
};
|
|
78
|
-
const next = typeof update === "function" ? update(prev) : update;
|
|
79
|
-
this.setStreamValues({
|
|
80
|
-
...prev,
|
|
81
|
-
...next
|
|
82
|
-
}, kind);
|
|
83
|
-
};
|
|
84
|
-
};
|
|
85
|
-
matchEventType = (expected, actual, _data) => {
|
|
86
|
-
return expected === actual || actual.startsWith(`${expected}|`);
|
|
87
|
-
};
|
|
88
|
-
enqueue = async (action, options) => {
|
|
89
|
-
try {
|
|
90
|
-
this.queueSize = Math.max(0, this.queueSize - 1);
|
|
91
|
-
this.setState({
|
|
92
|
-
isLoading: true,
|
|
93
|
-
error: void 0
|
|
94
|
-
});
|
|
95
|
-
this.abortRef = new AbortController();
|
|
96
|
-
const run = await action(this.abortRef.signal);
|
|
97
|
-
let streamError;
|
|
98
|
-
for await (const { event, data } of run) {
|
|
99
|
-
if (event === "error") {
|
|
100
|
-
streamError = new StreamError(data);
|
|
101
|
-
break;
|
|
102
|
-
}
|
|
103
|
-
const namespace = event.includes("|") ? event.split("|").slice(1) : void 0;
|
|
104
|
-
const mutate = this.getMutateFn("stream", options.initialValues);
|
|
105
|
-
if (event === "metadata") options.callbacks.onMetadataEvent?.(data);
|
|
106
|
-
if (event === "events") options.callbacks.onLangChainEvent?.(data);
|
|
107
|
-
if (this.matchEventType("updates", event, data)) options.callbacks.onUpdateEvent?.(data, {
|
|
108
|
-
namespace,
|
|
109
|
-
mutate
|
|
110
|
-
});
|
|
111
|
-
if (this.matchEventType("custom", event, data)) options.callbacks.onCustomEvent?.(data, {
|
|
112
|
-
namespace,
|
|
113
|
-
mutate
|
|
114
|
-
});
|
|
115
|
-
if (this.matchEventType("checkpoints", event, data)) options.callbacks.onCheckpointEvent?.(data, { namespace });
|
|
116
|
-
if (this.matchEventType("tasks", event, data)) options.callbacks.onTaskEvent?.(data, { namespace });
|
|
117
|
-
if (this.matchEventType("debug", event, data)) options.callbacks.onDebugEvent?.(data, { namespace });
|
|
118
|
-
if (event === "values") if ("__interrupt__" in data) this.setStreamValues((prev) => ({
|
|
119
|
-
...prev,
|
|
120
|
-
...data
|
|
121
|
-
}));
|
|
122
|
-
else this.setStreamValues(data);
|
|
123
|
-
if (this.matchEventType("messages", event, data)) {
|
|
124
|
-
const [serialized, metadata] = data;
|
|
125
|
-
const messageId = this.messages.add(serialized, metadata);
|
|
126
|
-
if (!messageId) {
|
|
127
|
-
console.warn("Failed to add message to manager, no message ID found");
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
this.setStreamValues((streamValues) => {
|
|
131
|
-
const values$1 = {
|
|
132
|
-
...options.initialValues,
|
|
133
|
-
...streamValues
|
|
134
|
-
};
|
|
135
|
-
const messages = options.getMessages(values$1).slice();
|
|
136
|
-
const { chunk, index } = this.messages.get(messageId, messages.length) ?? {};
|
|
137
|
-
if (!chunk || index == null) return values$1;
|
|
138
|
-
if (chunk.getType() === "remove") messages.splice(index, 1);
|
|
139
|
-
else messages[index] = toMessageDict(chunk);
|
|
140
|
-
return options.setMessages(values$1, messages);
|
|
141
|
-
});
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
if (streamError != null) throw streamError;
|
|
145
|
-
const values = await options.onSuccess?.();
|
|
146
|
-
if (typeof values !== "undefined" && this.queueSize === 0) this.setStreamValues(values);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
if (!(error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError"))) {
|
|
149
|
-
console.error(error);
|
|
150
|
-
this.setState({ error });
|
|
151
|
-
await options.onError?.(error);
|
|
152
|
-
}
|
|
153
|
-
} finally {
|
|
154
|
-
this.setState({ isLoading: false });
|
|
155
|
-
this.abortRef = new AbortController();
|
|
156
|
-
options.onFinish?.();
|
|
157
|
-
}
|
|
158
|
-
};
|
|
159
|
-
start = async (action, options) => {
|
|
160
|
-
this.queueSize += 1;
|
|
161
|
-
this.queue = this.queue.then(() => this.enqueue(action, options));
|
|
162
|
-
};
|
|
163
|
-
stop = async (historyValues, options) => {
|
|
164
|
-
this.abortRef.abort();
|
|
165
|
-
this.abortRef = new AbortController();
|
|
166
|
-
options.onStop?.({ mutate: this.getMutateFn("stop", historyValues) });
|
|
167
|
-
};
|
|
168
|
-
clear = () => {
|
|
169
|
-
this.abortRef.abort();
|
|
170
|
-
this.abortRef = new AbortController();
|
|
171
|
-
this.setState({
|
|
172
|
-
error: void 0,
|
|
173
|
-
values: null,
|
|
174
|
-
isLoading: false
|
|
175
|
-
});
|
|
176
|
-
this.messages.clear();
|
|
177
|
-
};
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
//#endregion
|
|
181
|
-
export { StreamManager };
|
|
182
|
-
//# sourceMappingURL=manager.js.map
|
package/dist/ui/manager.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":["timeoutId: NodeJS.Timeout | number | undefined","streamError: StreamError | undefined","values"],"sources":["../../src/ui/manager.ts"],"sourcesContent":["import type {\n CheckpointsStreamEvent,\n CustomStreamEvent,\n DebugStreamEvent,\n ErrorStreamEvent,\n EventsStreamEvent,\n FeedbackStreamEvent,\n MessagesTupleStreamEvent,\n MetadataStreamEvent,\n TasksStreamEvent,\n UpdatesStreamEvent,\n ValuesStreamEvent,\n} from \"../types.stream.js\";\nimport { MessageTupleManager, toMessageDict } from \"./messages.js\";\nimport { StreamError } from \"./errors.js\";\nimport type { Message } from \"../types.messages.js\";\n\ntype BagTemplate = {\n ConfigurableType?: Record<string, unknown>;\n InterruptType?: unknown;\n CustomEventType?: unknown;\n UpdateType?: unknown;\n};\n\ntype GetUpdateType<\n Bag extends BagTemplate,\n StateType extends Record<string, unknown>\n> = Bag extends { UpdateType: unknown }\n ? Bag[\"UpdateType\"]\n : Partial<StateType>;\n\ntype GetCustomEventType<Bag extends BagTemplate> = Bag extends {\n CustomEventType: unknown;\n}\n ? Bag[\"CustomEventType\"]\n : unknown;\n\ntype EventStreamMap<StateType, UpdateType, CustomType> = {\n values: ValuesStreamEvent<StateType>;\n updates: UpdatesStreamEvent<UpdateType>;\n custom: CustomStreamEvent<CustomType>;\n debug: DebugStreamEvent;\n messages: MessagesTupleStreamEvent;\n events: EventsStreamEvent;\n metadata: MetadataStreamEvent;\n checkpoints: CheckpointsStreamEvent<StateType>;\n tasks: TasksStreamEvent<StateType, UpdateType>;\n error: ErrorStreamEvent;\n feedback: FeedbackStreamEvent;\n};\n\nexport type EventStreamEvent<StateType, UpdateType, CustomType> =\n EventStreamMap<StateType, UpdateType, CustomType>[keyof EventStreamMap<\n StateType,\n UpdateType,\n CustomType\n >];\n\ninterface StreamManagerEventCallbacks<\n StateType extends Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate\n> {\n onUpdateEvent?: (\n data: UpdatesStreamEvent<GetUpdateType<Bag, StateType>>[\"data\"],\n options: {\n namespace: string[] | undefined;\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }\n ) => void;\n onCustomEvent?: (\n data: GetCustomEventType<Bag>,\n options: {\n namespace: string[] | undefined;\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }\n ) => void;\n onMetadataEvent?: (data: MetadataStreamEvent[\"data\"]) => void;\n onLangChainEvent?: (data: EventsStreamEvent[\"data\"]) => void;\n onDebugEvent?: (\n data: DebugStreamEvent[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n onCheckpointEvent?: (\n data: CheckpointsStreamEvent<StateType>[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n onTaskEvent?: (\n data: TasksStreamEvent<StateType, GetUpdateType<Bag, StateType>>[\"data\"],\n options: { namespace: string[] | undefined }\n ) => void;\n}\n\nexport class StreamManager<\n StateType extends Record<string, unknown>,\n Bag extends BagTemplate = BagTemplate\n> {\n private abortRef = new AbortController();\n\n private messages: MessageTupleManager;\n\n private listeners = new Set<() => void>();\n\n private throttle: number | boolean;\n\n private queue: Promise<unknown> = Promise.resolve();\n\n private queueSize: number = 0;\n\n private state: {\n isLoading: boolean;\n values: [values: StateType, kind: \"stream\" | \"stop\"] | null;\n error: unknown;\n };\n\n constructor(\n messages: MessageTupleManager,\n options: { throttle: number | boolean }\n ) {\n this.messages = messages;\n this.state = { isLoading: false, values: null, error: undefined };\n this.throttle = options.throttle;\n }\n\n private setState = (newState: Partial<typeof this.state>) => {\n this.state = { ...this.state, ...newState };\n this.notifyListeners();\n };\n\n private notifyListeners = () => {\n this.listeners.forEach((listener) => listener());\n };\n\n subscribe = (listener: () => void): (() => void) => {\n if (this.throttle === false) {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n const timeoutMs = this.throttle === true ? 0 : this.throttle;\n let timeoutId: NodeJS.Timeout | number | undefined;\n\n const throttledListener = () => {\n clearTimeout(timeoutId);\n timeoutId = setTimeout(() => {\n clearTimeout(timeoutId);\n listener();\n }, timeoutMs);\n };\n\n this.listeners.add(throttledListener);\n return () => {\n clearTimeout(timeoutId);\n this.listeners.delete(throttledListener);\n };\n };\n\n getSnapshot = () => this.state;\n\n get isLoading() {\n return this.state.isLoading;\n }\n\n get values() {\n return this.state.values?.[0] ?? null;\n }\n\n get error() {\n return this.state.error;\n }\n\n setStreamValues = (\n values:\n | (StateType | null)\n | ((prev: StateType | null, kind: \"stream\" | \"stop\") => StateType | null),\n kind: \"stream\" | \"stop\" = \"stream\"\n ) => {\n if (typeof values === \"function\") {\n const [prevValues, prevKind] = this.state.values ?? [null, \"stream\"];\n const nextValues = values(prevValues, prevKind);\n this.setState({ values: nextValues != null ? [nextValues, kind] : null });\n } else {\n const nextValues = values != null ? [values, kind] : null;\n this.setState({ values: nextValues as [StateType, \"stream\" | \"stop\"] });\n }\n };\n\n private getMutateFn = (kind: \"stream\" | \"stop\", historyValues: StateType) => {\n return (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => {\n const prev = {\n ...historyValues,\n ...(this.state.values ?? [null, \"stream\"])[0],\n };\n const next = typeof update === \"function\" ? update(prev) : update;\n this.setStreamValues({ ...prev, ...next }, kind);\n };\n };\n\n private matchEventType = <\n T extends keyof EventStreamMap<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >(\n expected: T,\n actual: EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[\"event\"],\n _data: EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[\"data\"]\n ): _data is EventStreamMap<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >[T][\"data\"] => {\n return expected === actual || actual.startsWith(`${expected}|`);\n };\n\n protected enqueue = async (\n action: (\n signal: AbortSignal\n ) => Promise<\n AsyncGenerator<\n EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >\n >,\n options: {\n getMessages: (values: StateType) => Message[];\n\n setMessages: (current: StateType, messages: Message[]) => StateType;\n\n initialValues: StateType;\n\n callbacks: StreamManagerEventCallbacks<StateType, Bag>;\n\n onSuccess: () =>\n | StateType\n | null\n | undefined\n | void\n | Promise<StateType | null | undefined | void>;\n\n onError: (error: unknown) => void | Promise<void>;\n\n onFinish?: () => void;\n }\n ) => {\n try {\n this.queueSize = Math.max(0, this.queueSize - 1);\n this.setState({ isLoading: true, error: undefined });\n this.abortRef = new AbortController();\n\n const run = await action(this.abortRef.signal);\n\n let streamError: StreamError | undefined;\n for await (const { event, data } of run) {\n if (event === \"error\") {\n streamError = new StreamError(data);\n break;\n }\n\n const namespace = event.includes(\"|\")\n ? event.split(\"|\").slice(1)\n : undefined;\n\n const mutate = this.getMutateFn(\"stream\", options.initialValues);\n\n if (event === \"metadata\") options.callbacks.onMetadataEvent?.(data);\n if (event === \"events\") options.callbacks.onLangChainEvent?.(data);\n\n if (this.matchEventType(\"updates\", event, data)) {\n options.callbacks.onUpdateEvent?.(data, { namespace, mutate });\n }\n\n if (this.matchEventType(\"custom\", event, data)) {\n options.callbacks.onCustomEvent?.(data, { namespace, mutate });\n }\n\n if (this.matchEventType(\"checkpoints\", event, data)) {\n options.callbacks.onCheckpointEvent?.(data, { namespace });\n }\n\n if (this.matchEventType(\"tasks\", event, data)) {\n options.callbacks.onTaskEvent?.(data, { namespace });\n }\n\n if (this.matchEventType(\"debug\", event, data)) {\n options.callbacks.onDebugEvent?.(data, { namespace });\n }\n\n if (event === \"values\") {\n if (\"__interrupt__\" in data) {\n this.setStreamValues((prev) => ({ ...prev, ...data }));\n } else {\n this.setStreamValues(data);\n }\n }\n\n if (this.matchEventType(\"messages\", event, data)) {\n const [serialized, metadata] = data;\n\n const messageId = this.messages.add(serialized, metadata);\n if (!messageId) {\n console.warn(\n \"Failed to add message to manager, no message ID found\"\n );\n continue;\n }\n\n this.setStreamValues((streamValues) => {\n const values = { ...options.initialValues, ...streamValues };\n\n // Assumption: we're concatenating the message\n const messages = options.getMessages(values).slice();\n const { chunk, index } =\n this.messages.get(messageId, messages.length) ?? {};\n\n if (!chunk || index == null) return values;\n if (chunk.getType() === \"remove\") {\n messages.splice(index, 1);\n } else {\n messages[index] = toMessageDict(chunk);\n }\n\n return options.setMessages(values, messages);\n });\n }\n }\n\n if (streamError != null) throw streamError;\n\n const values = await options.onSuccess?.();\n if (typeof values !== \"undefined\" && this.queueSize === 0) {\n this.setStreamValues(values);\n }\n } catch (error) {\n if (\n !(\n error instanceof Error && // eslint-disable-line no-instanceof/no-instanceof\n (error.name === \"AbortError\" || error.name === \"TimeoutError\")\n )\n ) {\n console.error(error);\n this.setState({ error });\n await options.onError?.(error);\n }\n } finally {\n this.setState({ isLoading: false });\n this.abortRef = new AbortController();\n options.onFinish?.();\n }\n };\n\n start = async (\n action: (\n signal: AbortSignal\n ) => Promise<\n AsyncGenerator<\n EventStreamEvent<\n StateType,\n GetUpdateType<Bag, StateType>,\n GetCustomEventType<Bag>\n >\n >\n >,\n options: {\n getMessages: (values: StateType) => Message[];\n\n setMessages: (current: StateType, messages: Message[]) => StateType;\n\n initialValues: StateType;\n\n callbacks: StreamManagerEventCallbacks<StateType, Bag>;\n\n onSuccess: () =>\n | StateType\n | null\n | undefined\n | void\n | Promise<StateType | null | undefined | void>;\n\n onError: (error: unknown) => void | Promise<void>;\n\n onFinish?: () => void;\n }\n ): Promise<void> => {\n this.queueSize += 1;\n this.queue = this.queue.then(() => this.enqueue(action, options));\n };\n\n stop = async (\n historyValues: StateType,\n options: {\n onStop?: (options: {\n mutate: (\n update: Partial<StateType> | ((prev: StateType) => Partial<StateType>)\n ) => void;\n }) => void;\n }\n ): Promise<void> => {\n this.abortRef.abort();\n this.abortRef = new AbortController();\n\n options.onStop?.({ mutate: this.getMutateFn(\"stop\", historyValues) });\n };\n\n clear = () => {\n // Cancel any running streams\n this.abortRef.abort();\n this.abortRef = new AbortController();\n\n // Set the stream state to null\n this.setState({ error: undefined, values: null, isLoading: false });\n\n // Clear any pending messages\n this.messages.clear();\n };\n}\n"],"mappings":";;;;AAgGA,IAAa,gBAAb,MAGE;CACA,AAAQ,WAAW,IAAI;CAEvB,AAAQ;CAER,AAAQ,4BAAY,IAAI;CAExB,AAAQ;CAER,AAAQ,QAA0B,QAAQ;CAE1C,AAAQ,YAAoB;CAE5B,AAAQ;CAMR,YACE,UACA,SACA;AACA,OAAK,WAAW;AAChB,OAAK,QAAQ;GAAE,WAAW;GAAO,QAAQ;GAAM,OAAO;;AACtD,OAAK,WAAW,QAAQ;;CAG1B,AAAQ,YAAY,aAAyC;AAC3D,OAAK,QAAQ;GAAE,GAAG,KAAK;GAAO,GAAG;;AACjC,OAAK;;CAGP,AAAQ,wBAAwB;AAC9B,OAAK,UAAU,SAAS,aAAa;;CAGvC,aAAa,aAAuC;AAClD,MAAI,KAAK,aAAa,OAAO;AAC3B,QAAK,UAAU,IAAI;AACnB,gBAAa,KAAK,UAAU,OAAO;;EAGrC,MAAM,YAAY,KAAK,aAAa,OAAO,IAAI,KAAK;EACpD,IAAIA;EAEJ,MAAM,0BAA0B;AAC9B,gBAAa;AACb,eAAY,iBAAiB;AAC3B,iBAAa;AACb;MACC;;AAGL,OAAK,UAAU,IAAI;AACnB,eAAa;AACX,gBAAa;AACb,QAAK,UAA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