@anvia/core 0.26.0 → 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.md +303 -94
  2. package/dist/agent/index.d.ts +36 -70
  3. package/dist/agent/index.js +25 -18
  4. package/dist/agent-yBG8e9Jj.d.ts +153 -0
  5. package/dist/chunk-4WI3VGZK.js +127 -0
  6. package/dist/chunk-4WI3VGZK.js.map +1 -0
  7. package/dist/chunk-77AIYARB.js +654 -0
  8. package/dist/chunk-77AIYARB.js.map +1 -0
  9. package/dist/chunk-AI5JMUW7.js +45 -0
  10. package/dist/chunk-AI5JMUW7.js.map +1 -0
  11. package/dist/chunk-BEYBU7VJ.js +53 -0
  12. package/dist/chunk-BEYBU7VJ.js.map +1 -0
  13. package/dist/chunk-CWM7B2OO.js +315 -0
  14. package/dist/chunk-CWM7B2OO.js.map +1 -0
  15. package/dist/chunk-D37WMSP6.js +131 -0
  16. package/dist/chunk-D37WMSP6.js.map +1 -0
  17. package/dist/chunk-DBSCKTUL.js +3793 -0
  18. package/dist/chunk-DBSCKTUL.js.map +1 -0
  19. package/dist/chunk-EINTGEGY.js +629 -0
  20. package/dist/chunk-EINTGEGY.js.map +1 -0
  21. package/dist/chunk-FMHLROPQ.js +351 -0
  22. package/dist/chunk-FMHLROPQ.js.map +1 -0
  23. package/dist/chunk-FN7HLLAZ.js +211 -0
  24. package/dist/chunk-FN7HLLAZ.js.map +1 -0
  25. package/dist/chunk-GKDERULJ.js +50 -0
  26. package/dist/chunk-GKDERULJ.js.map +1 -0
  27. package/dist/{chunk-CWUJUSOS.js → chunk-KIDGIJM7.js} +26 -5
  28. package/dist/chunk-KIDGIJM7.js.map +1 -0
  29. package/dist/chunk-KR3RCCHJ.js +500 -0
  30. package/dist/chunk-KR3RCCHJ.js.map +1 -0
  31. package/dist/chunk-MGNTXGTX.js +37 -0
  32. package/dist/chunk-MGNTXGTX.js.map +1 -0
  33. package/dist/{chunk-MRQLEK2B.js → chunk-OJH6HWHX.js} +63 -51
  34. package/dist/chunk-OJH6HWHX.js.map +1 -0
  35. package/dist/chunk-QOUPWOGW.js +29 -0
  36. package/dist/chunk-QOUPWOGW.js.map +1 -0
  37. package/dist/chunk-TIZYTPJO.js +208 -0
  38. package/dist/chunk-TIZYTPJO.js.map +1 -0
  39. package/dist/{chunk-NCPN4SJR.js → chunk-XKYYBABH.js} +13 -13
  40. package/dist/chunk-XKYYBABH.js.map +1 -0
  41. package/dist/client-B8DT1vUG.d.ts +83 -0
  42. package/dist/completion/index.d.ts +6 -36
  43. package/dist/completion/index.js +25 -29
  44. package/dist/dynamic-tools-KwEGRbHp.d.ts +45 -0
  45. package/dist/embeddings/index.d.ts +11 -9
  46. package/dist/embeddings/index.js +2 -4
  47. package/dist/evals/index.d.ts +47 -20
  48. package/dist/evals/index.js +104 -65
  49. package/dist/evals/index.js.map +1 -1
  50. package/dist/extractor/index.d.ts +27 -42
  51. package/dist/extractor/index.js +7 -22
  52. package/dist/guardrails/index.d.ts +3 -2
  53. package/dist/guardrails/index.js +1 -1
  54. package/dist/image-generation/index.d.ts +23 -23
  55. package/dist/image-generation/index.js +5 -39
  56. package/dist/image-generation/index.js.map +1 -1
  57. package/dist/index.d.ts +25 -20
  58. package/dist/index.js +60 -63
  59. package/dist/internal/agent.d.ts +163 -9
  60. package/dist/internal/agent.js +25 -18
  61. package/dist/loaders/index.d.ts +6 -10
  62. package/dist/loaders/index.js.map +1 -1
  63. package/dist/mcp/index.d.ts +19 -13
  64. package/dist/mcp/index.js +13 -348
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/memory/index.d.ts +20 -6
  67. package/dist/memory/index.js +9 -10
  68. package/dist/message-schema-Cn7ezRfJ.d.ts +52 -0
  69. package/dist/middleware-C7PdmKF7.d.ts +56 -0
  70. package/dist/model-call-options-CZkSw_xN.d.ts +6 -0
  71. package/dist/model-listing/index.d.ts +3 -1
  72. package/dist/observability/index.d.ts +20 -3
  73. package/dist/observability/index.js +8 -5
  74. package/dist/observability/index.js.map +1 -1
  75. package/dist/pipeline/index.d.ts +114 -72
  76. package/dist/pipeline/index.js +478 -286
  77. package/dist/pipeline/index.js.map +1 -1
  78. package/dist/retry-CjvSlKGW.d.ts +16 -0
  79. package/dist/skills/index.d.ts +5 -4
  80. package/dist/skills/index.js +7 -8
  81. package/dist/speech-generation/index.d.ts +37 -0
  82. package/dist/speech-generation/index.js +8 -0
  83. package/dist/streaming/index.js +37 -3
  84. package/dist/streaming/index.js.map +1 -1
  85. package/dist/{think-tool-DfCMuO8e.d.ts → think-tool-6H2QNQzQ.d.ts} +5 -5
  86. package/dist/tool/index.d.ts +10 -6
  87. package/dist/tool/index.js +15 -21
  88. package/dist/tool--Mz4v1eL.d.ts +57 -0
  89. package/dist/transcription/index.d.ts +29 -22
  90. package/dist/transcription/index.js +5 -57
  91. package/dist/transcription/index.js.map +1 -1
  92. package/dist/type-utils-CtHVDRn_.d.ts +6 -0
  93. package/dist/types-3x3mOLHU.d.ts +379 -0
  94. package/dist/types-BVzM4RsC.d.ts +155 -0
  95. package/dist/types-CQ_ioXWK.d.ts +319 -0
  96. package/dist/types-Cr4uiYo5.d.ts +99 -0
  97. package/dist/{types-04LqWrmy.d.ts → types-DiJqJejp.d.ts} +1 -1
  98. package/dist/types-Dld1TpWj.d.ts +130 -0
  99. package/dist/vector-store/index.d.ts +33 -34
  100. package/dist/vector-store/index.js +6 -6
  101. package/package.json +6 -18
  102. package/dist/agent-x3YTyv5i.d.ts +0 -222
  103. package/dist/audio-generation/index.d.ts +0 -33
  104. package/dist/audio-generation/index.js +0 -42
  105. package/dist/audio-generation/index.js.map +0 -1
  106. package/dist/chunk-2ODTMRHP.js +0 -54
  107. package/dist/chunk-2ODTMRHP.js.map +0 -1
  108. package/dist/chunk-ADH7NNCS.js +0 -512
  109. package/dist/chunk-ADH7NNCS.js.map +0 -1
  110. package/dist/chunk-BALBBVI3.js +0 -2732
  111. package/dist/chunk-BALBBVI3.js.map +0 -1
  112. package/dist/chunk-CWUJUSOS.js.map +0 -1
  113. package/dist/chunk-DALYP4PX.js +0 -225
  114. package/dist/chunk-DALYP4PX.js.map +0 -1
  115. package/dist/chunk-HYUYZEAJ.js +0 -223
  116. package/dist/chunk-HYUYZEAJ.js.map +0 -1
  117. package/dist/chunk-I6XOQ4LK.js +0 -466
  118. package/dist/chunk-I6XOQ4LK.js.map +0 -1
  119. package/dist/chunk-JI5YZWNT.js +0 -220
  120. package/dist/chunk-JI5YZWNT.js.map +0 -1
  121. package/dist/chunk-MC3CCKEB.js +0 -221
  122. package/dist/chunk-MC3CCKEB.js.map +0 -1
  123. package/dist/chunk-MELYDKWQ.js +0 -337
  124. package/dist/chunk-MELYDKWQ.js.map +0 -1
  125. package/dist/chunk-MNWK2USR.js +0 -243
  126. package/dist/chunk-MNWK2USR.js.map +0 -1
  127. package/dist/chunk-MRQLEK2B.js.map +0 -1
  128. package/dist/chunk-NCPN4SJR.js.map +0 -1
  129. package/dist/chunk-OIMLU4SF.js +0 -20
  130. package/dist/chunk-OIMLU4SF.js.map +0 -1
  131. package/dist/chunk-Q25IWLBT.js +0 -138
  132. package/dist/chunk-Q25IWLBT.js.map +0 -1
  133. package/dist/chunk-UQX6EXWG.js +0 -33
  134. package/dist/chunk-UQX6EXWG.js.map +0 -1
  135. package/dist/chunk-WQKHFADH.js +0 -12
  136. package/dist/chunk-WQKHFADH.js.map +0 -1
  137. package/dist/chunk-XUUY2L2D.js +0 -42
  138. package/dist/chunk-XUUY2L2D.js.map +0 -1
  139. package/dist/chunk-XWUC7CIT.js +0 -1
  140. package/dist/chunk-XWUC7CIT.js.map +0 -1
  141. package/dist/chunk-YLMDBQO4.js +0 -141
  142. package/dist/chunk-YLMDBQO4.js.map +0 -1
  143. package/dist/errors-2moLDuuN.d.ts +0 -17
  144. package/dist/hooks/index.d.ts +0 -12
  145. package/dist/hooks/index.js +0 -17
  146. package/dist/index-BxSbmOMr.d.ts +0 -257
  147. package/dist/json-BVPssigK.d.ts +0 -39
  148. package/dist/middleware-Dp3d_pxi.d.ts +0 -90
  149. package/dist/request/index.d.ts +0 -28
  150. package/dist/request/index.js +0 -25
  151. package/dist/request/index.js.map +0 -1
  152. package/dist/tool-Cohdv5GC.d.ts +0 -65
  153. package/dist/types-BCTRUGex.d.ts +0 -47
  154. package/dist/types-BrLbKnEz.d.ts +0 -119
  155. package/dist/types-D9JpeAPF.d.ts +0 -114
  156. package/dist/types-G12i56s2.d.ts +0 -354
  157. package/dist/types-JJCxRnaZ.d.ts +0 -70
  158. package/dist/types-O-abTIin.d.ts +0 -79
  159. package/dist/ui/index.d.ts +0 -107
  160. package/dist/ui/index.js +0 -10
  161. package/dist/ui/index.js.map +0 -1
  162. /package/dist/{hooks → speech-generation}/index.js.map +0 -0
