@voicethere/agent 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +28 -0
  2. package/dist/agent.js +11 -2
  3. package/dist/cli.d.ts +1 -0
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +11 -0
  6. package/dist/cli.js.map +1 -1
  7. package/dist/flow/classify.d.ts +12 -0
  8. package/dist/flow/classify.d.ts.map +1 -0
  9. package/dist/flow/classify.js +37 -0
  10. package/dist/flow/classify.js.map +1 -0
  11. package/dist/flow/cli-flow.d.ts +19 -0
  12. package/dist/flow/cli-flow.d.ts.map +1 -0
  13. package/dist/flow/cli-flow.js +566 -0
  14. package/dist/flow/cli-flow.js.map +1 -0
  15. package/dist/flow/core/compile.d.ts +131 -0
  16. package/dist/flow/core/compile.d.ts.map +1 -0
  17. package/dist/flow/core/compile.js +197 -0
  18. package/dist/flow/core/compile.js.map +1 -0
  19. package/dist/flow/core/conditions.d.ts +5 -0
  20. package/dist/flow/core/conditions.d.ts.map +1 -0
  21. package/dist/flow/core/conditions.js +70 -0
  22. package/dist/flow/core/conditions.js.map +1 -0
  23. package/dist/flow/core/effects.d.ts +105 -0
  24. package/dist/flow/core/effects.d.ts.map +1 -0
  25. package/dist/flow/core/effects.js +2 -0
  26. package/dist/flow/core/effects.js.map +1 -0
  27. package/dist/flow/core/generate-mock.d.ts +16 -0
  28. package/dist/flow/core/generate-mock.d.ts.map +1 -0
  29. package/dist/flow/core/generate-mock.js +206 -0
  30. package/dist/flow/core/generate-mock.js.map +1 -0
  31. package/dist/flow/core/host.d.ts +9 -0
  32. package/dist/flow/core/host.d.ts.map +1 -0
  33. package/dist/flow/core/host.js +99 -0
  34. package/dist/flow/core/host.js.map +1 -0
  35. package/dist/flow/core/index.d.ts +17 -0
  36. package/dist/flow/core/index.d.ts.map +1 -0
  37. package/dist/flow/core/index.js +17 -0
  38. package/dist/flow/core/index.js.map +1 -0
  39. package/dist/flow/core/interpreter.d.ts +69 -0
  40. package/dist/flow/core/interpreter.d.ts.map +1 -0
  41. package/dist/flow/core/interpreter.js +738 -0
  42. package/dist/flow/core/interpreter.js.map +1 -0
  43. package/dist/flow/core/json-pointer.d.ts +6 -0
  44. package/dist/flow/core/json-pointer.d.ts.map +1 -0
  45. package/dist/flow/core/json-pointer.js +28 -0
  46. package/dist/flow/core/json-pointer.js.map +1 -0
  47. package/dist/flow/core/migrate.d.ts +16 -0
  48. package/dist/flow/core/migrate.d.ts.map +1 -0
  49. package/dist/flow/core/migrate.js +29 -0
  50. package/dist/flow/core/migrate.js.map +1 -0
  51. package/dist/flow/core/mock-effects.d.ts +14 -0
  52. package/dist/flow/core/mock-effects.d.ts.map +1 -0
  53. package/dist/flow/core/mock-effects.js +90 -0
  54. package/dist/flow/core/mock-effects.js.map +1 -0
  55. package/dist/flow/core/mocks.d.ts +55 -0
  56. package/dist/flow/core/mocks.d.ts.map +1 -0
  57. package/dist/flow/core/mocks.js +73 -0
  58. package/dist/flow/core/mocks.js.map +1 -0
  59. package/dist/flow/core/route.d.ts +29 -0
  60. package/dist/flow/core/route.d.ts.map +1 -0
  61. package/dist/flow/core/route.js +61 -0
  62. package/dist/flow/core/route.js.map +1 -0
  63. package/dist/flow/core/schema.d.ts +19 -0
  64. package/dist/flow/core/schema.d.ts.map +1 -0
  65. package/dist/flow/core/schema.js +317 -0
  66. package/dist/flow/core/schema.js.map +1 -0
  67. package/dist/flow/core/template.d.ts +16 -0
  68. package/dist/flow/core/template.d.ts.map +1 -0
  69. package/dist/flow/core/template.js +65 -0
  70. package/dist/flow/core/template.js.map +1 -0
  71. package/dist/flow/core/trace.d.ts +26 -0
  72. package/dist/flow/core/trace.d.ts.map +1 -0
  73. package/dist/flow/core/trace.js +2 -0
  74. package/dist/flow/core/trace.js.map +1 -0
  75. package/dist/flow/core/types.d.ts +159 -0
  76. package/dist/flow/core/types.d.ts.map +1 -0
  77. package/dist/flow/core/types.js +2 -0
  78. package/dist/flow/core/types.js.map +1 -0
  79. package/dist/flow/core/validate.d.ts +3 -0
  80. package/dist/flow/core/validate.d.ts.map +1 -0
  81. package/dist/flow/core/validate.js +550 -0
  82. package/dist/flow/core/validate.js.map +1 -0
  83. package/dist/flow/create-flow-agent.d.ts +36 -0
  84. package/dist/flow/create-flow-agent.d.ts.map +1 -0
  85. package/dist/flow/create-flow-agent.js +175 -0
  86. package/dist/flow/create-flow-agent.js.map +1 -0
  87. package/dist/flow/effects-node.d.ts +21 -0
  88. package/dist/flow/effects-node.d.ts.map +1 -0
  89. package/dist/flow/effects-node.js +189 -0
  90. package/dist/flow/effects-node.js.map +1 -0
  91. package/dist/flow/index.d.ts +12 -0
  92. package/dist/flow/index.d.ts.map +1 -0
  93. package/dist/flow/index.js +7 -0
  94. package/dist/flow/index.js.map +1 -0
  95. package/dist/flow/llm-node.d.ts +24 -0
  96. package/dist/flow/llm-node.d.ts.map +1 -0
  97. package/dist/flow/llm-node.js +251 -0
  98. package/dist/flow/llm-node.js.map +1 -0
  99. package/dist/flow/record.d.ts +22 -0
  100. package/dist/flow/record.d.ts.map +1 -0
  101. package/dist/flow/record.js +126 -0
  102. package/dist/flow/record.js.map +1 -0
  103. package/dist/llm/agent/build-tool-registry.d.ts +26 -0
  104. package/dist/llm/agent/build-tool-registry.d.ts.map +1 -0
  105. package/dist/llm/agent/build-tool-registry.js +106 -0
  106. package/dist/llm/agent/build-tool-registry.js.map +1 -0
  107. package/dist/llm/agent/create-llm-agent.d.ts.map +1 -1
  108. package/dist/llm/agent/create-llm-agent.js +45 -106
  109. package/dist/llm/agent/create-llm-agent.js.map +1 -1
  110. package/dist/llm/anthropic-provider.d.ts.map +1 -1
  111. package/dist/llm/anthropic-provider.js +10 -0
  112. package/dist/llm/anthropic-provider.js.map +1 -1
  113. package/dist/llm/catalog.d.ts +4 -0
  114. package/dist/llm/catalog.d.ts.map +1 -1
  115. package/dist/llm/catalog.js +7 -0
  116. package/dist/llm/catalog.js.map +1 -1
  117. package/dist/llm/gemini-provider.d.ts.map +1 -1
  118. package/dist/llm/gemini-provider.js +12 -0
  119. package/dist/llm/gemini-provider.js.map +1 -1
  120. package/dist/llm/index.d.ts +2 -0
  121. package/dist/llm/index.d.ts.map +1 -1
  122. package/dist/llm/index.js +1 -0
  123. package/dist/llm/index.js.map +1 -1
  124. package/dist/llm/openai-provider.d.ts.map +1 -1
  125. package/dist/llm/openai-provider.js +10 -0
  126. package/dist/llm/openai-provider.js.map +1 -1
  127. package/dist/llm/types.d.ts +7 -2
  128. package/dist/llm/types.d.ts.map +1 -1
  129. package/dist/llm/types.js.map +1 -1
  130. package/dist/protocol.d.ts +4 -0
  131. package/dist/protocol.d.ts.map +1 -1
  132. package/dist/protocol.js.map +1 -1
  133. package/dist/runtime.d.ts +4 -0
  134. package/dist/runtime.d.ts.map +1 -1
  135. package/dist/runtime.js +10 -0
  136. package/dist/runtime.js.map +1 -1
  137. package/dist/templates/echo/agent.js +12 -2
  138. package/dist/templates/flow-agent/agent.js +49085 -0
  139. package/dist/templates/language-switch/agent.js +12 -2
  140. package/dist/templates/llm-agent/agent.js +156 -106
  141. package/dist/templates/llm-docs-rag/agent.js +156 -106
  142. package/dist/templates/llm-mcp-service/agent.js +156 -106
  143. package/dist/templates/positional-tts/agent.js +12 -2
  144. package/dist/templates/recording-consent/agent.js +12 -2
  145. package/dist/templates/registry.d.ts.map +1 -1
  146. package/dist/templates/registry.js +23 -0
  147. package/dist/templates/registry.js.map +1 -1
  148. package/dist/templates/spatial-showcase/agent.js +12 -2
  149. package/dist/templates/voice-showcase/agent.js +12 -2
  150. package/dist/templates/voice-starter/agent.js +12 -2
  151. package/dist/templates/webhooks/agent.js +12 -2
  152. package/eject/llm/loop.ts +51 -104
  153. package/package.json +19 -2
  154. package/schema/voicethere.flow.schema.json +681 -0
  155. package/templates/flow-agent/README.md +38 -0
  156. package/templates/flow-agent/agent.ts +14 -0
  157. package/templates/flow-agent/tools.ts +5 -0
  158. package/templates/flow-agent/voicethere.flow.json +80 -0
  159. package/templates/flow-agent/voicethere.flow.mocks.json +17 -0
  160. package/templates/llm-agent/README.md +4 -2
