@anvia/core 0.26.0 → 1.0.0-rc.10

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