@@ -1,387 +1,579 @@
1
+ import {
2
+ AgentRunBlockedError,
3
+ cancelAgentApproval
4
+ } from "../chunk-DBSCKTUL.js";
5
+ import "../chunk-YK4WAAS4.js";
6
+ import "../chunk-EINTGEGY.js";
7
+ import "../chunk-CQNNSZPG.js";
8
+ import "../chunk-D37WMSP6.js";
9
+ import "../chunk-77AIYARB.js";
10
+ import "../chunk-OJH6HWHX.js";
11
+ import "../chunk-CWM7B2OO.js";
1
12
  import {
2
13
  mapWithConcurrency
3
- } from "../chunk-OIMLU4SF.js";
14
+ } from "../chunk-FMHLROPQ.js";
15
+ import {
16
+ extract
17
+ } from "../chunk-4WI3VGZK.js";
18
+ import "../chunk-MGNTXGTX.js";
19
+ import "../chunk-KR3RCCHJ.js";
20
+ import "../chunk-TIZYTPJO.js";
21
+ import "../chunk-KIDGIJM7.js";
22
+ import {
23
+ abortError,
24
+ throwIfAborted
25
+ } from "../chunk-FN7HLLAZ.js";
26
+
27
+ // src/pipeline/errors.ts
28
+ var PipelineAgentApprovalError = class extends Error {
29
+ constructor(result) {
30
+ super("Pipeline agent stage required tool approval and was rejected.");
31
+ this.result = result;
32
+ this.name = "PipelineAgentApprovalError";
33
+ }
34
+ result;
35
+ };
4
36
 