@@ -0,0 +1,738 @@
1
+ import { renderValue } from "./compile.js";
2
+ import { resolvePointer } from "./json-pointer.js";
3
+ import { matchRule } from "./route.js";
4
+ import { renderTemplate } from "./template.js";
5
+ /** Backstop for a whole llm node (all rounds and tool calls). */
6
+ export const LLM_NODE_TIMEOUT_MS = 120_000;
7
+ export class FlowSession {
8
+ compiled;
9
+ fx;
10
+ opts;
11
+ maxSteps;
12
+ vars = {};
13
+ history = [];
14
+ nodeIndex;
15
+ channel;
16
+ pendingFinal;
17
+ stepSeq = 0;
18
+ traceSeq = 0;
19
+ stepsThisTurn = 0;
20
+ turnStartSeq = 0;
21
+ waiting;
22
+ cancelCurrent;
23
+ running = false;
24
+ again = false;
25
+ started = false;
26
+ _ended = false;
27
+ _staleDropped = 0;
28
+ constructor(compiled, effects, opts) {
29
+ this.compiled = compiled;
30
+ this.fx = effects;
31
+ this.opts = opts;
32
+ this.maxSteps = opts.maxStepsPerTurn ?? 100;
33
+ this.channel = opts.channel;
34
+ this.nodeIndex = compiled.start;
35
+ this.vars = Object.assign(Object.create(null), compiled.defaults, opts.initialVars ?? {}, { "session.id": opts.sessionId, "session.channel": opts.channel });
36
+ }
37
+ get ended() {
38
+ return this._ended;
39
+ }
40
+ get staleDropped() {
41
+ return this._staleDropped;
42
+ }
43
+ get variables() {
44
+ return { ...this.vars };
45
+ }
46
+ /** Prototype of the internal variable store (null). */
47
+ get variablesPrototype() {
48
+ return Object.getPrototypeOf(this.vars);
49
+ }
50
+ get conversation() {
51
+ return this.history.map((h) => ({ ...h }));
52
+ }
53
+ start() {
54
+ if (this.started || this._ended)
55
+ return Promise.resolve();
56
+ this.started = true;
57
+ return this.drive();
58
+ }
59
+ onUserText(text, o = {}) {
60
+ if (this._ended || !this.started)
61
+ return Promise.resolve();
62
+ const w = this.waiting;
63
+ if (w) {
64
+ this.resumeListen(w, "input", { text, ...o });
65
+ return this.drive();
66
+ }
67
+ // Metadata only: no text.
68
+ this.fx.log?.("info", "flow_input_buffered", {
69
+ length: text.length,
70
+ ...(o.utteranceId !== undefined ? { utteranceId: o.utteranceId } : {}),
71
+ replaced: this.pendingFinal !== undefined,
72
+ });
73
+ this.pendingFinal = { text, ...o };
74
+ return Promise.resolve();
75
+ }
76
+ stop() {
77
+ if (this._ended)
78
+ return;
79
+ this._ended = true;
80
+ this.stepSeq++;
81
+ this.waiting?.cancelTimer();
82
+ this.waiting = undefined;
83
+ this.cancelCurrent?.();
84
+ this.cancelCurrent = undefined;
85
+ }
86
+ // ---- internals ----
87
+ lookup = (path) => {
88
+ if (Object.hasOwn(this.vars, path))
89
+ return this.vars[path];
90
+ const parts = path.split(".");
91
+ for (let k = parts.length - 1; k >= 1; k--) {
92
+ const head = parts.slice(0, k).join(".");
93
+ if (Object.hasOwn(this.vars, head)) {
94
+ let cur = this.vars[head];
95
+ for (const key of parts.slice(k)) {
96
+ if (cur === null || typeof cur !== "object")
97
+ return undefined;
98
+ cur = Object.hasOwn(cur, key)
99
+ ? cur[key]
100
+ : undefined;
101
+ }
102
+ return cur;
103
+ }
104
+ }
105
+ return undefined;
106
+ };
107
+ render(parts) {
108
+ return renderTemplate(parts, this.lookup);
109
+ }
110
+ emit(node, phase, extra = {}) {
111
+ const seq = ++this.traceSeq;
112
+ const e = {
113
+ seq,
114
+ stepSeq: this.stepSeq,
115
+ nodeId: node.id,
116
+ type: node.type,
117
+ phase,
118
+ ...extra,
119
+ };
120
+ if (phase === "exit" && this.opts.includeValuesInTrace)
121
+ e.vars = { ...this.vars };
122
+ this.fx.trace(e);
123
+ return seq;
124
+ }
125
+ async drive() {
126
+ if (this.running) {
127
+ this.again = true;
128
+ return;
129
+ }
130
+ this.running = true;
131
+ try {
132
+ do {
133
+ this.again = false;
134
+ try {
135
+ await this.loop();
136
+ }
137
+ catch {
138
+ this.failEffect();
139
+ return;
140
+ }
141
+ } while (this.again && !this._ended);
142
+ }
143
+ finally {
144
+ this.running = false;
145
+ }
146
+ }
147
+ failEffect() {
148
+ this.cancelCurrent?.();
149
+ this.cancelCurrent = undefined;
150
+ if (this._ended)
151
+ return;
152
+ this._ended = true;
153
+ this.waiting?.cancelTimer();
154
+ this.waiting = undefined;
155
+ try {
156
+ const node = this.compiled.nodes[this.nodeIndex];
157
+ this.emit(node, "exit", { error: "FLOW_EFFECT_ERROR" });
158
+ this.fx.end("error");
159
+ }
160
+ catch {
161
+ // reporting must not throw out of the drive loop
162
+ }
163
+ }
164
+ nameOf(i) {
165
+ return this.compiled.nodes[i].id;
166
+ }
167
+ get turnId() {
168
+ return `${this.opts.sessionId}:${this.turnStartSeq}`;
169
+ }
170
+ resumeListen(w, how, input) {
171
+ const node = this.compiled.nodes[w.index];
172
+ if (node.type !== "listen")
173
+ return;
174
+ w.cancelTimer();
175
+ this.waiting = undefined;
176
+ const changed = [];
177
+ let target;
178
+ if (how === "input" && input) {
179
+ this.applyInput(input, changed);
180
+ target = node.next;
181
+ }
182
+ else {
183
+ target = node.onNoInput;
184
+ }
185
+ this.stepsThisTurn = 0;
186
+ this.turnStartSeq = this.stepSeq;
187
+ this.emit(node, "exit", {
188
+ edge: this.nameOf(target),
189
+ durationMs: this.fx.clock.now() - w.enterAt,
190
+ varsChanged: changed,
191
+ });
192
+ this.nodeIndex = target;
193
+ }
194
+ applyInput(input, changed) {
195
+ if (input.source !== undefined && input.source !== this.channel) {
196
+ this.channel = input.source;
197
+ this.vars["session.channel"] = input.source;
198
+ changed.push("session.channel");
199
+ }
200
+ this.vars["last.transcript"] = input.text;
201
+ changed.push("last.transcript");
202
+ if (input.utteranceId !== undefined) {
203
+ this.vars["last.utteranceId"] = input.utteranceId;
204
+ changed.push("last.utteranceId");
205
+ }
206
+ if (input.language !== undefined) {
207
+ this.vars["last.language"] = input.language;
208
+ changed.push("last.language");
209
+ }
210
+ else if (Object.hasOwn(this.vars, "last.language")) {
211
+ delete this.vars["last.language"];
212
+ changed.push("last.language");
213
+ }
214
+ this.history.push({ role: "user", text: input.text });
215
+ }
216
+ setError(id, code, changed) {
217
+ this.vars[`error.${id}`] = code;
218
+ changed.push(`error.${id}`);
219
+ }
220
+ clearError(id, changed) {
221
+ if (Object.hasOwn(this.vars, `error.${id}`)) {
222
+ delete this.vars[`error.${id}`];
223
+ changed.push(`error.${id}`);
224
+ }
225
+ }
226
+ applyMap(map, body, changed) {
227
+ for (const [name, pointer] of map) {
228
+ const v = resolvePointer(body, pointer);
229
+ if (v === undefined)
230
+ continue;
231
+ this.vars[name] = v;
232
+ changed.push(name);
233
+ }
234
+ }
235
+ /** Runs one effect call with a timeout; `cancelCurrent` cancels it. */
236
+ async bounded(timeoutMs, start) {
237
+ const ctl = new AbortController();
238
+ let cancelTimer = () => { };
239
+ const out = await new Promise((resolve) => {
240
+ cancelTimer = this.fx.clock.setTimeout(() => {
241
+ ctl.abort();
242
+ resolve({ k: "timeout" });
243
+ }, timeoutMs);
244
+ this.cancelCurrent = () => {
245
+ cancelTimer();
246
+ ctl.abort();
247
+ resolve({ k: "cancelled" });
248
+ };
249
+ let p;
250
+ try {
251
+ p = start(ctl.signal);
252
+ }
253
+ catch (err) {
254
+ resolve({ k: "err", err });
255
+ return;
256
+ }
257
+ p.then((v) => resolve({ k: "ok", v }), (err) => resolve({ k: "err", err }));
258
+ });
259
+ cancelTimer();
260
+ this.cancelCurrent = undefined;
261
+ return out;
262
+ }
263
+ stale(seq) {
264
+ if (this._ended || seq !== this.stepSeq) {
265
+ this._staleDropped++;
266
+ return true;
267
+ }
268
+ return false;
269
+ }
270
+ async loop() {
271
+ while (!this._ended) {
272
+ if (this.waiting)
273
+ return;
274
+ if (this.stepsThisTurn >= this.maxSteps) {
275
+ const node = this.compiled.nodes[this.nodeIndex];
276
+ this.stepSeq++;
277
+ this.emit(node, "exit", { error: "FLOW_STEP_LIMIT" });
278
+ this._ended = true;
279
+ this.fx.end("step_limit");
280
+ return;
281
+ }
282
+ const index = this.nodeIndex;
283
+ const node = this.compiled.nodes[index];
284
+ const seq = ++this.stepSeq;
285
+ this.stepsThisTurn++;
286
+ const t0 = this.fx.clock.now();
287
+ const enterSeq = this.emit(node, "enter");
288
+ const done = (target, extra = {}) => {
289
+ this.emit(node, "exit", {
290
+ durationMs: this.fx.clock.now() - t0,
291
+ ...(target !== undefined ? { edge: this.nameOf(target) } : {}),
292
+ ...extra,
293
+ });
294
+ if (target !== undefined)
295
+ this.nodeIndex = target;
296
+ };
297
+ switch (node.type) {
298
+ case "speak": {
299
+ const text = this.render(node.text);
300
+ this.history.push({ role: "assistant", text });
301
+ if (this.channel === "chat") {
302
+ this.fx.chat?.(text);
303
+ }
304
+ else {
305
+ const h = this.fx.speak(text, {
306
+ interruptible: node.interruptible,
307
+ turnId: this.turnId,
308
+ });
309
+ this.cancelCurrent = h.cancel;
310
+ await h.done;
311
+ this.cancelCurrent = undefined;
312
+ if (this.stale(seq))
313
+ return;
314
+ }
315
+ done(node.next);
316
+ break;
317
+ }
318
+ case "listen": {
319
+ if (this.pendingFinal) {
320
+ const p = this.pendingFinal;
321
+ this.pendingFinal = undefined;
322
+ const changed = [];
323
+ this.applyInput(p, changed);
324
+ this.stepsThisTurn = 0;
325
+ this.turnStartSeq = this.stepSeq;
326
+ done(node.next, { varsChanged: changed });
327
+ break;
328
+ }
329
+ const cancelTimer = this.fx.clock.setTimeout(() => {
330
+ const w = this.waiting;
331
+ if (!w || w.seq !== seq || this._ended)
332
+ return;
333
+ try {
334
+ this.resumeListen(w, "timeout");
335
+ }
336
+ catch {
337
+ this.failEffect();
338
+ return;
339
+ }
340
+ void this.drive();
341
+ }, node.timeoutMs);
342
+ this.waiting = {
343
+ index,
344
+ seq,
345
+ cancelTimer,
346
+ enterAt: t0,
347
+ eventSeq: enterSeq,
348
+ };
349
+ return;
350
+ }
351
+ case "wait": {
352
+ let cancel = () => { };
353
+ await new Promise((resolve) => {
354
+ cancel = this.fx.clock.setTimeout(resolve, node.ms);
355
+ this.cancelCurrent = () => {
356
+ cancel();
357
+ resolve();
358
+ };
359
+ });
360
+ this.cancelCurrent = undefined;
361
+ if (this.stale(seq))
362
+ return;
363
+ this.stepsThisTurn = 0;
364
+ done(node.next);
365
+ break;
366
+ }
367
+ case "set": {
368
+ const changed = [];
369
+ for (const a of node.assign) {
370
+ this.vars[a.name] =
371
+ typeof a.value === "object" ? this.render(a.value) : a.value;
372
+ changed.push(a.name);
373
+ }
374
+ done(node.next, { varsChanged: changed });
375
+ break;
376
+ }
377
+ case "condition": {
378
+ done(node.test(this.lookup) ? node.then : node.else);
379
+ break;
380
+ }
381
+ case "end": {
382
+ if (node.text) {
383
+ const text = this.render(node.text);
384
+ this.history.push({ role: "assistant", text });
385
+ if (this.channel === "chat") {
386
+ this.fx.chat?.(text);
387
+ }
388
+ else {
389
+ const h = this.fx.speak(text, {
390
+ interruptible: false,
391
+ turnId: this.turnId,
392
+ });
393
+ this.cancelCurrent = h.cancel;
394
+ await h.done;
395
+ this.cancelCurrent = undefined;
396
+ if (this.stale(seq))
397
+ return;
398
+ }
399
+ }
400
+ done(undefined);
401
+ this._ended = true;
402
+ this.fx.end(node.reason);
403
+ return;
404
+ }
405
+ case "route": {
406
+ const text = this.render(node.input);
407
+ const rule = matchRule(node.paths, text);
408
+ let chosen = rule.path;
409
+ let via = "rule";
410
+ let errCode;
411
+ let tokens;
412
+ if (!chosen) {
413
+ via = "classifier";
414
+ const model = this.compiled.models[node.model ?? "classifier"] ??
415
+ this.compiled.models["default"];
416
+ const ctl = new AbortController();
417
+ let cancelTimer = () => { };
418
+ const outcome = await new Promise((resolve) => {
419
+ cancelTimer = this.fx.clock.setTimeout(() => {
420
+ ctl.abort();
421
+ resolve({ k: "timeout" });
422
+ }, node.timeoutMs);
423
+ this.cancelCurrent = () => {
424
+ cancelTimer();
425
+ ctl.abort();
426
+ resolve({ k: "cancelled" });
427
+ };
428
+ let p;
429
+ try {
430
+ p = this.fx.classify({
431
+ model: model,
432
+ input: text,
433
+ paths: node.paths.map((x) => ({
434
+ id: x.id,
435
+ examples: x.examples,
436
+ })),
437
+ ...(node.historyTurns > 0
438
+ ? {
439
+ history: this.history
440
+ .slice(-node.historyTurns * 2)
441
+ .map((h) => ({ ...h })),
442
+ }
443
+ : {}),
444
+ timeoutMs: node.timeoutMs,
445
+ }, ctl.signal);
446
+ }
447
+ catch (err) {
448
+ resolve({ k: "err", code: errorCode(err) });
449
+ return;
450
+ }
451
+ p.then((r) => resolve({ k: "ok", path: r.path, tokens: r.tokens }), (err) => resolve({ k: "err", code: errorCode(err) }));
452
+ });
453
+ cancelTimer();
454
+ this.cancelCurrent = undefined;
455
+ if (this.stale(seq))
456
+ return;
457
+ if (outcome.k === "timeout")
458
+ errCode = "ROUTE_TIMEOUT";
459
+ else if (outcome.k === "err")
460
+ errCode = outcome.code;
461
+ else if (outcome.k === "ok") {
462
+ chosen = node.paths.find((x) => x.id === outcome.path);
463
+ tokens = outcome.tokens;
464
+ }
465
+ }
466
+ if (errCode !== undefined) {
467
+ this.vars[`error.${node.id}`] = errCode;
468
+ done(node.onError, {
469
+ via,
470
+ error: errCode,
471
+ ...(tokens ? { tokens } : {}),
472
+ varsChanged: [`error.${node.id}`],
473
+ });
474
+ break;
475
+ }
476
+ if (!chosen) {
477
+ done(node.onNone, {
478
+ via,
479
+ edge: "none",
480
+ ...(tokens ? { tokens } : {}),
481
+ });
482
+ break;
483
+ }
484
+ this.vars[`route.${node.id}`] = chosen.id;
485
+ done(chosen.next, {
486
+ edge: chosen.id,
487
+ via,
488
+ ...(tokens ? { tokens } : {}),
489
+ varsChanged: [`route.${node.id}`],
490
+ });
491
+ break;
492
+ }
493
+ case "http": {
494
+ const headers = {};
495
+ for (const [k, h] of node.headers) {
496
+ headers[k] =
497
+ h.kind === "secret"
498
+ ? { secret: h.secret, prefix: h.prefix }
499
+ : this.render(h.parts);
500
+ }
501
+ const req = {
502
+ method: node.method,
503
+ url: this.render(node.url),
504
+ headers,
505
+ ...(node.body !== undefined
506
+ ? { body: renderValue(node.body, (p) => this.render(p)) }
507
+ : {}),
508
+ timeoutMs: node.timeoutMs,
509
+ };
510
+ const out = await this.bounded(node.timeoutMs, (sig) => this.fx.http(req, sig));
511
+ if (this.stale(seq))
512
+ return;
513
+ const changed = [];
514
+ let code;
515
+ if (out.k === "timeout")
516
+ code = "HTTP_TIMEOUT";
517
+ else if (out.k === "err")
518
+ code = errorCode(out.err, "HTTP_NETWORK");
519
+ else if (out.k === "ok") {
520
+ const st = out.v.status;
521
+ this.vars[`${node.id}.status`] = st;
522
+ changed.push(`${node.id}.status`);
523
+ if (st < 200 || st >= 300)
524
+ code = `HTTP_${st}`;
525
+ else
526
+ this.applyMap(node.map, out.v.body, changed);
527
+ }
528
+ if (code !== undefined) {
529
+ this.setError(node.id, code, changed);
530
+ done(node.onError, { error: code, varsChanged: changed });
531
+ }
532
+ else {
533
+ this.clearError(node.id, changed);
534
+ done(node.next, { varsChanged: changed });
535
+ }
536
+ break;
537
+ }
538
+ case "mcp": {
539
+ const args = node.args === undefined
540
+ ? {}
541
+ : renderValue(node.args, (p) => this.render(p));
542
+ const out = await this.bounded(node.timeoutMs, (sig) => this.fx.tool(node.source, node.tool, args, sig, {
543
+ timeoutMs: node.timeoutMs,
544
+ }));
545
+ if (this.stale(seq))
546
+ return;
547
+ const changed = [];
548
+ let code;
549
+ if (out.k === "timeout")
550
+ code = "MCP_TIMEOUT";
551
+ else if (out.k === "err")
552
+ code = errorCode(out.err, "MCP_ERROR");
553
+ else if (out.k === "ok") {
554
+ if (out.v.isError)
555
+ code = "MCP_TOOL_ERROR";
556
+ else {
557
+ const parsed = parseJson(out.v.content);
558
+ const structured = parsed !== null && typeof parsed === "object"
559
+ ? parsed
560
+ : undefined;
561
+ if (node.map.length > 0)
562
+ this.applyMap(node.map, structured ?? out.v.content, changed);
563
+ else {
564
+ this.vars[`${node.id}.result`] = structured ?? out.v.content;
565
+ changed.push(`${node.id}.result`);
566
+ }
567
+ }
568
+ }
569
+ if (code !== undefined) {
570
+ this.setError(node.id, code, changed);
571
+ done(node.onError, { error: code, varsChanged: changed });
572
+ }
573
+ else {
574
+ this.clearError(node.id, changed);
575
+ done(node.next, { varsChanged: changed });
576
+ }
577
+ break;
578
+ }
579
+ case "llm": {
580
+ const hist = this.history.map((h) => ({ ...h }));
581
+ const messages = node.send === "message"
582
+ ? [
583
+ {
584
+ role: "user",
585
+ text: node.message ? this.render(node.message) : "",
586
+ },
587
+ ]
588
+ : node.historyTurns !== undefined
589
+ ? hist.slice(-node.historyTurns)
590
+ : hist;
591
+ const ctl = new AbortController();
592
+ const handles = [];
593
+ const spoken = [];
594
+ let timedOut = false;
595
+ let cancelled = false;
596
+ let abortWake = () => { };
597
+ const aborted = new Promise((resolve) => {
598
+ abortWake = () => resolve("aborted");
599
+ });
600
+ const cancelTimer = this.fx.clock.setTimeout(() => {
601
+ timedOut = true;
602
+ ctl.abort();
603
+ abortWake();
604
+ }, LLM_NODE_TIMEOUT_MS);
605
+ this.cancelCurrent = () => {
606
+ cancelled = true;
607
+ ctl.abort();
608
+ abortWake();
609
+ for (const h of handles)
610
+ h.cancel();
611
+ };
612
+ let code;
613
+ let finalText;
614
+ let tokens;
615
+ try {
616
+ const iter = this.fx
617
+ .llm({
618
+ model: this.compiled.models[node.model ?? "default"],
619
+ system: this.render(node.instructions),
620
+ messages,
621
+ tools: node.tools,
622
+ speak: node.speak,
623
+ maxRounds: node.maxRounds,
624
+ ...(node.filler ? { filler: node.filler } : {}),
625
+ }, ctl.signal)[Symbol.asyncIterator]();
626
+ for (;;) {
627
+ const r = await Promise.race([iter.next(), aborted]);
628
+ if (cancelled || this._ended) {
629
+ // stop() can win while a result is already resolved: act on nothing.
630
+ void iter.return?.(undefined)?.catch?.(() => { });
631
+ break;
632
+ }
633
+ if (r === "aborted") {
634
+ void iter.return?.(undefined)?.catch?.(() => { });
635
+ break;
636
+ }
637
+ if (r.done)
638
+ break;
639
+ const ev = r.value;
640
+ if (ev.type === "sentence") {
641
+ if (this.channel === "chat") {
642
+ // Chat gets one reply at the end of the node, not one per sentence.
643
+ }
644
+ else {
645
+ handles.push(this.fx.speak(ev.text, {
646
+ interruptible: true,
647
+ turnId: this.turnId,
648
+ ...(ev.filler ? { filler: true } : {}),
649
+ }));
650
+ }
651
+ if (!ev.filler)
652
+ spoken.push(ev.text);
653
+ }
654
+ else if (ev.type === "tool") {
655
+ if (ev.phase === "start") {
656
+ this.emit(node, "enter", { parent: enterSeq, tool: ev.name });
657
+ }
658
+ else {
659
+ this.emit(node, "exit", {
660
+ parent: enterSeq,
661
+ tool: ev.name,
662
+ ...(ev.durationMs !== undefined
663
+ ? { durationMs: ev.durationMs }
664
+ : {}),
665
+ ...(ev.error ? { error: ev.error } : {}),
666
+ });
667
+ }
668
+ }
669
+ else {
670
+ finalText = ev.text;
671
+ tokens = ev.tokens;
672
+ }
673
+ }
674
+ if (timedOut)
675
+ code = "LLM_TIMEOUT";
676
+ else if (!cancelled && finalText === undefined)
677
+ code = "LLM_NO_RESULT";
678
+ }
679
+ catch (err) {
680
+ code = timedOut ? "LLM_TIMEOUT" : errorCode(err, "LLM_ERROR");
681
+ }
682
+ cancelTimer();
683
+ this.cancelCurrent = undefined;
684
+ if (cancelled || this.stale(seq))
685
+ return;
686
+ if (this.channel === "chat" && spoken.length > 0)
687
+ this.fx.chat?.(spoken.join(" "));
688
+ if (handles.length > 0) {
689
+ this.cancelCurrent = () => {
690
+ for (const h of handles)
691
+ h.cancel();
692
+ };
693
+ await Promise.all(handles.map((h) => h.done.catch(() => { })));
694
+ this.cancelCurrent = undefined;
695
+ if (this.stale(seq))
696
+ return;
697
+ }
698
+ const changed = [];
699
+ if (spoken.length > 0)
700
+ this.history.push({ role: "assistant", text: spoken.join(" ") });
701
+ if (code !== undefined) {
702
+ this.setError(node.id, code, changed);
703
+ done(node.onError, {
704
+ error: code,
705
+ varsChanged: changed,
706
+ ...(tokens ? { tokens } : {}),
707
+ });
708
+ }
709
+ else {
710
+ if (node.saveAs !== undefined) {
711
+ this.vars[node.saveAs] = finalText ?? "";
712
+ changed.push(node.saveAs);
713
+ }
714
+ this.clearError(node.id, changed);
715
+ done(node.next, {
716
+ varsChanged: changed,
717
+ ...(tokens ? { tokens } : {}),
718
+ });
719
+ }
720
+ break;
721
+ }
722
+ }
723
+ }
724
+ }
725
+ }
726
+ function errorCode(err, fallback = "ROUTE_ERROR") {
727
+ const c = err?.code;
728
+ return typeof c === "string" && c !== "" ? c : fallback;
729
+ }
730
+ function parseJson(text) {
731
+ try {
732
+ return JSON.parse(text);
733
+ }
734
+ catch {
735
+ return undefined;
736
+ }
737
+ }
738
+ //# sourceMappingURL=interpreter.js.map