5
- // src/pipeline/builder.ts
37
+ // src/pipeline/pipeline.ts
6
38
  import { z } from "zod";
7
39
 
8
40
  // src/pipeline/graph.ts
9
- function initialBuilderState(metadata) {
10
- return {
11
- graph: initialGraph(metadata),
12
- terminalNodeId: "input",
13
- terminalNodeIds: ["input"],
14
- nextNodeIndex: 1,
15
- nextEdgeIndex: 1
16
- };
17
- }
18
- function initialGraph(metadata) {
19
- const id = normalizeId(metadata.id ?? "pipeline");
41
+ var INPUT_ID = "$input";
42
+ var OUTPUT_ID = "$output";
43
+ var RESERVED_STAGE_IDS = /* @__PURE__ */ new Set([INPUT_ID, OUTPUT_ID]);
44
+ function initialPipelineState(options) {
45
+ const input = graphNode(INPUT_ID, [INPUT_ID], "input", "Input");
20
46
  const graph = {
21
- id,
22
- nodes: [{ id: "input", kind: "input", label: "Input" }],
47
+ id: options.id,
48
+ nodes: [input],
23
49
  edges: []
24
50
  };
25
- if (metadata.name !== void 0) {
26
- graph.name = metadata.name;
27
- }
28
- if (metadata.description !== void 0) {
29
- graph.description = metadata.description;
30
- }
31
- if (metadata.metadata !== void 0) {
32
- graph.metadata = metadata.metadata;
33
- }
34
- return graph;
35
- }
36
- function appendNode(state, kind, label, options = {}) {
37
- const node = graphNode(kind, label, state.nextNodeIndex, {
38
- ...options,
39
- existingIds: new Set(state.graph.nodes.map((item) => item.id))
40
- });
51
+ if (options.name !== void 0) graph.name = options.name;
52
+ if (options.description !== void 0) graph.description = options.description;
53
+ if (options.metadata !== void 0) graph.metadata = options.metadata;
41
54
  return {
42
- node,
43
- state: appendGraphNode(state, node, activeTerminalNodeIds(state), [node.id])
55
+ graph,
56
+ terminalPaths: [input.path],
57
+ stageIds: /* @__PURE__ */ new Set(),
58
+ nextEdgeIndex: 1
44
59
  };
45
60
  }
46
- function appendChildNode(state, parentId, kind, label, options = {}) {
47
- const node = graphNode(kind, label, state.nextNodeIndex, {
48
- ...options,
49
- existingIds: new Set(state.graph.nodes.map((item) => item.id))
61
+ function appendStageNode(state, kind, stage, options = {}) {
62
+ const id = validateStageId(stage.id);
63
+ if (state.stageIds.has(id)) {
64
+ throw new TypeError(`Pipeline stage id "${id}" is already registered.`);
65
+ }
66
+ const node = graphNode(id, [id], kind, stage.name ?? options.defaultLabel ?? id, {
67
+ description: stage.description,
68
+ metadata: stage.metadata,
69
+ agentId: options.agentId,
70
+ agentName: options.agentName,
71
+ pipelineId: options.pipelineId
50
72
  });
51
73
  return {
52
74
  node,
53
- state: appendGraphNode(state, node, [parentId], activeTerminalNodeIds(state))
75
+ state: appendNode(state, node, state.terminalPaths, [node.path], id)
54
76
  };
55
77
  }
56
- function activeTerminalNodeIds(state) {
57
- return state.terminalNodeIds.length > 0 ? state.terminalNodeIds : [state.terminalNodeId];
78
+ function appendComposedGraph(state, boundary, child) {
79
+ return appendChildGraph(state, boundary.path, child);
58
80
  }
59
- function withTerminalNodes(state, terminalNodeIds) {
60
- return {
61
- ...state,
62
- terminalNodeId: terminalNodeIds.at(-1) ?? state.terminalNodeId,
63
- terminalNodeIds
64
- };
81
+ function appendParallelBranch(state, parallel, branchKey, child) {
82
+ const id = validateStageId(branchKey);
83
+ const path = [...parallel.path, id];
84
+ const node = graphNode(id, path, "branch", id, { branchKey: id, pipelineId: child.id });
85
+ const withBranch = appendNode(state, node, [parallel.path], state.terminalPaths);
86
+ const withChild = appendChildGraph(withBranch, node.path, child);
87
+ return { state: withChild, node, terminalPaths: withChild.terminalPaths };
88
+ }
89
+ function withTerminalPaths(state, terminalPaths) {
90
+ return { ...state, terminalPaths };
65
91
  }
66
92
  function withOutputNode(state) {
67
93
  const graph = cloneGraph(state.graph);
68
- if (graph.nodes.some((node) => node.id === "output")) {
94
+ const outputPath = [OUTPUT_ID];
95
+ if (graph.nodes.some((node) => pathEquals(node.path, outputPath))) {
69
96
  return graph;
70
97
  }
71
- graph.nodes.push({ id: "output", kind: "output", label: "Output" });
98
+ graph.nodes.push(graphNode(OUTPUT_ID, outputPath, "output", "Output"));
72
99
  graph.edges.push(
73
- ...activeTerminalNodeIds(state).map((sourceId, index) => ({
100
+ ...state.terminalPaths.map((source, index) => ({
74
101
  id: `edge_${state.nextEdgeIndex + index}`,
75
- source: sourceId,
76
- target: "output"
102
+ source: [...source],
103
+ target: outputPath
77
104
  }))
78
105
  );
79
106
  return graph;
80
107
  }
81
- function nextStageLabel(state, prefix) {
82
- return `${prefix} ${state.nextNodeIndex}`;
83
- }
84
108
  function cloneGraph(graph) {
85
109
  return {
86
110
  ...graph,
87
- nodes: graph.nodes.map((node) => ({ ...node })),
88
- edges: graph.edges.map((edge) => ({ ...edge }))
111
+ nodes: graph.nodes.map((node) => ({ ...node, path: [...node.path] })),
112
+ edges: graph.edges.map((edge) => ({
113
+ ...edge,
114
+ source: [...edge.source],
115
+ target: [...edge.target]
116
+ }))
89
117
  };
90
118
  }
91
- function appendGraphNode(state, node, sourceIds, terminalNodeIds) {
92
- const edges = sourceIds.map((sourceId, index) => ({
119
+ function scopedNode(node, path) {
120
+ return { ...node, path: [...path] };
121
+ }
122
+ function appendChildGraph(state, parentPath, child) {
123
+ const childNodes = child.nodes.filter((node) => !isBoundaryPath(node.path)).map((node) => scopedNode(node, [...parentPath, ...node.path]));
124
+ const childEdges = [];
125
+ const terminalPaths = [];
126
+ let nextEdgeIndex = state.nextEdgeIndex;
127
+ for (const edge of child.edges) {
128
+ const sourceIsInput = isInputPath(edge.source);
129
+ const targetIsOutput = isOutputPath(edge.target);
130
+ const source = sourceIsInput ? [...parentPath] : [...parentPath, ...edge.source];
131
+ if (targetIsOutput) {
132
+ terminalPaths.push(source);
133
+ continue;
134
+ }
135
+ const target = [...parentPath, ...edge.target];
136
+ childEdges.push({
137
+ id: `edge_${nextEdgeIndex}`,
138
+ source,
139
+ target,
140
+ ...edge.label === void 0 ? {} : { label: edge.label }
141
+ });
142
+ nextEdgeIndex += 1;
143
+ }
144
+ return {
145
+ ...state,
146
+ graph: {
147
+ ...state.graph,
148
+ nodes: [...state.graph.nodes, ...childNodes],
149
+ edges: [...state.graph.edges, ...childEdges]
150
+ },
151
+ terminalPaths: terminalPaths.length === 0 ? [[...parentPath]] : terminalPaths,
152
+ nextEdgeIndex
153
+ };
154
+ }
155
+ function appendNode(state, node, sourcePaths, terminalPaths, stageId) {
156
+ const edges = sourcePaths.map((source, index) => ({
93
157
  id: `edge_${state.nextEdgeIndex + index}`,
94
- source: sourceId,
95
- target: node.id
158
+ source: [...source],
159
+ target: [...node.path]
96
160
  }));
97
- const terminalNodeId = terminalNodeIds.at(-1) ?? state.terminalNodeId;
161
+ const stageIds = new Set(state.stageIds);
162
+ if (stageId !== void 0) stageIds.add(stageId);
98
163
  return {
99
164
  graph: {
100
165
  ...state.graph,
101
166
  nodes: [...state.graph.nodes, node],
102
167
  edges: [...state.graph.edges, ...edges]
103
168
  },
104
- terminalNodeId,
105
- terminalNodeIds,
106
- nextNodeIndex: state.nextNodeIndex + 1,
169
+ terminalPaths,
170
+ stageIds,
107
171
  nextEdgeIndex: state.nextEdgeIndex + edges.length
108
172
  };
109
173
  }
110
- function graphNode(kind, label, index, options = {}) {
111
- const id = uniqueGraphNodeId(
112
- normalizeId(options.preferredId ?? `${kind}_${index}`),
113
- options.existingIds ?? /* @__PURE__ */ new Set()
114
- );
115
- const node = {
116
- id,
117
- kind,
118
- label
119
- };
120
- if (options.description !== void 0) {
121
- node.description = options.description;
122
- }
123
- if (options.metadata !== void 0) {
124
- node.metadata = options.metadata;
125
- }
126
- if (options.agentId !== void 0) {
127
- node.agentId = options.agentId;
128
- }
129
- if (options.agentName !== void 0) {
130
- node.agentName = options.agentName;
174
+ function graphNode(id, path, kind, label, options = {}) {
175
+ const node = { id, path: [...path], kind, label };
176
+ if (options.description !== void 0) node.description = options.description;
177
+ if (options.metadata !== void 0) node.metadata = options.metadata;
178
+ if (options.agentId !== void 0) node.agentId = options.agentId;
179
+ if (options.agentName !== void 0) node.agentName = options.agentName;
180
+ if (options.pipelineId !== void 0) node.pipelineId = options.pipelineId;
181
+ if (options.branchKey !== void 0) node.branchKey = options.branchKey;
182
+ return node;
183
+ }
184
+ function validateStageId(value) {
185
+ if (typeof value !== "string") {
186
+ throw new TypeError("Pipeline stage id must be a string.");
131
187
  }
132
- if (options.pipelineId !== void 0) {
133
- node.pipelineId = options.pipelineId;
188
+ const id = value.trim();
189
+ if (id.length === 0) {
190
+ throw new TypeError("Pipeline stage id must be a non-empty string.");
134
191
  }
135
- if (options.branchKey !== void 0) {
136
- node.branchKey = options.branchKey;
192
+ if (RESERVED_STAGE_IDS.has(id)) {
193
+ throw new TypeError(`Pipeline stage id "${id}" is reserved.`);
137
194
  }
138
- return node;
195
+ return id;
139
196
  }
140
- function normalizeId(value) {
141
- const normalized = value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
142
- return normalized.length === 0 ? "pipeline" : normalized;
197
+ function isBoundaryPath(path) {
198
+ return isInputPath(path) || isOutputPath(path);
143
199
  }
144
- function uniqueGraphNodeId(baseId, existingIds) {
145
- let id = baseId;
146
- let suffix = 2;
147
- while (existingIds.has(id)) {
148
- id = `${baseId}_${suffix}`;
149
- suffix += 1;
150
- }
151
- return id;
200
+ function isInputPath(path) {
201
+ return path.length === 1 && path[0] === INPUT_ID;
202
+ }
203
+ function isOutputPath(path) {
204
+ return path.length === 1 && path[0] === OUTPUT_ID;
205
+ }
206
+ function pathEquals(left, right) {
207
+ return left.length === right.length && left.every((segment, index) => segment === right[index]);
152
208
  }
153
-
154
- // src/pipeline/pipeline.ts
155
- var Pipeline = class {
156
- constructor(executor, pipelineGraph = initialGraph({})) {
157
- this.executor = executor;
158
- this.pipelineGraph = pipelineGraph;
159
- this.id = pipelineGraph.id;
160
- this.name = pipelineGraph.name;
161
- this.description = pipelineGraph.description;
162
- this.metadata = pipelineGraph.metadata;
163
- }
164
- executor;
165
- pipelineGraph;
166
- id;
167
- name;
168
- description;
169
- metadata;
170
- /** Run one input through the built pipeline and return the final stage output. */
171
- async run(input, options = {}) {
172
- return await this.executor(input, { observer: options.observer });
173
- }
174
- /** Run many inputs through the same pipeline with bounded concurrency. */
175
- async batch(inputs, options) {
176
- return mapWithConcurrency([...inputs], options.concurrency, (input) => this.run(input));
177
- }
178
- graph() {
179
- return cloneGraph(this.pipelineGraph);
180
- }
181
- };
182
209
 
183
210
  // src/pipeline/runtime.ts
184
- async function runNode(context, node, fn) {
211
+ async function runNode(context, node, path, fn) {
212
+ throwIfAborted(context.abortSignal);
213
+ const eventNode = scopedNode(node, path);
185
214
  const startedAt = Date.now();
186
- await context.observer?.onEvent({ type: "stage_started", node });
215
+ await emitEvent(context, {
216
+ type: "stage_started",
217
+ runId: context.runId,
218
+ pipelineId: context.pipelineId,
219
+ path: [...path],
220
+ node: eventNode
221
+ });
187
222
  try {
188
223
  const output = await fn();
189
- await context.observer?.onEvent({
224
+ throwIfAborted(context.abortSignal);
225
+ await emitEvent(context, {
190
226
  type: "stage_completed",
191
- node,
227
+ runId: context.runId,
228
+ pipelineId: context.pipelineId,
229
+ path: [...path],
230
+ node: eventNode,
192
231
  durationMs: Date.now() - startedAt
193
232
  });
194
233
  return output;
195
234
  } catch (error) {
196
- await context.observer?.onEvent({
235
+ const failureEvent = {
197
236
  type: "stage_failed",
198
- node,
237
+ runId: context.runId,
238
+ pipelineId: context.pipelineId,
239
+ path: [...path],
240
+ node: eventNode,
199
241
  durationMs: Date.now() - startedAt,
200
242
  error
201
- });
243
+ };
244
+ try {
245
+ await emitEvent(context, failureEvent);
246
+ } catch (observerError) {
247
+ throw new AggregateError(
248
+ [error, observerError],
249
+ `Pipeline stage "${node.id}" and its observer both failed.`
250
+ );
251
+ }
202
252
  throw error;
203
253
  }
204
254
  }
255
+ function stageContext(input, context) {
256
+ return {
257
+ input,
258
+ runId: context.runId,
259
+ pipelineId: context.pipelineId,
260
+ runMetadata: context.runMetadata,
261
+ abortSignal: context.abortSignal
262
+ };
263
+ }
264
+ function childContext(context, abortSignal) {
265
+ return { ...context, abortSignal };
266
+ }
267
+ function combineAbortSignals(parent, local) {
268
+ const controller = new AbortController();
269
+ const abortFromParent = () => controller.abort(parent?.reason);
270
+ const abortFromLocal = () => controller.abort(local.reason);
271
+ if (parent?.aborted === true) {
272
+ controller.abort(parent.reason);
273
+ } else if (local.aborted) {
274
+ controller.abort(local.reason);
275
+ } else {
276
+ parent?.addEventListener("abort", abortFromParent, { once: true });
277
+ local.addEventListener("abort", abortFromLocal, { once: true });
278
+ }
279
+ return {
280
+ signal: controller.signal,
281
+ dispose() {
282
+ parent?.removeEventListener("abort", abortFromParent);
283
+ local.removeEventListener("abort", abortFromLocal);
284
+ }
285
+ };
286
+ }
287
+ function pipelineAbortError(signal) {
288
+ return abortError(signal?.reason);
289
+ }
290
+ async function emitEvent(context, event) {
291
+ if (context.observer === void 0) return;
292
+ try {
293
+ await context.observer.onEvent(event);
294
+ } catch (error) {
295
+ if (context.failOnObserverError) throw error;
296
+ }
297
+ }
205
298
 
206
- // src/pipeline/builder.ts
207
- var PipelineBuilder = class _PipelineBuilder {
299
+ // src/pipeline/pipeline.ts
300
+ var internalPipelineOptions = /* @__PURE__ */ Symbol("internal-pipeline-options");
301
+ var Pipeline = class {
302
+ id;
303
+ name;
304
+ description;
305
+ metadata;
208
306
  executor;
209
307
  state;
210
- constructor(metadataOrExecutor, stateOrMetadata) {
211
- if (stateOrMetadata !== void 0 && isBuilderState(stateOrMetadata)) {
212
- this.executor = metadataOrExecutor;
213
- this.state = stateOrMetadata;
214
- return;
215
- }
216
- if (typeof metadataOrExecutor === "function") {
217
- const executor = metadataOrExecutor;
218
- this.executor = ((input) => executor(input));
219
- this.state = initialBuilderState({});
220
- return;
221
- }
222
- if (isZodSchema(metadataOrExecutor)) {
223
- const schema = metadataOrExecutor;
224
- const metadata = stateOrMetadata !== void 0 && isPipelineMetadata(stateOrMetadata) ? stateOrMetadata : {};
225
- this.executor = ((input) => schema.parse(input));
226
- this.state = initialBuilderState(metadata);
227
- return;
308
+ constructor(options) {
309
+ if (isInternalPipelineOptions(options)) {
310
+ this.executor = options[internalPipelineOptions].executor;
311
+ this.state = options[internalPipelineOptions].state;
312
+ } else {
313
+ const id = normalizePipelineId(options.id);
314
+ if (!isZodSchema(options.inputSchema)) {
315
+ throw new TypeError("Pipeline inputSchema must be a Zod schema.");
316
+ }
317
+ const inputSchema = options.inputSchema;
318
+ this.executor = (async (input, context) => {
319
+ throwIfAborted(context.abortSignal);
320
+ return inputSchema.parseAsync(input);
321
+ });
322
+ this.state = initialPipelineState({
323
+ id,
324
+ name: options.name,
325
+ description: options.description,
326
+ metadata: options.metadata
327
+ });
228
328
  }
229
- this.executor = identity;
230
- this.state = initialBuilderState(metadataOrExecutor ?? {});
329
+ const graph = this.state.graph;
330
+ this.id = graph.id;
331
+ this.name = graph.name;
332
+ this.description = graph.description;
333
+ this.metadata = graph.metadata;
231
334
  }
232
- /** Add a synchronous or asynchronous transform stage. */
233
- step(fn, metadata) {
234
- const next = appendNode(
235
- this.state,
236
- "step",
237
- metadata?.name ?? nextStageLabel(this.state, "Step"),
238
- {
239
- description: metadata?.description,
240
- metadata: metadata?.metadata,
241
- preferredId: metadata?.id
242
- }
243
- );
244
- return new _PipelineBuilder(
245
- async (input, context) => {
246
- const value = await this.runStep(input, context);
247
- const result = await runNode(context, next.node, () => fn(value));
248
- return result;
249
- },
250
- next.state
251
- );
335
+ step(options) {
336
+ const next = appendStageNode(this.state, "step", options);
337
+ const executor = (async (input, context, pathPrefix) => {
338
+ const value = await this.execute(input, context, pathPrefix);
339
+ const path = [...pathPrefix, next.node.id];
340
+ return await runNode(
341
+ context,
342
+ next.node,
343
+ path,
344
+ () => options.run(stageContext(value, context))
345
+ );
346
+ });
347
+ return this.derive(executor, next.state);
252
348
  }
253
- /** Compose another pipeline operation after the current stage. */
254
- use(op, metadata) {
255
- const nested = op instanceof Pipeline ? op : void 0;
256
- const next = appendNode(
257
- this.state,
258
- nested === void 0 ? "step" : "pipeline",
259
- metadata?.name ?? nested?.name ?? nested?.id ?? nextStageLabel(this.state, nested === void 0 ? "Operation" : "Pipeline"),
260
- {
261
- description: metadata?.description ?? nested?.description,
262
- metadata: metadata?.metadata ?? nested?.metadata,
263
- preferredId: metadata?.id,
264
- pipelineId: nested?.id
265
- }
266
- );
267
- return new _PipelineBuilder(
268
- async (input, context) => {
269
- const value = await this.runStep(input, context);
270
- const result = await runNode(context, next.node, () => op.run(value));
271
- return result;
272
- },
273
- next.state
274
- );
349
+ compose(options) {
350
+ const boundary = appendStageNode(this.state, "pipeline", options, {
351
+ defaultLabel: options.pipeline.name ?? options.pipeline.id,
352
+ pipelineId: options.pipeline.id
353
+ });
354
+ const state = appendComposedGraph(boundary.state, boundary.node, options.pipeline.graph());
355
+ const executor = (async (input, context, pathPrefix) => {
356
+ const value = await this.execute(input, context, pathPrefix);
357
+ const path = [...pathPrefix, boundary.node.id];
358
+ return await runNode(
359
+ context,
360
+ boundary.node,
361
+ path,
362
+ () => options.pipeline.execute(value, context, path)
363
+ );
364
+ });
365
+ return this.derive(executor, state);
275
366
  }
276
- /** Run named branch operations concurrently from the current value. */
277
- parallel(branches, metadata) {
278
- const parallel = appendNode(
279
- this.state,
280
- "parallel",
281
- metadata?.name ?? `${Object.keys(branches).length} parallel branches`,
282
- {
283
- description: metadata?.description,
284
- metadata: metadata?.metadata,
285
- preferredId: metadata?.id
286
- }
287
- );
367
+ parallel(options) {
368
+ const branchEntries = normalizeParallelBranches(options.branches);
369
+ if (branchEntries.length === 0) {
370
+ throw new TypeError("Pipeline parallel branches must not be empty.");
371
+ }
372
+ const parallel = appendStageNode(this.state, "parallel", options, {
373
+ defaultLabel: `${branchEntries.length} parallel branches`
374
+ });
288
375
  let nextState = parallel.state;
289
- const branchNodes = {};
290
- for (const key of Object.keys(branches)) {
291
- const branch = appendChildNode(nextState, parallel.node.id, "branch", key, {
292
- branchKey: key
293
- });
294
- nextState = branch.state;
295
- branchNodes[key] = branch.node;
376
+ const branchNodes = /* @__PURE__ */ new Map();
377
+ const terminalPaths = [];
378
+ for (const [key, branch] of branchEntries) {
379
+ const appended = appendParallelBranch(nextState, parallel.node, key, branch.graph());
380
+ nextState = appended.state;
381
+ branchNodes.set(key, appended.node);
382
+ terminalPaths.push(...appended.terminalPaths);
296
383
  }
297
- nextState = withTerminalNodes(
298
- nextState,
299
- Object.values(branchNodes).map((node) => node.id)
300
- );
301
- return new _PipelineBuilder(async (input, context) => {
302
- const value = await this.runStep(input, context);
303
- const entries = await runNode(
304
- context,
305
- parallel.node,
306
- () => Promise.all(
307
- Object.entries(branches).map(async ([key, op]) => {
308
- const node = branchNodes[key];
309
- const output = await runNode(context, node, () => op.run(value));
384
+ nextState = withTerminalPaths(nextState, terminalPaths);
385
+ return this.derive(async (input, context, pathPrefix) => {
386
+ const value = await this.execute(input, context, pathPrefix);
387
+ const parallelPath = [...pathPrefix, parallel.node.id];
388
+ return runNode(context, parallel.node, parallelPath, async () => {
389
+ const controller = new AbortController();
390
+ const combined = combineAbortSignals(context.abortSignal, controller.signal);
391
+ const branchContext = childContext(context, combined.signal);
392
+ let firstError;
393
+ const promises = branchEntries.map(async ([key, branch]) => {
394
+ const node = branchNodes.get(key);
395
+ const path = [...parallelPath, node.id];
396
+ try {
397
+ const output = await runNode(
398
+ branchContext,
399
+ node,
400
+ path,
401
+ () => branch.execute(value, branchContext, path)
402
+ );
310
403
  return [key, output];
311
- })
312
- )
313
- );
314
- return Object.fromEntries(entries);
404
+ } catch (error) {
405
+ if (firstError === void 0) firstError = error;
406
+ if (!controller.signal.aborted) controller.abort(error);
407
+ throw error;
408
+ }
409
+ });
410
+ const settled = await Promise.allSettled(promises);
411
+ combined.dispose();
412
+ if (context.abortSignal?.aborted === true) {
413
+ throw pipelineAbortError(context.abortSignal);
414
+ }
415
+ if (firstError !== void 0) throw firstError;
416
+ return Object.fromEntries(
417
+ settled.map(
418
+ (result) => result.value
419
+ )
420
+ );
421
+ });
315
422
  }, nextState);
316
423
  }
317
- /** Send the current value to an agent as text and continue with the agent output. */
318
- prompt(agent, metadata) {
319
- const next = appendNode(this.state, "agent", metadata?.name ?? agent.name ?? agent.id, {
320
- description: metadata?.description ?? agent.description,
321
- metadata: metadata?.metadata,
322
- preferredId: metadata?.id,
323
- agentId: agent.id,
324
- agentName: agent.name
424
+ agent(options) {
425
+ const next = appendStageNode(this.state, "agent", options, {
426
+ defaultLabel: options.agent.name ?? options.agent.id,
427
+ agentId: options.agent.id,
428
+ agentName: options.agent.name
325
429
  });
326
- return new _PipelineBuilder(async (input, context) => {
327
- const value = await this.runStep(input, context);
328
- return runNode(context, next.node, async () => {
329
- const response = await agent.prompt(String(value)).send();
430
+ return this.derive(async (input, context, pathPrefix) => {
431
+ const value = await this.execute(input, context, pathPrefix);
432
+ const path = [...pathPrefix, next.node.id];
433
+ return runNode(context, next.node, path, async () => {
434
+ const request = await options.request(stageContext(value, context));
435
+ const response = await options.agent.generate({
436
+ ...request,
437
+ abortSignal: context.abortSignal
438
+ });
439
+ if (response.status === "approval_required") {
440
+ await cancelAgentApproval(
441
+ response,
442
+ `Pipeline agent stage "${next.node.id}" rejects tool approval suspension.`
443
+ );
444
+ throw new PipelineAgentApprovalError(response);
445
+ }
446
+ if (response.status === "blocked") {
447
+ throw new AgentRunBlockedError(response);
448
+ }
330
449
  return response.output;
331
450
  });
332
451
  }, next.state);
333
452
  }
334
- /** Send the current value to an extractor as text and continue with typed schema data. */
335
- extract(extractor, metadata) {
336
- const next = appendNode(
337
- this.state,
338
- "extractor",
339
- metadata?.name ?? nextStageLabel(this.state, "Extractor"),
340
- {
341
- description: metadata?.description,
342
- metadata: metadata?.metadata,
343
- preferredId: metadata?.id
344
- }
345
- );
346
- return new _PipelineBuilder(async (input, context) => {
347
- const value = await this.runStep(input, context);
348
- return runNode(context, next.node, () => extractor.extract(String(value)));
453
+ extract(options) {
454
+ const next = appendStageNode(this.state, "extractor", options);
455
+ return this.derive(async (input, context, pathPrefix) => {
456
+ const value = await this.execute(input, context, pathPrefix);
457
+ const path = [...pathPrefix, next.node.id];
458
+ return runNode(context, next.node, path, async () => {
459
+ const text = await options.text(stageContext(value, context));
460
+ const result = await extract({
461
+ model: options.model,
462
+ text,
463
+ outputSchema: options.outputSchema,
464
+ instructions: options.instructions,
465
+ retries: options.retries,
466
+ temperature: options.temperature,
467
+ maxTokens: options.maxTokens,
468
+ providerOptions: options.providerOptions,
469
+ abortSignal: context.abortSignal
470
+ });
471
+ return result.output;
472
+ });
349
473
  }, next.state);
350
474
  }
351
- /** Finish the builder and return a runnable pipeline. */
352
- build() {
353
- const graph = withOutputNode(this.state);
354
- return new Pipeline(
355
- (input, context) => this.runStep(input, context),
356
- graph
357
- );
475
+ async run(options) {
476
+ const runId = normalizeRunId(options.runId ?? globalThis.crypto.randomUUID());
477
+ const context = {
478
+ runId,
479
+ pipelineId: this.id,
480
+ runMetadata: options.metadata,
481
+ abortSignal: options.abortSignal,
482
+ observer: options.observer,
483
+ failOnObserverError: options.failOnObserverError === true
484
+ };
485
+ throwIfAborted(context.abortSignal);
486
+ const output = await this.execute(options.input, context, []);
487
+ throwIfAborted(context.abortSignal);
488
+ return { runId, output };
358
489
  }
359
- async runStep(input, context) {
360
- return await this.executor(input, context);
490
+ async runBatch(options) {
491
+ throwIfAborted(options.abortSignal);
492
+ return mapWithConcurrency([...options.inputs], options.concurrency, async (input) => {
493
+ const runId = globalThis.crypto.randomUUID();
494
+ try {
495
+ const result = await this.run({
496
+ input,
497
+ runId,
498
+ metadata: options.metadata,
499
+ abortSignal: options.abortSignal,
500
+ observer: options.observer,
501
+ failOnObserverError: options.failOnObserverError
502
+ });
503
+ return { status: "completed", ...result };
504
+ } catch (error) {
505
+ if (options.abortSignal?.aborted === true) {
506
+ throw pipelineAbortError(options.abortSignal);
507
+ }
508
+ return { status: "failed", runId, error };
509
+ }
510
+ });
511
+ }
512
+ graph() {
513
+ return cloneGraph(withOutputNode(this.state));
514
+ }
515
+ derive(executor, state) {
516
+ return createDerivedPipeline(executor, state);
517
+ }
518
+ async execute(input, context, pathPrefix) {
519
+ throwIfAborted(context.abortSignal);
520
+ return await this.executor(input, context, pathPrefix);
361
521
  }
362
522
  };
363
- function identity(input) {
364
- return input;
523
+ function createDerivedPipeline(executor, state) {
524
+ const options = {
525
+ [internalPipelineOptions]: { executor, state }
526
+ };
527
+ return new Pipeline(options);
528
+ }
529
+ function isInternalPipelineOptions(options) {
530
+ return internalPipelineOptions in options;
365
531
  }
366
532
  function isZodSchema(value) {
367
533
  return value instanceof z.ZodType;
368
534
  }
369
- function isBuilderState(value) {
370
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
371
- return false;
535
+ function normalizePipelineId(id) {
536
+ if (typeof id !== "string") {
537
+ throw new TypeError("Pipeline id must be a string.");
372
538
  }
373
- const candidate = value;
374
- return "graph" in candidate && "terminalNodeId" in candidate && "terminalNodeIds" in candidate && "nextNodeIndex" in candidate && "nextEdgeIndex" in candidate;
539
+ const normalized = id.trim();
540
+ if (normalized.length === 0) {
541
+ throw new TypeError("Pipeline id must be a non-empty string.");
542
+ }
543
+ return normalized;
544
+ }
545
+ function normalizeRunId(runId) {
546
+ if (typeof runId !== "string") {
547
+ throw new TypeError("Pipeline runId must be a string.");
548
+ }
549
+ const normalized = runId.trim();
550
+ if (normalized.length === 0) {
551
+ throw new TypeError("Pipeline runId must be a non-empty string.");
552
+ }
553
+ return normalized;
375
554
  }
376
- function isPipelineMetadata(value) {
377
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
378
- return false;
555
+ function normalizeParallelBranches(branches) {
556
+ const entries = [];
557
+ const ids = /* @__PURE__ */ new Set();
558
+ for (const key of Object.keys(branches)) {
559
+ const pipeline = branches[key];
560
+ const id = key.trim();
561
+ if (id.length === 0) {
562
+ throw new TypeError("Pipeline parallel branch id must be a non-empty string.");
563
+ }
564
+ if (ids.has(id)) {
565
+ throw new TypeError(`Pipeline parallel branch id "${id}" is already registered.`);
566
+ }
567
+ ids.add(id);
568
+ if (id !== key) {
569
+ throw new TypeError("Pipeline parallel branch ids must not contain surrounding whitespace.");
570
+ }
571
+ entries.push([id, pipeline]);
379
572
  }
380
- const candidate = value;
381
- return "id" in candidate || "name" in candidate || "description" in candidate || "metadata" in candidate;
573
+ return entries;
382
574
  }
383
575
  export {
384
576
  Pipeline,
385
- PipelineBuilder
577
+ PipelineAgentApprovalError
386
578
  };
387
579
  //# sourceMappingURL=index.js.map