@voltro/plugin-ai-flows 0.83.0 → 0.83.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,83 +1,83 @@
1
1
  import { FLOW_RUN_WORKFLOW as e, HUMAN_RESPONSE_SIGNAL_PREFIX as t, flowRunWorkflow as n, humanResponseSignalName as r } from "./workflow.js";
2
- import { A as i, B as a, C as o, D as s, E as c, F as l, H as u, I as d, L as f, M as p, N as m, O as h, P as ee, R as g, S as te, T as ne, V as _, _ as re, a as ie, b as v, c as ae, d as y, f as oe, g as se, h as ce, i as b, j as le, k as ue, l as de, m as fe, n as pe, o as x, p as me, r as he, s as ge, t as _e, u as ve, v as ye, w as be, x as xe, y as Se, z as Ce } from "./ir-DcPJp738.js";
2
+ import { A as i, B as a, C as o, D as s, E as c, F as l, H as u, I as d, L as f, M as p, N as m, O as h, P as ee, R as te, S as g, T as _, V as v, _ as y, a as ne, b as re, c as ie, d as ae, f as oe, g as se, h as ce, i as b, j as le, k as ue, l as de, m as fe, n as pe, o as x, p as me, r as he, s as ge, t as _e, u as ve, v as ye, w as be, x as xe, y as Se, z as Ce } from "./ir-CdDUTf98.js";
3
3
  import { FlowBriefIncomplete as we, FlowCapabilityMissing as S, FlowDependencyError as Te, FlowNotAwaitingResponse as Ee, FlowNotFound as De, FlowReviewDeliveryError as Oe, FlowRunNotFound as C, FlowValidationError as ke } from "./errors.js";
4
4
  import { n as Ae, t as je } from "./cadence-_9Izk_fL.js";
5
- import { Cause as Me, Effect as w, Schema as T } from "effect";
6
- import { WorkflowControlResultSchema as Ne, WorkflowRunHandleSchema as Pe, definePlugin as Fe, pluginInstanceName as Ie } from "@voltro/protocol";
7
- import { and as E, boolean as Le, eq as D, id as Re, inSet as ze, integer as O, json as k, notInSet as Be, queryFor as A, registerRetention as Ve, table as He, text as j, timestamp as M } from "@voltro/database";
8
- import { tenant as Ue } from "@voltro/plugin-multitenancy/mixin";
9
- import { audit as We } from "@voltro/plugin-audit/mixin";
10
- import { softDelete as Ge } from "@voltro/plugin-soft-delete/mixin";
11
- import { awaitSignalSuspending as Ke, step as N } from "@voltro/workflow";
12
- import { defineTool as P, estimateCostUsd as qe, gatewayCostUsd as Je, generateImage as Ye, generateObject as Xe, generateObjectJson as Ze, generateObjectWithTools as Qe, generateSpeech as $e, generateText as et, generateVideo as tt, isMeteredUsage as nt } from "@voltro/ai";
13
- import { createHash as rt } from "node:crypto";
5
+ import { Cause as Me, Effect as w, Exit as Ne, Schema as T } from "effect";
6
+ import { WorkflowControlResultSchema as Pe, WorkflowRunHandleSchema as Fe, definePlugin as Ie, pluginInstanceName as Le } from "@voltro/protocol";
7
+ import { and as Re, boolean as ze, eq as E, id as Be, inSet as Ve, integer as D, json as O, notInSet as He, queryFor as k, registerRetention as Ue, table as We, text as A, timestamp as Ge } from "@voltro/database";
8
+ import { tenant as Ke } from "@voltro/plugin-multitenancy/mixin";
9
+ import { audit as qe } from "@voltro/plugin-audit/mixin";
10
+ import { softDelete as Je } from "@voltro/plugin-soft-delete/mixin";
11
+ import { SuspensionUnavailable as Ye, awaitSignalSuspending as Xe, step as j } from "@voltro/workflow";
12
+ import { defineTool as M, estimateCostUsd as Ze, gatewayCostUsd as Qe, generateImage as $e, generateObject as et, generateObjectJson as tt, generateObjectWithTools as nt, generateSpeech as rt, generateText as it, generateVideo as at, isMeteredUsage as ot } from "@voltro/ai";
13
+ import { createHash as st } from "node:crypto";
14
14
  //#region src/registry.ts
15
- var F = /* @__PURE__ */ new Map(), it = (e) => {
16
- F.set(e.name, e);
17
- }, at = (e) => F.get(e), ot = () => [...F.values()], st = () => F.clear(), I = He("_voltro_ai_flows", {
18
- id: Re({ prefix: "aifl" }),
19
- name: j(),
20
- description: j().nullable(),
21
- mode: j().default("deterministic"),
22
- status: j().default("draft"),
23
- visibility: j().default("private"),
24
- orchestratorModel: j().nullable(),
25
- orchestratorInstructions: j().nullable(),
26
- maxSteps: O().default(30),
27
- steps: k().nullable(),
28
- inputSchema: k().nullable(),
29
- chainTo: k().nullable(),
30
- cadence: k().nullable(),
31
- humanTimeoutMs: O().nullable(),
32
- isEnabled: Le().default(!0),
33
- metadata: k().nullable(),
34
- icon: j().nullable(),
35
- color: j().nullable(),
36
- avatarUrl: j().nullable(),
37
- usageCount: O().default(0),
38
- ownerId: j().nullable()
39
- }).renamedFrom("ai_flows").with(Ue(), We(), Ge()).index(["status"]).index(["visibility"]), L = He("_voltro_ai_flow_runs", {
40
- id: Re({ prefix: "aifr" }),
41
- flowRef: j(),
42
- flowName: j().nullable(),
43
- mode: j().default("deterministic"),
44
- status: j().default("pending"),
45
- source: j().nullable(),
46
- requestId: j(),
47
- workflowStart: k().nullable(),
48
- input: k().nullable(),
49
- output: k().nullable(),
50
- steps: k().nullable(),
51
- currentStep: O().default(0),
52
- totalSteps: O().default(0),
53
- humanResponse: k().nullable(),
54
- chainPending: k().nullable(),
55
- chainRefusal: j().nullable(),
56
- costMicroUsd: O().default(0),
57
- costCompleteness: j().default("unknown"),
58
- durationMs: O().nullable(),
59
- error: j().nullable(),
60
- errorMessage: j().nullable(),
61
- startedAt: M().nullable(),
62
- completedAt: M().nullable(),
63
- cancelledAt: M().nullable(),
64
- sessionId: j().nullable(),
65
- sessionName: j().nullable(),
66
- ownerId: j().nullable(),
67
- metadata: k().nullable()
68
- }).renamedFrom("ai_flow_runs").with(Ue(), We()).index(["flowRef"]).index(["status"]).index(["requestId"]), ct = [I, L], lt = T.Struct({
15
+ var N = /* @__PURE__ */ new Map(), ct = (e) => {
16
+ N.set(e.name, e);
17
+ }, lt = (e) => N.get(e), P = () => [...N.values()], ut = () => N.clear(), F = We("_voltro_ai_flows", {
18
+ id: Be({ prefix: "aifl" }),
19
+ name: A(),
20
+ description: A().nullable(),
21
+ mode: A().default("deterministic"),
22
+ status: A().default("draft"),
23
+ visibility: A().default("private"),
24
+ orchestratorModel: A().nullable(),
25
+ orchestratorInstructions: A().nullable(),
26
+ maxSteps: D().default(30),
27
+ steps: O().nullable(),
28
+ inputSchema: O().nullable(),
29
+ chainTo: O().nullable(),
30
+ cadence: O().nullable(),
31
+ humanTimeoutMs: D().nullable(),
32
+ isEnabled: ze().default(!0),
33
+ metadata: O().nullable(),
34
+ icon: A().nullable(),
35
+ color: A().nullable(),
36
+ avatarUrl: A().nullable(),
37
+ usageCount: D().default(0),
38
+ ownerId: A().nullable()
39
+ }).renamedFrom("ai_flows").with(Ke(), qe(), Je()).index(["status"]).index(["visibility"]), I = We("_voltro_ai_flow_runs", {
40
+ id: Be({ prefix: "aifr" }),
41
+ flowRef: A(),
42
+ flowName: A().nullable(),
43
+ mode: A().default("deterministic"),
44
+ status: A().default("pending"),
45
+ source: A().nullable(),
46
+ requestId: A(),
47
+ workflowStart: O().nullable(),
48
+ input: O().nullable(),
49
+ output: O().nullable(),
50
+ steps: O().nullable(),
51
+ currentStep: D().default(0),
52
+ totalSteps: D().default(0),
53
+ humanResponse: O().nullable(),
54
+ chainPending: O().nullable(),
55
+ chainRefusal: A().nullable(),
56
+ costMicroUsd: D().default(0),
57
+ costCompleteness: A().default("unknown"),
58
+ durationMs: D().nullable(),
59
+ error: A().nullable(),
60
+ errorMessage: A().nullable(),
61
+ startedAt: Ge().nullable(),
62
+ completedAt: Ge().nullable(),
63
+ cancelledAt: Ge().nullable(),
64
+ sessionId: A().nullable(),
65
+ sessionName: A().nullable(),
66
+ ownerId: A().nullable(),
67
+ metadata: O().nullable()
68
+ }).renamedFrom("ai_flow_runs").with(Ke(), qe()).index(["flowRef"]).index(["status"]).index(["requestId"]), dt = [F, I], ft = T.Struct({
69
69
  id: T.NonEmptyString,
70
70
  workflowName: T.Literal(e),
71
71
  status: T.Literal("queued")
72
- }), ut = (t) => ({
72
+ }), pt = (t) => ({
73
73
  id: t,
74
74
  workflowName: e,
75
75
  executionId: t,
76
76
  status: "running"
77
- }), dt = (e) => {
77
+ }), mt = (e) => {
78
78
  let t = `flow start was not executed: ${e.reason}`;
79
79
  return e.incumbentExecutionId === null ? e.failureId === null ? t : `${t} (failure report ${e.failureId})` : `${t} (incumbent execution ${e.incumbentExecutionId})`;
80
- }, ft = async (e, t = {}) => {
80
+ }, ht = async (e, t = {}) => {
81
81
  let n = e.workflows;
82
82
  if (!n) throw Error("workflow runtime unavailable; flow starts cannot be reconciled");
83
83
  if (n.startsDeferredUntilCommit === !0) return {
@@ -88,8 +88,8 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
88
88
  failures: []
89
89
  };
90
90
  let r = t.take ?? 200, i = await e.store.query({
91
- table: L.tableName,
92
- predicate: D("status", "pending"),
91
+ table: I.tableName,
92
+ predicate: E("status", "pending"),
93
93
  order: [],
94
94
  take: r,
95
95
  skip: void 0,
@@ -104,7 +104,7 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
104
104
  for (let t of i) {
105
105
  let r = t.id;
106
106
  if (typeof r != "string") continue;
107
- let i = T.decodeUnknownOption(lt)(t.workflowStart);
107
+ let i = T.decodeUnknownOption(ft)(t.workflowStart);
108
108
  if (i._tag !== "None") {
109
109
  a.examined++;
110
110
  try {
@@ -118,14 +118,14 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
118
118
  }
119
119
  let o = (/* @__PURE__ */ new Date()).toISOString();
120
120
  if (t.kind === "accepted") {
121
- if (await e.store.update(L.tableName, r, { workflowStart: ut(t.executionId) }) === null) throw Error("flow run disappeared while recording its accepted start");
121
+ if (await e.store.update(I.tableName, r, { workflowStart: pt(t.executionId) }) === null) throw Error("flow run disappeared while recording its accepted start");
122
122
  a.accepted++;
123
123
  continue;
124
124
  }
125
- if (await e.store.update(L.tableName, r, {
125
+ if (await e.store.update(I.tableName, r, {
126
126
  status: "failed",
127
127
  error: "FlowStartNotExecuted",
128
- errorMessage: dt(t),
128
+ errorMessage: mt(t),
129
129
  completedAt: o
130
130
  }) === null) throw Error("flow run disappeared while recording that its start will not execute");
131
131
  a.notExecuted++;
@@ -138,32 +138,32 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
138
138
  }
139
139
  }
140
140
  return a;
141
- }, pt = 168, mt = "VOLTRO_AI_FLOW_HUMAN_REVIEW_TIMEOUT_HOURS", ht = 2160, gt = "VOLTRO_AI_FLOW_RUNS_TTL_HOURS", _t = 5, vt = "VOLTRO_AI_FLOW_MAX_CHAIN_DEPTH", yt = { current: {} }, bt = (e) => {
142
- yt.current = e;
143
- }, xt = () => yt.current, St = () => {
144
- yt.current = {};
145
- }, Ct = (e, t) => {
141
+ }, gt = 168, _t = "VOLTRO_AI_FLOW_HUMAN_REVIEW_TIMEOUT_HOURS", vt = 2160, yt = "VOLTRO_AI_FLOW_RUNS_TTL_HOURS", bt = 5, xt = "VOLTRO_AI_FLOW_MAX_CHAIN_DEPTH", St = { current: {} }, Ct = (e) => {
142
+ St.current = e;
143
+ }, wt = () => St.current, Tt = () => {
144
+ St.current = {};
145
+ }, Et = (e, t) => {
146
146
  if (e === void 0 || e.trim() === "") return t * 36e5;
147
147
  let n = Number(e);
148
148
  return !Number.isFinite(n) || n < 0 ? t * 36e5 : n * 36e5;
149
- }, wt = (e) => Number.isFinite(e) && e > 0 ? e : Infinity, Tt = (e) => {
149
+ }, Dt = (e) => Number.isFinite(e) && e > 0 ? e : Infinity, Ot = (e) => {
150
150
  let t = e.env ?? process.env;
151
- return wt(e.step?.timeoutMs ?? e.flow?.humanTimeoutMs ?? e.deps?.humanReviewTimeoutMs ?? xt().humanReviewTimeoutMs ?? Ct(t.VOLTRO_AI_FLOW_HUMAN_REVIEW_TIMEOUT_HOURS, 168));
152
- }, Et = (e) => {
153
- let t = e?.env ?? process.env, n = Number(t[vt]), r = e?.maxChainDepth ?? xt().maxChainDepth ?? (Number.isFinite(n) && n >= 1 ? n : 5);
151
+ return Dt(e.step?.timeoutMs ?? e.flow?.humanTimeoutMs ?? e.deps?.humanReviewTimeoutMs ?? wt().humanReviewTimeoutMs ?? Et(t.VOLTRO_AI_FLOW_HUMAN_REVIEW_TIMEOUT_HOURS, 168));
152
+ }, kt = (e) => {
153
+ let t = e?.env ?? process.env, n = Number(t[xt]), r = e?.maxChainDepth ?? wt().maxChainDepth ?? (Number.isFinite(n) && n >= 1 ? n : 5);
154
154
  return Number.isFinite(r) && r >= 1 ? r : 5;
155
- }, Dt = /\{\{\s*([\w.-]+)\s*\}\}/g, Ot = (e) => {
155
+ }, At = /\{\{\s*([\w.-]+)\s*\}\}/g, jt = (e) => {
156
156
  let t = [];
157
- for (let n of e.matchAll(Dt)) t.push(n[1]);
157
+ for (let n of e.matchAll(At)) t.push(n[1]);
158
158
  return t;
159
- }, kt = (e, t) => e.replace(Dt, (e, n) => {
159
+ }, Mt = (e, t) => e.replace(At, (e, n) => {
160
160
  let r = t[n];
161
161
  return r == null ? "" : typeof r == "string" ? r : JSON.stringify(r);
162
- }), At = (e, t) => {
162
+ }), Nt = (e, t) => {
163
163
  let n = /* @__PURE__ */ new Set();
164
- for (let r of Ot(e)) t[r] == null && !n.has(r) && n.add(r);
164
+ for (let r of jt(e)) t[r] == null && !n.has(r) && n.add(r);
165
165
  return [...n];
166
- }, jt = (e) => {
166
+ }, Pt = (e) => {
167
167
  let t = [], n;
168
168
  if (e.forEach((e, r) => {
169
169
  let i = e.group;
@@ -192,34 +192,34 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
192
192
  });
193
193
  }
194
194
  return t;
195
- }, Mt = (e) => {
195
+ }, Ft = (e) => {
196
196
  let t = /* @__PURE__ */ new Map();
197
197
  for (let n of e) n.group !== void 0 && t.set(n.group, (t.get(n.group) ?? 0) + 1);
198
198
  return [...t.entries()].filter(([, e]) => e > 1).map(([e]) => e).sort();
199
- }, Nt = T.suspend(() => T.Union(T.Null, T.Boolean, T.Finite, T.String, T.Array(Nt).pipe(T.mutable), T.Record({
199
+ }, L = T.suspend(() => T.Union(T.Null, T.Boolean, T.Finite, T.String, T.Array(L).pipe(T.mutable), T.Record({
200
200
  key: T.String,
201
- value: Nt
201
+ value: L
202
202
  }))), R = T.Record({
203
203
  key: T.String,
204
204
  value: T.Record({
205
205
  key: T.String,
206
- value: Nt
206
+ value: L
207
207
  })
208
- }), Pt = T.Struct({
208
+ }), It = T.Struct({
209
209
  maxTokens: T.optionalWith(T.Int.pipe(T.positive(), T.lessThanOrEqualTo(2 ** 53 - 1)), { exact: !0 }),
210
210
  temperature: T.optionalWith(T.Finite.pipe(T.nonNegative()), { exact: !0 }),
211
211
  providerOptions: T.optionalWith(R, { exact: !0 })
212
- }), Ft = [
212
+ }), Lt = [
213
213
  "maxTokens",
214
214
  "temperature",
215
215
  "providerOptions"
216
- ], It = (e) => {
216
+ ], Rt = (e) => {
217
217
  if (typeof e != "object" || !e || Array.isArray(e)) return "params must be an object";
218
- let t = Object.keys(e), n = t.filter((e) => !Ft.includes(e)).sort(), r = t.filter((t) => Ft.includes(t) && T.decodeUnknownOption(Pt)({ [t]: e[t] })._tag === "None").sort();
218
+ let t = Object.keys(e), n = t.filter((e) => !Lt.includes(e)).sort(), r = t.filter((t) => Lt.includes(t) && T.decodeUnknownOption(It)({ [t]: e[t] })._tag === "None").sort();
219
219
  return [...n.length > 0 ? [`unsupported field${n.length === 1 ? "" : "s"}: ${n.join(", ")}`] : [], ...r.length > 0 ? [`invalid value for: ${r.join(", ")}`] : []].join("; ");
220
- }, Lt = (e) => w.try({
221
- try: () => T.decodeUnknownSync(Pt, { onExcessProperty: "error" })(e === void 0 ? {} : e),
222
- catch: () => `invalid text params (${It(e)}): expected maxTokens (positive safe integer), temperature (finite nonnegative number), and/or providerOptions (provider-keyed JSON object); other fields are not supported`
220
+ }, zt = (e) => w.try({
221
+ try: () => T.decodeUnknownSync(It, { onExcessProperty: "error" })(e === void 0 ? {} : e),
222
+ catch: () => `invalid text params (${Rt(e)}): expected maxTokens (positive safe integer), temperature (finite nonnegative number), and/or providerOptions (provider-keyed JSON object); other fields are not supported`
223
223
  }), z = T.String.pipe(T.filter((e) => {
224
224
  try {
225
225
  let t = new URL(e);
@@ -227,25 +227,25 @@ var F = /* @__PURE__ */ new Map(), it = (e) => {
227
227
  } catch {
228
228
  return !1;
229
229
  }
230
- })), Rt = T.Record({
230
+ })), B = T.Record({
231
231
  key: T.String,
232
232
  value: z
233
- }), zt = (e, t, n = {}) => w.try({
233
+ }), Bt = (e, t, n = {}) => w.try({
234
234
  try: () => {
235
- let r = T.decodeUnknownSync(te, { onExcessProperty: "error" })(e === void 0 ? {} : e), i = Object.fromEntries(Object.entries(r).map(([e, r]) => [e, r.from === "upload" ? r.url : r.artifact === void 0 ? Object.hasOwn(t, r.ref) ? t[r.ref] : void 0 : Object.hasOwn(n, r.ref) ? n[r.ref]?.[r.artifact]?.url : void 0]));
236
- return T.decodeUnknownSync(Rt)(i);
235
+ let r = T.decodeUnknownSync(g, { onExcessProperty: "error" })(e === void 0 ? {} : e), i = Object.fromEntries(Object.entries(r).map(([e, r]) => [e, r.from === "upload" ? r.url : r.artifact === void 0 ? Object.hasOwn(t, r.ref) ? t[r.ref] : void 0 : Object.hasOwn(n, r.ref) ? n[r.ref]?.[r.artifact]?.url : void 0]));
236
+ return T.decodeUnknownSync(B)(i);
237
237
  },
238
238
  catch: () => "invalid or unresolved media input: each slot must resolve to an absolute HTTP(S) URL without embedded credentials"
239
- }), Bt = T.Struct({
239
+ }), Vt = T.Struct({
240
240
  url: z,
241
241
  mediaType: T.NonEmptyString
242
242
  });
243
243
  T.Record({
244
244
  key: T.String,
245
- value: Bt
245
+ value: Vt
246
246
  });
247
- var Vt = (e, t = {}) => {
248
- let n = T.decodeUnknownOption(te)(e === void 0 ? {} : e);
247
+ var Ht = (e, t = {}) => {
248
+ let n = T.decodeUnknownOption(g)(e === void 0 ? {} : e);
249
249
  if (n._tag === "None") return {};
250
250
  let r = {};
251
251
  for (let [e, i] of Object.entries(n.value)) {
@@ -264,9 +264,9 @@ var Vt = (e, t = {}) => {
264
264
  });
265
265
  }
266
266
  return r;
267
- }, Ht = (e, t) => w.try({
267
+ }, Ut = (e, t) => w.try({
268
268
  try: () => {
269
- let n = T.decodeUnknownSync(Rt)(t === void 0 ? {} : t), r = e === "image" ? ["referenceImageUrl", "maskImageUrl"] : e === "video" ? [
269
+ let n = T.decodeUnknownSync(B)(t === void 0 ? {} : t), r = e === "image" ? ["referenceImageUrl", "maskImageUrl"] : e === "video" ? [
270
270
  "referenceImageUrl",
271
271
  "firstFrameImageUrl",
272
272
  "lastFrameImageUrl",
@@ -277,26 +277,26 @@ var Vt = (e, t = {}) => {
277
277
  return n;
278
278
  },
279
279
  catch: () => `invalid or unsupported media input for ${e}; check the built-in adapter's slot contract`
280
- }), Ut = T.Struct({
281
- artifacts: v,
280
+ }), Wt = T.Struct({
281
+ artifacts: re,
282
282
  costMicroUsd: T.optional(T.Finite.pipe(T.nonNegative())),
283
283
  costSource: T.optional(b),
284
284
  requestId: T.optional(T.NonEmptyString),
285
285
  usage: T.optional(m)
286
- }), Wt = (e) => w.try({
287
- try: () => T.decodeUnknownSync(Ut, { onExcessProperty: "error" })(e),
286
+ }), Gt = (e) => w.try({
287
+ try: () => T.decodeUnknownSync(Wt, { onExcessProperty: "error" })(e),
288
288
  catch: () => "invalid media result: expected artifacts with URL, mediaType and role, exactly one primary artifact, and optional storage references"
289
- }), B = (e) => e, Gt = (e) => e._tag === "FlowAgentUnavailable" ? e.publicMessage ?? "agent unavailable" : "agent not found", Kt = T.Struct({
289
+ }), V = (e) => e, Kt = (e) => e._tag === "FlowAgentUnavailable" ? e.publicMessage ?? "agent unavailable" : "agent not found", qt = T.Struct({
290
290
  value: T.optional(T.Unknown),
291
291
  text: T.optional(T.String),
292
292
  url: T.optional(T.String),
293
- artifacts: T.optional(v),
293
+ artifacts: T.optional(re),
294
294
  costMicroUsd: T.optional(T.Number),
295
295
  costSource: T.optional(b),
296
296
  requestId: T.optional(T.String),
297
297
  usage: T.optional(m),
298
298
  error: T.optional(T.String)
299
- }), qt = (e) => Wt(e).pipe(w.map((e) => {
299
+ }), Jt = (e) => Gt(e).pipe(w.map((e) => {
300
300
  let t = e.artifacts.find((e) => e.role === "primary");
301
301
  return {
302
302
  value: t.url,
@@ -307,55 +307,55 @@ var Vt = (e, t = {}) => {
307
307
  ...e.costSource === void 0 ? {} : { costSource: e.costSource },
308
308
  ...e.usage === void 0 ? {} : { usage: e.usage }
309
309
  };
310
- }), w.catchAll((e) => w.succeed({ error: e }))), V = (e) => ({
310
+ }), w.catchAll((e) => w.succeed({ error: e }))), H = (e) => ({
311
311
  ...e.requestId ? { requestId: e.requestId } : {},
312
312
  ...e.costMicroUsd ? { costMicroUsd: e.costMicroUsd } : {},
313
313
  ...e.costSource === void 0 ? {} : { costSource: e.costSource },
314
314
  ...e.usage === void 0 ? {} : { usage: e.usage }
315
- }), H = () => (/* @__PURE__ */ new Date()).toISOString(), Jt = (e) => Math.round(e * 1e6), Yt = (e) => ({
315
+ }), U = () => (/* @__PURE__ */ new Date()).toISOString(), Yt = (e) => Math.round(e * 1e6), Xt = (e) => ({
316
316
  name: "gateway",
317
317
  model: e
318
- }), U = (e, t) => e.resolveModel?.(t) ?? Yt(t), Xt = (e, t, n, r) => w.gen(function* () {
318
+ }), W = (e, t) => e.resolveModel?.(t) ?? Xt(t), Zt = (e, t, n, r) => w.gen(function* () {
319
319
  return t.maxSteps !== void 0 && (!Number.isSafeInteger(t.maxSteps) || t.maxSteps < 1) ? yield* w.fail(new S({
320
320
  capability: "resolveAgent",
321
321
  message: "agent maxSteps must be a positive safe integer"
322
- })) : yield* et({
322
+ })) : yield* it({
323
323
  ...r,
324
324
  system: t.system,
325
325
  prompt: n,
326
- provider: U(e, t.model),
326
+ provider: W(e, t.model),
327
327
  ...t.tools === void 0 ? {} : { tools: t.tools },
328
328
  ...t.maxSteps === void 0 ? {} : { maxSteps: t.maxSteps }
329
329
  });
330
- }), Zt = (e, t, n) => W(e, t, n).costMicroUsd, W = (e, t, n) => {
331
- let r = Je(t);
330
+ }), Qt = (e, t, n) => G(e, t, n).costMicroUsd, G = (e, t, n) => {
331
+ let r = Qe(t);
332
332
  if (typeof r == "number") return {
333
- costMicroUsd: Jt(r),
333
+ costMicroUsd: Yt(r),
334
334
  costSource: "gateway"
335
335
  };
336
- let i = qe(e, { model: n ?? "unknown" });
336
+ let i = Ze(e, { model: n ?? "unknown" });
337
337
  return {
338
338
  costMicroUsd: i.costMicroUsd ?? 0,
339
339
  costSource: i.costSource ?? "unpriced"
340
340
  };
341
- }, G = (e) => {
341
+ }, K = (e) => {
342
342
  let t = e.filter((e) => (e.status === "succeeded" || e.status === "failed") && (e.costSource !== void 0 || e.costMicroUsd !== void 0));
343
343
  if (t.length === 0) return "unknown";
344
344
  let n = t.map((e) => e.costSource ?? "unpriced");
345
345
  return n.every((e) => e === "gateway") ? "actual" : n.some((e) => e === "unpriced") ? "incomplete" : "estimated";
346
- }, K = (e, t, n) => w.promise(() => e.store.update(L.tableName, t, n).then(() => void 0)).pipe(w.catchAllCause(() => w.void)), Qt = (e, t, n, r) => w.promise(async () => {
347
- let i = await e.store.query(A(L).where(D("id", t)).descriptor), a = i[0]?.[r];
348
- i[0] !== void 0 && a == null && await e.store.update(L.tableName, t, n);
349
- }).pipe(w.catchAllCause(() => w.void)), $t = (e, t) => w.promise(async () => {
350
- let n = (await e.store.query(A(L).where(D("id", t)).descriptor))[0]?.status;
346
+ }, q = (e, t, n) => w.promise(() => e.store.update(I.tableName, t, n).then(() => void 0)).pipe(w.catchAllCause(() => w.void)), $t = (e, t, n, r) => w.promise(async () => {
347
+ let i = await e.store.query(k(I).where(E("id", t)).descriptor), a = i[0]?.[r];
348
+ i[0] !== void 0 && a == null && await e.store.update(I.tableName, t, n);
349
+ }).pipe(w.catchAllCause(() => w.void)), en = (e, t) => w.promise(async () => {
350
+ let n = (await e.store.query(k(I).where(E("id", t)).descriptor))[0]?.status;
351
351
  return n === "cancelling" || n === "cancelled";
352
- }).pipe(w.catchAllCause(() => w.succeed(!1))), en = (e, t) => w.promise(() => e.store.updateMany(L.tableName, {
352
+ }).pipe(w.catchAllCause(() => w.succeed(!1))), tn = (e, t) => w.promise(() => e.store.updateMany(I.tableName, {
353
353
  status: "cancelled",
354
- completedAt: H()
355
- }, { where: E(D("id", t), D("status", "cancelling")) }).then(() => void 0)).pipe(w.catchAllCause(() => w.void)), tn = (e, t) => w.gen(function* () {
356
- let n = at(t);
354
+ completedAt: U()
355
+ }, { where: Re(E("id", t), E("status", "cancelling")) }).then(() => void 0)).pipe(w.catchAllCause(() => w.void)), J = (e, t) => w.gen(function* () {
356
+ let n = lt(t);
357
357
  if (n) return n;
358
- let r = (yield* w.promise(() => e.store.query(A(I).where(D("id", t)).descriptor)))[0];
358
+ let r = (yield* w.promise(() => e.store.query(k(F).where(E("id", t)).descriptor)))[0];
359
359
  return r ? d({
360
360
  name: r.name ?? t,
361
361
  mode: r.mode,
@@ -372,10 +372,10 @@ var Vt = (e, t = {}) => {
372
372
  message: `no flow registered or stored for "${t}"`
373
373
  }));
374
374
  }), nn = (e, t, n, r, i, a) => w.gen(function* () {
375
- let e = kt(n.prompt ?? "", r), o = yield* Lt(n.type === "agent" || n.type === "structured" || n.type === "generate" && (n.modality ?? "text") === "text" ? n.params : void 0).pipe(w.either);
375
+ let e = Mt(n.prompt ?? "", r), o = yield* zt(n.type === "agent" || n.type === "structured" || n.type === "generate" && (n.modality ?? "text") === "text" ? n.params : void 0).pipe(w.either);
376
376
  if (o._tag === "Left") return { error: `step "${n.id}": ${o.left}` };
377
377
  if (n.mediaInputs !== void 0 && (n.type !== "generate" || (n.modality ?? "text") === "text")) return { error: `step "${n.id}": media inputs require an image, video or audio generation step` };
378
- let s = At(n.prompt ?? "", r);
378
+ let s = Nt(n.prompt ?? "", r);
379
379
  if (s.length > 0) return { error: new Te({
380
380
  stepId: n.id,
381
381
  unresolvedRef: s[0],
@@ -394,7 +394,7 @@ var Vt = (e, t = {}) => {
394
394
  capability: "resolveAgent",
395
395
  message: "no agent resolver configured"
396
396
  }).message };
397
- let r = yield* B(t.resolveAgent(n.agentRef, i)).pipe(w.map((e) => ({
397
+ let r = yield* V(t.resolveAgent(n.agentRef, i)).pipe(w.map((e) => ({
398
398
  ok: !0,
399
399
  a: e
400
400
  })), w.catchAll((e) => w.succeed({
@@ -402,7 +402,7 @@ var Vt = (e, t = {}) => {
402
402
  e
403
403
  })));
404
404
  if (!r.ok) return { error: r.e.message };
405
- let a = yield* Xt(t, r.a, e, o.right).pipe(w.map((e) => ({
405
+ let a = yield* Zt(t, r.a, e, o.right).pipe(w.map((e) => ({
406
406
  ok: !0,
407
407
  r: e
408
408
  })), w.catchAll((e) => w.succeed({
@@ -412,16 +412,16 @@ var Vt = (e, t = {}) => {
412
412
  return a.ok ? {
413
413
  value: a.r.text,
414
414
  text: a.r.text,
415
- ...W(a.r.usage, a.r.providerMetadata, r.a.model)
415
+ ...G(a.r.usage, a.r.providerMetadata, r.a.model)
416
416
  } : { error: String(a.e.message ?? a.e) };
417
417
  }
418
418
  case "structured": {
419
419
  if (n.schema === void 0) return { error: `step "${n.id}": structured step requires a JSON Schema` };
420
- let r = n.model ?? t.defaultModels?.text, i = yield* Ze({
420
+ let r = n.model ?? t.defaultModels?.text, i = yield* tt({
421
421
  ...o.right,
422
422
  prompt: e,
423
423
  jsonSchema: n.schema,
424
- ...r ? { provider: U(t, r) } : {}
424
+ ...r ? { provider: W(t, r) } : {}
425
425
  }).pipe(w.map((e) => ({
426
426
  ok: !0,
427
427
  r: e
@@ -432,16 +432,16 @@ var Vt = (e, t = {}) => {
432
432
  return i.ok ? {
433
433
  value: i.r.object,
434
434
  text: JSON.stringify(i.r.object, null, 2),
435
- ...W(i.r.usage, i.r.providerMetadata, r)
435
+ ...G(i.r.usage, i.r.providerMetadata, r)
436
436
  } : { error: String(i.e.message ?? i.e) };
437
437
  }
438
438
  case "generate": {
439
439
  let s = n.modality ?? "text";
440
440
  if (s === "text") {
441
- let r = n.model ?? t.defaultModels?.text, i = yield* et({
441
+ let r = n.model ?? t.defaultModels?.text, i = yield* it({
442
442
  ...o.right,
443
443
  prompt: e,
444
- ...r ? { provider: U(t, r) } : {}
444
+ ...r ? { provider: W(t, r) } : {}
445
445
  }).pipe(w.map((e) => ({
446
446
  ok: !0,
447
447
  r: e
@@ -452,16 +452,16 @@ var Vt = (e, t = {}) => {
452
452
  return i.ok ? {
453
453
  value: i.r.text,
454
454
  text: i.r.text,
455
- ...W(i.r.usage, i.r.providerMetadata, r)
455
+ ...G(i.r.usage, i.r.providerMetadata, r)
456
456
  } : { error: String(i.e.message ?? i.e) };
457
457
  }
458
458
  if (!t.generateMedia) return { error: new S({
459
459
  capability: `media:${s}`,
460
460
  message: `no media generator configured for ${s}`
461
461
  }).message };
462
- let c = yield* zt(n.mediaInputs, r, a).pipe(w.either);
462
+ let c = yield* Bt(n.mediaInputs, r, a).pipe(w.either);
463
463
  if (c._tag === "Left") return { error: `step "${n.id}": ${c.left}` };
464
- let l = Vt(n.mediaInputs, a), u = n.model ?? t.defaultModels?.[s], d = yield* B(t.generateMedia({
464
+ let l = Ht(n.mediaInputs, a), u = n.model ?? t.defaultModels?.[s], d = yield* V(t.generateMedia({
465
465
  modality: s,
466
466
  ...u ? { model: u } : {},
467
467
  prompt: e,
@@ -483,7 +483,7 @@ var Vt = (e, t = {}) => {
483
483
  ...e === void 0 ? {} : e
484
484
  };
485
485
  }
486
- return yield* qt(d.m);
486
+ return yield* Jt(d.m);
487
487
  }
488
488
  case "human": return { error: new S({
489
489
  capability: "human",
@@ -499,26 +499,26 @@ var Vt = (e, t = {}) => {
499
499
  status: "pending",
500
500
  ...e.description ? { description: e.description } : {}
501
501
  })), d = 0;
502
- yield* Qt(e, n, {
502
+ yield* $t(e, n, {
503
503
  status: "running",
504
504
  steps: u,
505
505
  totalSteps: i.steps.length,
506
506
  currentStep: 0,
507
- startedAt: H()
507
+ startedAt: U()
508
508
  }, "startedAt");
509
- for (let o of jt(i.steps)) {
510
- if (yield* $t(e, n)) return yield* en(e, n), {
509
+ for (let o of Pt(i.steps)) {
510
+ if (yield* en(e, n)) return yield* tn(e, n), {
511
511
  runId: n,
512
512
  status: "cancelled"
513
513
  };
514
514
  if (o.steps.length > 1) {
515
515
  let r = [];
516
516
  for (let { index: e, step: t } of o.steps) {
517
- if (t.when !== void 0 && !_(t.when, c)) {
517
+ if (t.when !== void 0 && !v(t.when, c)) {
518
518
  u[e] = {
519
519
  ...u[e],
520
520
  status: "skipped",
521
- completedAt: H(),
521
+ completedAt: U(),
522
522
  skipReason: a(t.when)
523
523
  };
524
524
  continue;
@@ -529,17 +529,17 @@ var Vt = (e, t = {}) => {
529
529
  }), u[e] = {
530
530
  ...u[e],
531
531
  status: "running",
532
- startedAt: H()
532
+ startedAt: U()
533
533
  };
534
534
  }
535
- yield* K(e, n, {
535
+ yield* q(e, n, {
536
536
  steps: u,
537
537
  currentStep: o.steps[0].index
538
538
  });
539
- let i = yield* w.all(r.map(({ index: r, step: i }) => N({
539
+ let i = yield* w.all(r.map(({ index: r, step: i }) => j({
540
540
  name: `flow-${r}-${i.id}`,
541
541
  input: { index: r },
542
- success: Kt,
542
+ success: qt,
543
543
  execute: nn(e, t, i, c, {
544
544
  runId: n,
545
545
  tenantId: s.tenantId,
@@ -555,49 +555,49 @@ var Vt = (e, t = {}) => {
555
555
  d += n.costMicroUsd ?? 0, u[e] = {
556
556
  ...u[e],
557
557
  status: "failed",
558
- completedAt: H(),
558
+ completedAt: U(),
559
559
  errorMessage: n.error,
560
- ...V(n)
560
+ ...H(n)
561
561
  };
562
562
  continue;
563
563
  }
564
564
  t.outputKey && n.value !== void 0 && (c[t.outputKey] = n.value), t.outputKey && n.artifacts !== void 0 && (l[t.outputKey] = n.artifacts), d += n.costMicroUsd ?? 0, u[e] = {
565
565
  ...u[e],
566
566
  status: "succeeded",
567
- completedAt: H(),
567
+ completedAt: U(),
568
568
  ...n.text ? { output: { text: n.text } } : {},
569
569
  ...n.url ? { url: n.url } : {},
570
570
  ...n.artifacts === void 0 ? {} : { artifacts: n.artifacts },
571
- ...V(n)
571
+ ...H(n)
572
572
  };
573
573
  }
574
- if (f !== void 0) return yield* K(e, n, {
574
+ if (f !== void 0) return yield* q(e, n, {
575
575
  steps: u,
576
576
  status: "failed",
577
577
  errorMessage: f.result.error,
578
- completedAt: H(),
578
+ completedAt: U(),
579
579
  costMicroUsd: d,
580
- costCompleteness: G(u)
580
+ costCompleteness: K(u)
581
581
  }), {
582
582
  runId: n,
583
583
  status: "failed"
584
584
  };
585
- yield* K(e, n, {
585
+ yield* q(e, n, {
586
586
  steps: u,
587
587
  currentStep: o.steps[o.steps.length - 1].index + 1,
588
588
  costMicroUsd: d,
589
- costCompleteness: G(u)
589
+ costCompleteness: K(u)
590
590
  });
591
591
  continue;
592
592
  }
593
593
  let { index: f, step: p } = o.steps[0];
594
- if (p.when !== void 0 && !_(p.when, c)) {
594
+ if (p.when !== void 0 && !v(p.when, c)) {
595
595
  u[f] = {
596
596
  ...u[f],
597
597
  status: "skipped",
598
- completedAt: H(),
598
+ completedAt: U(),
599
599
  skipReason: a(p.when)
600
- }, yield* K(e, n, {
600
+ }, yield* q(e, n, {
601
601
  steps: u,
602
602
  currentStep: f + 1
603
603
  });
@@ -607,29 +607,29 @@ var Vt = (e, t = {}) => {
607
607
  let a = {
608
608
  mode: p.reviewMode ?? "approve",
609
609
  ...p.options ? { options: p.options } : {},
610
- prompt: kt(p.prompt ?? "", c)
610
+ prompt: Mt(p.prompt ?? "", c)
611
611
  };
612
612
  u[f] = {
613
613
  ...u[f],
614
614
  status: "waiting",
615
- startedAt: H(),
615
+ startedAt: U(),
616
616
  review: a
617
- }, yield* K(e, n, {
617
+ }, yield* q(e, n, {
618
618
  steps: u,
619
619
  status: "waiting",
620
620
  currentStep: f
621
- }), t.onEvent && (yield* B(t.onEvent({
621
+ }), t.onEvent && (yield* V(t.onEvent({
622
622
  kind: "review-needed",
623
623
  runId: n,
624
624
  flowName: i.name,
625
625
  ownerId: s.ownerId,
626
626
  source: s.source
627
627
  })).pipe(w.catchAllCause(() => w.void)));
628
- let o = Tt({
628
+ let o = Ot({
629
629
  step: p,
630
630
  flow: i,
631
631
  deps: t
632
- }), l = yield* Ke(e, {
632
+ }), l = yield* Xe(e, {
633
633
  name: r(f),
634
634
  schema: fe,
635
635
  timeoutMs: o
@@ -645,15 +645,15 @@ var Vt = (e, t = {}) => {
645
645
  return u[f] = {
646
646
  ...u[f],
647
647
  status: "failed",
648
- completedAt: H(),
648
+ completedAt: U(),
649
649
  errorMessage: t
650
- }, yield* K(e, n, {
650
+ }, yield* q(e, n, {
651
651
  steps: u,
652
652
  status: "failed",
653
653
  errorMessage: t,
654
- completedAt: H(),
654
+ completedAt: U(),
655
655
  costMicroUsd: d,
656
- costCompleteness: G(u)
656
+ costCompleteness: K(u)
657
657
  }), {
658
658
  runId: n,
659
659
  status: "failed"
@@ -663,15 +663,15 @@ var Vt = (e, t = {}) => {
663
663
  if (m.decision === "reject") return u[f] = {
664
664
  ...u[f],
665
665
  status: "failed",
666
- completedAt: H(),
666
+ completedAt: U(),
667
667
  errorMessage: "rejected by reviewer"
668
- }, yield* K(e, n, {
668
+ }, yield* q(e, n, {
669
669
  steps: u,
670
670
  status: "cancelled",
671
671
  humanResponse: m,
672
- completedAt: H(),
672
+ completedAt: U(),
673
673
  costMicroUsd: d,
674
- costCompleteness: G(u)
674
+ costCompleteness: K(u)
675
675
  }), {
676
676
  runId: n,
677
677
  status: "cancelled"
@@ -679,9 +679,9 @@ var Vt = (e, t = {}) => {
679
679
  p.outputKey && (c[p.outputKey] = m.value ?? m.text ?? m.decision ?? !0), u[f] = {
680
680
  ...u[f],
681
681
  status: "succeeded",
682
- completedAt: H(),
682
+ completedAt: U(),
683
683
  output: { text: String(m.text ?? m.value ?? m.decision ?? "approved") }
684
- }, yield* K(e, n, {
684
+ }, yield* q(e, n, {
685
685
  steps: u,
686
686
  status: "running",
687
687
  humanResponse: m,
@@ -692,15 +692,15 @@ var Vt = (e, t = {}) => {
692
692
  u[f] = {
693
693
  ...u[f],
694
694
  status: "running",
695
- startedAt: H()
696
- }, yield* K(e, n, {
695
+ startedAt: U()
696
+ }, yield* q(e, n, {
697
697
  steps: u,
698
698
  currentStep: f
699
699
  });
700
- let m = yield* N({
700
+ let m = yield* j({
701
701
  name: `flow-${f}-${p.id}`,
702
702
  input: { index: f },
703
- success: Kt,
703
+ success: qt,
704
704
  execute: nn(e, t, p, c, {
705
705
  runId: n,
706
706
  tenantId: s.tenantId,
@@ -710,16 +710,16 @@ var Vt = (e, t = {}) => {
710
710
  if (m.error) return d += m.costMicroUsd ?? 0, u[f] = {
711
711
  ...u[f],
712
712
  status: "failed",
713
- completedAt: H(),
713
+ completedAt: U(),
714
714
  errorMessage: m.error,
715
- ...V(m)
716
- }, yield* K(e, n, {
715
+ ...H(m)
716
+ }, yield* q(e, n, {
717
717
  steps: u,
718
718
  status: "failed",
719
719
  errorMessage: m.error,
720
- completedAt: H(),
720
+ completedAt: U(),
721
721
  costMicroUsd: d,
722
- costCompleteness: G(u)
722
+ costCompleteness: K(u)
723
723
  }), {
724
724
  runId: n,
725
725
  status: "failed"
@@ -727,24 +727,24 @@ var Vt = (e, t = {}) => {
727
727
  p.outputKey && m.value !== void 0 && (c[p.outputKey] = m.value), p.outputKey && m.artifacts !== void 0 && (l[p.outputKey] = m.artifacts), d += m.costMicroUsd ?? 0, u[f] = {
728
728
  ...u[f],
729
729
  status: "succeeded",
730
- completedAt: H(),
730
+ completedAt: U(),
731
731
  ...m.text ? { output: { text: m.text } } : {},
732
732
  ...m.url ? { url: m.url } : {},
733
733
  ...m.artifacts === void 0 ? {} : { artifacts: m.artifacts },
734
- ...V(m)
735
- }, yield* K(e, n, {
734
+ ...H(m)
735
+ }, yield* q(e, n, {
736
736
  steps: u,
737
737
  currentStep: f + 1,
738
738
  costMicroUsd: d,
739
- costCompleteness: G(u)
739
+ costCompleteness: K(u)
740
740
  });
741
741
  }
742
742
  let f = Object.create(null);
743
743
  for (let e of i.steps) e.outputKey && c[e.outputKey] !== void 0 && (f[e.outputKey] = c[e.outputKey]);
744
- return yield* K(e, n, {
744
+ return yield* q(e, n, {
745
745
  status: "succeeded",
746
746
  output: f,
747
- completedAt: H(),
747
+ completedAt: U(),
748
748
  costMicroUsd: d
749
749
  }), {
750
750
  runId: n,
@@ -757,12 +757,12 @@ var Vt = (e, t = {}) => {
757
757
  let c = [...a.chainPath ?? [], a.flowRef];
758
758
  if (s.flowRef === n.name || s.flowRef === a.flowRef) return;
759
759
  if (c.includes(s.flowRef)) {
760
- yield* K(e, t, { chainRefusal: `chain to "${s.flowRef}" refused — it is already in this run's chain (${c.join(" → ")}), which would loop` });
760
+ yield* q(e, t, { chainRefusal: `chain to "${s.flowRef}" refused — it is already in this run's chain (${c.join(" → ")}), which would loop` });
761
761
  return;
762
762
  }
763
- let l = Et(o);
763
+ let l = kt(o);
764
764
  if (c.length >= l) {
765
- yield* K(e, t, { chainRefusal: `chain to "${s.flowRef}" refused — depth ${c.length} reached the limit of ${l} (${c.join(" → ")})` });
765
+ yield* q(e, t, { chainRefusal: `chain to "${s.flowRef}" refused — depth ${c.length} reached the limit of ${l} (${c.join(" → ")})` });
766
766
  return;
767
767
  }
768
768
  let u = {
@@ -771,7 +771,7 @@ var Vt = (e, t = {}) => {
771
771
  }, d = {};
772
772
  for (let e of s.mappings) e.sourceKey in u && (d[e.targetKey] = u[e.sourceKey]);
773
773
  if (s.requireConfirmation) {
774
- yield* K(e, t, { chainPending: {
774
+ yield* q(e, t, { chainPending: {
775
775
  flowRef: s.flowRef,
776
776
  input: d,
777
777
  status: "pending"
@@ -783,7 +783,7 @@ var Vt = (e, t = {}) => {
783
783
  let p = `${t}--chain`, m = `${a.requestId}--chain`;
784
784
  yield* w.promise(async () => {
785
785
  try {
786
- await e.store.insert(L.tableName, {
786
+ await e.store.insert(I.tableName, {
787
787
  id: p,
788
788
  flowRef: s.flowRef,
789
789
  flowName: s.flowRef,
@@ -802,14 +802,26 @@ var Vt = (e, t = {}) => {
802
802
  chainPath: c
803
803
  });
804
804
  }).pipe(w.catchAllCause(() => w.void));
805
- }), on = (e) => e.steps.length === 0 ? "" : "Suggested plan (you MAY reorder, insert, or skip steps):\n" + e.steps.map((e, t) => `${t + 1}. [${e.type}${e.modality ? `/${e.modality}` : ""}] ${e.title ?? e.id}${e.prompt ? `: ${e.prompt}` : ""}`).join("\n"), sn = (e) => {
805
+ }), on = (e) => e.type === "agent" ? e.agentRef ? `agent step, agent "${e.agentRef}"` : "agent step" : e.type === "generate" ? `${e.modality ?? "media"} generation step` : `${e.type} step`, sn = (e) => e.steps.length === 0 ? "" : "Suggested plan (you MAY reorder, insert, or skip steps):\n" + e.steps.map((e, t) => `${t + 1}. ${e.title ?? e.id}${e.prompt ? `: ${e.prompt}` : ""} (${on(e)})`).join("\n"), cn = "an agentic flow runs its planner and every tool inside one durable step, which cannot park. Call the provider directly from the tool (generateImage, generateVideo, …), or give the work its own deterministic flow step", ln = T.optional(T.String.annotations({ description: "One short sentence: what this call is for. Shown to the user in the run timeline." })), un = (e) => e === void 0 || e.trim() === "" ? {} : { description: e.trim().slice(0, 200) }, dn = T.Struct({ json: T.String.annotations({ description: "The requested JSON object, serialized as a JSON string." }) }), fn = (e) => {
806
+ try {
807
+ let t = JSON.parse(e);
808
+ return typeof t == "object" && t && !Array.isArray(t) ? t : void 0;
809
+ } catch {
810
+ return;
811
+ }
812
+ }, pn = (e) => {
813
+ if (Ne.isSuccess(e)) return "the tool returned without recording a result";
814
+ if (Me.isInterruptedOnly(e.cause)) return "interrupted before it finished — nothing waited for its result";
815
+ let t = Me.squash(e.cause);
816
+ return t instanceof Error ? t.message : String(t);
817
+ }, mn = (e) => {
806
818
  let t = Object.entries(e);
807
819
  return t.length === 0 ? "Execute the flow." : "Brief for this run:\n" + t.map(([e, t]) => `- ${e}: ${typeof t == "string" ? t : JSON.stringify(t)}`).join("\n");
808
- }, cn = (e) => [
820
+ }, hn = (e) => [
809
821
  e.orchestrator?.instructions ?? "You are an orchestrator that uses the available tools to produce a bundled result.",
810
- on(e),
822
+ sn(e),
811
823
  "When finished, emit a JSON object mapping each deliverable name (outputKey) to its value."
812
- ].filter(Boolean).join("\n\n"), ln = T.Struct({
824
+ ].filter(Boolean).join("\n\n"), gn = T.Struct({
813
825
  object: T.Record({
814
826
  key: T.String,
815
827
  value: T.Unknown
@@ -819,53 +831,65 @@ var Vt = (e, t = {}) => {
819
831
  toolCostMicroUsd: T.Number,
820
832
  steps: T.Array(i),
821
833
  error: T.optional(T.String)
822
- }), un = (e, t, n, r, i, a, o, s) => w.gen(function* () {
823
- yield* Qt(e, n, {
834
+ }), _n = (e, t, n, r, i, a, o, s) => w.gen(function* () {
835
+ yield* $t(e, n, {
824
836
  status: "running",
825
- startedAt: H(),
837
+ startedAt: U(),
826
838
  totalSteps: r.steps.length
827
839
  }, "startedAt");
828
- let c = yield* N({
840
+ let c = yield* j({
829
841
  name: "flow-agentic",
830
842
  input: { flowRef: r.name },
831
- success: ln,
843
+ success: gn,
832
844
  execute: w.gen(function* () {
833
845
  let c = [], l = 0, u = (e) => {
834
846
  let t = c.length;
835
847
  return c.push({
836
848
  id: t,
837
849
  status: "running",
838
- startedAt: H(),
850
+ startedAt: U(),
839
851
  ...e
840
852
  }), t;
841
853
  }, d = (e, t) => {
842
854
  c[e] = {
843
855
  ...c[e],
844
- completedAt: H(),
856
+ completedAt: U(),
845
857
  ...t
846
858
  };
847
- }, f = () => K(e, n, {
859
+ }, f = () => q(e, n, {
848
860
  steps: c,
849
861
  currentStep: c.length,
850
862
  costMicroUsd: l
851
- }), p = {
852
- run_agent: P({
863
+ }), p = (e, t) => w.suspend(() => {
864
+ let n = u(e);
865
+ return w.zipRight(f(), t(n)).pipe(w.onExit((e) => c[n]?.status === "running" ? (d(n, {
866
+ status: "failed",
867
+ errorMessage: pn(e)
868
+ }), w.ignore(f())) : w.void));
869
+ }), m = (t.listAgents ? yield* V(t.listAgents({
870
+ runId: n,
871
+ tenantId: o,
872
+ ownerId: a
873
+ })).pipe(w.catchAll((e) => w.logWarning(`flow agent listing failed for run ${n}: ${e.message}`).pipe(w.annotateLogs({ scope: "voltro:ai-flows" }), w.as(void 0)))) : void 0) ?? [...new Set(r.steps.flatMap((e) => e.type === "agent" && e.agentRef ? [e.agentRef] : []))].map((e) => ({ ref: e })), h = m.map((e) => e.ref), ee = h.length > 0 ? T.Literal(...h) : T.String, te = {
874
+ run_agent: M({
853
875
  name: "run_agent",
854
- description: "Delegate a text task to an allowed sub-agent. Returns the agent's text.",
876
+ description: "Delegate a text task to an allowed sub-agent. Returns the agent's text." + (m.length > 0 ? ` Agents you may call: ${m.map((e) => e.description ? `${e.ref} (${e.description})` : e.ref).join("; ")}.` : ""),
855
877
  input: T.Struct({
856
- agentRef: T.String,
857
- prompt: T.String
878
+ agentRef: ee,
879
+ prompt: T.String,
880
+ purpose: ln
858
881
  }),
859
- execute: ({ agentRef: e, prompt: r }) => w.gen(function* () {
860
- let i = u({
861
- title: `agent:${e}`,
862
- type: "agent"
863
- });
864
- if (yield* f(), !t.resolveAgent) return d(i, {
882
+ execute: ({ agentRef: e, prompt: r, purpose: i }) => p({
883
+ title: `agent:${e}`,
884
+ type: "agent",
885
+ agentRef: e,
886
+ ...un(i)
887
+ }, (i) => w.gen(function* () {
888
+ if (!t.resolveAgent) return d(i, {
865
889
  status: "failed",
866
890
  errorMessage: "no agent resolver configured"
867
891
  }), yield* f(), "ERROR: no agent resolver configured";
868
- let s = yield* B(t.resolveAgent(e, {
892
+ let s = yield* V(t.resolveAgent(e, {
869
893
  runId: n,
870
894
  tenantId: o,
871
895
  ownerId: a
@@ -879,8 +903,8 @@ var Vt = (e, t = {}) => {
879
903
  if (!s.ok) return d(i, {
880
904
  status: "failed",
881
905
  errorMessage: s.e.message
882
- }), yield* f(), `ERROR: ${Gt(s.e)}`;
883
- let c = yield* Xt(t, s.a, r, {}).pipe(w.map((e) => ({
906
+ }), yield* f(), `ERROR: ${Kt(s.e)}`;
907
+ let c = yield* Zt(t, s.a, r, {}).pipe(w.map((e) => ({
884
908
  ok: !0,
885
909
  r: e
886
910
  })), w.catchAll((e) => w.succeed({
@@ -894,42 +918,44 @@ var Vt = (e, t = {}) => {
894
918
  errorMessage: e
895
919
  }), yield* f(), `ERROR: ${e}`;
896
920
  }
897
- let p = Zt(c.r.usage, c.r.providerMetadata, s.a.model);
898
- return l += p, d(i, {
921
+ let u = Qt(c.r.usage, c.r.providerMetadata, s.a.model);
922
+ return l += u, d(i, {
899
923
  status: "succeeded",
900
924
  output: { text: c.r.text },
901
- costMicroUsd: p
925
+ costMicroUsd: u
902
926
  }), yield* f(), c.r.text;
903
- })
927
+ }))
904
928
  }),
905
- generate_media: P({
929
+ generate_media: M({
906
930
  name: "generate_media",
907
931
  description: "Generate image, video, or audio artifacts. Returns every artifact with its URL, role, media type and optional storage reference.",
908
932
  input: T.Struct({
909
933
  modality: T.Literal("image", "video", "audio"),
910
934
  prompt: T.String,
935
+ purpose: ln,
911
936
  model: T.optional(T.String),
912
- inputs: T.optional(Rt),
937
+ inputs: T.optional(B),
913
938
  params: T.optional(T.Record({
914
939
  key: T.String,
915
940
  value: T.Unknown
916
941
  }))
917
942
  }),
918
- execute: ({ modality: e, prompt: r, model: i, inputs: s, params: c }) => w.gen(function* () {
919
- let p = u({
920
- title: `media:${e}`,
921
- type: "generate"
922
- });
923
- if (yield* f(), !t.generateMedia) return d(p, {
943
+ execute: ({ modality: e, prompt: r, purpose: i, model: s, inputs: c, params: u }) => p({
944
+ title: `media:${e}`,
945
+ type: "generate",
946
+ modality: e,
947
+ ...un(i)
948
+ }, (i) => w.gen(function* () {
949
+ if (!t.generateMedia) return d(i, {
924
950
  status: "failed",
925
951
  errorMessage: `no media generator for ${e}`
926
952
  }), yield* f(), `ERROR: no media generator configured for ${e}`;
927
- let m = yield* B(t.generateMedia({
953
+ let p = yield* V(t.generateMedia({
928
954
  modality: e,
929
955
  prompt: r,
930
- ...i ? { model: i } : {},
931
- ...s === void 0 ? {} : { inputs: s },
932
- ...c === void 0 ? {} : { params: c },
956
+ ...s ? { model: s } : {},
957
+ ...c === void 0 ? {} : { inputs: c },
958
+ ...u === void 0 ? {} : { params: u },
933
959
  run: {
934
960
  runId: n,
935
961
  tenantId: o,
@@ -942,44 +968,41 @@ var Vt = (e, t = {}) => {
942
968
  ok: !1,
943
969
  e
944
970
  })));
945
- if (!m.ok) return d(p, {
971
+ if (!p.ok) return d(i, {
946
972
  status: "failed",
947
- errorMessage: m.e.message
948
- }), yield* f(), `ERROR: ${m.e.message}`;
949
- let h = yield* qt(m.r);
950
- return h.error ? (d(p, {
973
+ errorMessage: p.e.message
974
+ }), yield* f(), `ERROR: ${p.e.message}`;
975
+ let m = yield* Jt(p.r);
976
+ return m.error ? (d(i, {
951
977
  status: "failed",
952
- errorMessage: h.error
953
- }), yield* f(), { error: h.error }) : (l += h.costMicroUsd ?? 0, d(p, {
978
+ errorMessage: m.error
979
+ }), yield* f(), { error: m.error }) : (l += m.costMicroUsd ?? 0, d(i, {
954
980
  status: "succeeded",
955
- url: h.url,
956
- artifacts: h.artifacts,
957
- ...h.requestId ? { requestId: h.requestId } : {},
958
- costMicroUsd: h.costMicroUsd ?? 0,
959
- costSource: h.costSource ?? "unpriced"
960
- }), yield* f(), { artifacts: h.artifacts });
961
- })
981
+ url: m.url,
982
+ artifacts: m.artifacts,
983
+ ...m.requestId ? { requestId: m.requestId } : {},
984
+ costMicroUsd: m.costMicroUsd ?? 0,
985
+ costSource: m.costSource ?? "unpriced"
986
+ }), yield* f(), { artifacts: m.artifacts });
987
+ }))
962
988
  }),
963
- pick_structured: P({
989
+ pick_structured: M({
964
990
  name: "pick_structured",
965
991
  description: "Produce a JSON object for a task. Returns the object.",
966
992
  input: T.Struct({
967
993
  prompt: T.String,
994
+ purpose: ln,
968
995
  model: T.optional(T.String)
969
996
  }),
970
- execute: ({ prompt: e, model: n }) => w.gen(function* () {
971
- let r = u({
972
- title: "structured",
973
- type: "structured"
974
- });
975
- yield* f();
976
- let i = yield* Xe({
977
- prompt: e,
978
- schema: T.Record({
979
- key: T.String,
980
- value: T.Unknown
981
- }),
982
- ...n ? { provider: U(t, n) } : {}
997
+ execute: ({ prompt: e, purpose: n, model: r }) => p({
998
+ title: "structured",
999
+ type: "structured",
1000
+ ...un(n)
1001
+ }, (n) => w.gen(function* () {
1002
+ let i = yield* et({
1003
+ prompt: `${e}\n\nReturn the JSON object serialized as a string in the \`json\` field.`,
1004
+ schema: dn,
1005
+ ...r ? { provider: W(t, r) } : {}
983
1006
  }).pipe(w.map((e) => ({
984
1007
  ok: !0,
985
1008
  r: e
@@ -989,62 +1012,76 @@ var Vt = (e, t = {}) => {
989
1012
  })));
990
1013
  if (!i.ok) {
991
1014
  let e = String(i.e.message ?? i.e);
992
- return d(r, {
1015
+ return d(n, {
993
1016
  status: "failed",
994
1017
  errorMessage: e
995
1018
  }), yield* f(), { error: e };
996
1019
  }
997
- let a = Zt(i.r.usage, i.r.providerMetadata, n);
998
- return l += a, d(r, {
1020
+ let a = Qt(i.r.usage, i.r.providerMetadata, r);
1021
+ l += a;
1022
+ let o = fn(i.r.object.json);
1023
+ if (o === void 0) {
1024
+ let e = "the model's `json` field is not a JSON object";
1025
+ return d(n, {
1026
+ status: "failed",
1027
+ errorMessage: e,
1028
+ costMicroUsd: a
1029
+ }), yield* f(), { error: e };
1030
+ }
1031
+ return d(n, {
999
1032
  status: "succeeded",
1000
- output: { text: JSON.stringify(i.r.object) },
1033
+ output: { text: JSON.stringify(o) },
1001
1034
  costMicroUsd: a
1002
- }), yield* f(), i.r.object;
1003
- })
1035
+ }), yield* f(), o;
1036
+ }))
1004
1037
  })
1005
- }, m = yield* (t.resolveTools ? B(t.resolveTools(s, {
1038
+ }, g = yield* (t.resolveTools ? V(t.resolveTools(s, {
1006
1039
  runId: n,
1007
1040
  tenantId: o,
1008
1041
  ownerId: a
1009
- }, { provider: () => r.orchestrator?.model ? U(t, r.orchestrator.model) : void 0 })) : w.succeed({})).pipe(w.either);
1010
- if (m._tag === "Left") return yield* w.logWarning(`flow tool resolution failed for run ${n}: ${m.left.message}`).pipe(w.annotateLogs({ scope: "voltro:ai-flows" })), {
1042
+ }, { provider: () => r.orchestrator?.model ? W(t, r.orchestrator.model) : void 0 })) : w.succeed({})).pipe(w.either);
1043
+ if (g._tag === "Left") return yield* w.logWarning(`flow tool resolution failed for run ${n}: ${g.left.message}`).pipe(w.annotateLogs({ scope: "voltro:ai-flows" })), {
1011
1044
  object: {},
1012
1045
  planCostMicroUsd: 0,
1013
1046
  toolCostMicroUsd: 0,
1014
1047
  steps: c,
1015
1048
  error: "flow tool resolution failed"
1016
1049
  };
1017
- if (Object.keys(m.right).some((e) => Object.hasOwn(p, e))) return {
1050
+ if (Object.keys(g.right).some((e) => Object.hasOwn(te, e))) return {
1018
1051
  object: {},
1019
1052
  planCostMicroUsd: 0,
1020
1053
  toolCostMicroUsd: 0,
1021
1054
  steps: c,
1022
1055
  error: "flow tools cannot replace reserved planner tools"
1023
1056
  };
1024
- let h = t.memoryPrefix ? yield* B(t.memoryPrefix(a)).pipe(w.catchAll(() => w.succeed(""))) : "", ee = h ? `${h}\n\n${cn(r)}` : cn(r), g = yield* Qe({
1025
- system: ee,
1026
- prompt: sn(i),
1057
+ let _ = t.memoryPrefix ? yield* V(t.memoryPrefix(a)).pipe(w.catchAll(() => w.succeed(""))) : "", v = _ ? `${_}\n\n${hn(r)}` : hn(r), y = yield* nt({
1058
+ system: v,
1059
+ prompt: mn(i),
1027
1060
  schema: T.Record({
1028
1061
  key: T.String,
1029
1062
  value: T.Unknown
1030
1063
  }),
1031
1064
  tools: {
1032
- ...m.right,
1033
- ...p
1065
+ ...g.right,
1066
+ ...te
1034
1067
  },
1035
1068
  maxSteps: r.maxSteps,
1036
- ...r.orchestrator?.model ? { provider: U(t, r.orchestrator.model) } : {}
1037
- }).pipe(w.map((e) => ({
1069
+ ...r.orchestrator?.model ? { provider: W(t, r.orchestrator.model) } : {}
1070
+ }).pipe(w.provideService(Ye, cn), w.map((e) => ({
1038
1071
  ok: !0,
1039
1072
  r: e
1040
1073
  })), w.catchAll((e) => w.succeed({
1041
1074
  ok: !1,
1042
1075
  e
1043
1076
  })));
1044
- return g.ok ? {
1045
- object: g.r.object,
1046
- planCostMicroUsd: Zt(g.r.usage, g.r.providerMetadata, r.orchestrator?.model),
1047
- planCostSource: W(g.r.usage, g.r.providerMetadata, r.orchestrator?.model).costSource,
1077
+ for (let e of c) e.status === "running" && d(e.id, {
1078
+ status: "failed",
1079
+ errorMessage: "not finished — the run ended first"
1080
+ });
1081
+ return y.ok ? {
1082
+ object: y.r.object,
1083
+ planCostMicroUsd: Qt(y.r.usage, y.r.providerMetadata, r.orchestrator?.model),
1084
+ planCostSource: G(y.r.usage, y.r.providerMetadata, r.orchestrator?.model).costSource,
1048
1085
  toolCostMicroUsd: l,
1049
1086
  steps: c
1050
1087
  } : {
@@ -1052,29 +1089,29 @@ var Vt = (e, t = {}) => {
1052
1089
  planCostMicroUsd: 0,
1053
1090
  toolCostMicroUsd: l,
1054
1091
  steps: c,
1055
- error: String(g.e.message ?? g.e)
1092
+ error: String(y.e.message ?? y.e)
1056
1093
  };
1057
1094
  })
1058
- }), l = c.planCostMicroUsd + c.toolCostMicroUsd, u = G([...c.steps, {
1095
+ }), l = c.planCostMicroUsd + c.toolCostMicroUsd, u = K([...c.steps, {
1059
1096
  status: "succeeded",
1060
1097
  costMicroUsd: c.planCostMicroUsd,
1061
1098
  costSource: c.planCostSource ?? "unpriced"
1062
1099
  }]);
1063
- return c.error ? (yield* K(e, n, {
1100
+ return c.error ? (yield* q(e, n, {
1064
1101
  status: "failed",
1065
1102
  steps: c.steps,
1066
1103
  errorMessage: c.error,
1067
- completedAt: H(),
1104
+ completedAt: U(),
1068
1105
  costMicroUsd: l,
1069
1106
  costCompleteness: u
1070
1107
  }), {
1071
1108
  runId: n,
1072
1109
  status: "failed"
1073
- }) : (yield* K(e, n, {
1110
+ }) : (yield* q(e, n, {
1074
1111
  status: "succeeded",
1075
1112
  steps: c.steps,
1076
1113
  output: c.object,
1077
- completedAt: H(),
1114
+ completedAt: U(),
1078
1115
  costMicroUsd: l,
1079
1116
  costCompleteness: u
1080
1117
  }), {
@@ -1082,53 +1119,53 @@ var Vt = (e, t = {}) => {
1082
1119
  status: "succeeded",
1083
1120
  output: c.object
1084
1121
  });
1085
- }), dn = (e, t = {}) => (n, r) => w.gen(function* () {
1086
- let { runId: r, flowRef: i, input: a } = n, o = yield* w.tryPromise(() => e.store.query(A(L).where(D("id", r)).descriptor)).pipe(w.flatMap(T.decodeUnknown(T.Tuple(T.Struct({
1122
+ }), vn = (e, t = {}) => (n, r) => w.gen(function* () {
1123
+ let { runId: r, flowRef: i, input: a } = n, o = yield* w.tryPromise(() => e.store.query(k(I).where(E("id", r)).descriptor)).pipe(w.flatMap(T.decodeUnknown(T.Tuple(T.Struct({
1087
1124
  id: T.Literal(r),
1088
1125
  tenantId: T.NullOr(T.NonEmptyString),
1089
1126
  ownerId: T.optional(T.NullOr(T.String))
1090
1127
  })))), w.either);
1091
- if (o._tag === "Left") return yield* K(e, r, {
1128
+ if (o._tag === "Left") return yield* q(e, r, {
1092
1129
  status: "failed",
1093
1130
  errorMessage: "flow run context unavailable: expected one matching run row with an explicit tenantId (string or null)",
1094
- completedAt: H()
1131
+ completedAt: U()
1095
1132
  }), {
1096
1133
  runId: r,
1097
1134
  status: "failed"
1098
1135
  };
1099
- let { tenantId: s, ownerId: c = null } = o.right[0], l = yield* N({
1136
+ let { tenantId: s, ownerId: c = null } = o.right[0], l = yield* j({
1100
1137
  name: "flow-0-resolve",
1101
1138
  input: { flowRef: i },
1102
1139
  success: T.Struct({
1103
1140
  ir: T.Unknown,
1104
1141
  error: T.optional(T.String)
1105
1142
  }),
1106
- execute: tn(e, i).pipe(w.map((e) => ({ ir: e })), w.catchAll((e) => w.succeed({
1143
+ execute: J(e, i).pipe(w.map((e) => ({ ir: e })), w.catchAll((e) => w.succeed({
1107
1144
  ir: void 0,
1108
1145
  error: e.message
1109
1146
  })))
1110
1147
  });
1111
- if (l.error || !l.ir) return yield* K(e, r, {
1148
+ if (l.error || !l.ir) return yield* q(e, r, {
1112
1149
  status: "failed",
1113
1150
  errorMessage: l.error ?? "flow not found",
1114
- completedAt: H()
1151
+ completedAt: U()
1115
1152
  }), {
1116
1153
  runId: r,
1117
1154
  status: "failed"
1118
1155
  };
1119
- let u = l.ir, d = u.mode === "agentic" ? yield* un(e, t, r, u, a, c, s, i) : yield* rn(e, t, r, u, a, {
1156
+ let u = l.ir, d = u.mode === "agentic" ? yield* _n(e, t, r, u, a, c, s, i) : yield* rn(e, t, r, u, a, {
1120
1157
  ownerId: c,
1121
1158
  tenantId: s,
1122
1159
  source: n.source
1123
1160
  });
1124
- return d.status === "succeeded" && u.chain && (yield* an(e, r, u, a, d.output ?? {}, n, t)), t.onEvent && (d.status === "succeeded" || d.status === "failed") && (yield* B(t.onEvent({
1161
+ return d.status === "succeeded" && u.chain && (yield* an(e, r, u, a, d.output ?? {}, n, t)), t.onEvent && (d.status === "succeeded" || d.status === "failed") && (yield* V(t.onEvent({
1125
1162
  kind: d.status,
1126
1163
  runId: r,
1127
1164
  flowName: u.name,
1128
1165
  ownerId: c,
1129
1166
  source: n.source
1130
1167
  })).pipe(w.catchAllCause(() => w.void))), d;
1131
- }), fn = {
1168
+ }), yn = {
1132
1169
  text: (e) => ({
1133
1170
  type: "generate",
1134
1171
  modality: "text",
@@ -1155,17 +1192,17 @@ var Vt = (e, t = {}) => {
1155
1192
  type: "human",
1156
1193
  ...e
1157
1194
  })
1158
- }, pn = (e) => e.map((e, t) => "id" in e && e.id ? e : {
1195
+ }, bn = (e) => e.map((e, t) => "id" in e && e.id ? e : {
1159
1196
  id: `step-${t}`,
1160
1197
  ...e
1161
- }), mn = (e) => {
1162
- let t = [], n = jt(e.steps);
1163
- for (let e of Mt(n)) t.push(`group "${e}" is not contiguous — only CONSECUTIVE steps sharing a group run concurrently, so this would execute as two separate fan-outs`);
1198
+ }), xn = (e) => {
1199
+ let t = [], n = Pt(e.steps);
1200
+ for (let e of Ft(n)) t.push(`group "${e}" is not contiguous — only CONSECUTIVE steps sharing a group run concurrently, so this would execute as two separate fan-outs`);
1164
1201
  let r = new Set(e.brief.map((e) => e.key));
1165
1202
  for (let e of n) {
1166
1203
  for (let { step: n } of e.steps) {
1167
1204
  n.type === "human" && n.group !== void 0 && t.push(`step "${n.id}" is a human review inside group "${n.group}" — a review SUSPENDS the whole run, which one branch of a fan-out cannot do`);
1168
- for (let i of Ot(n.prompt ?? "")) r.has(i) || t.push(e.steps.length > 1 ? `step "${n.id}" references {{${i}}} which is produced inside its OWN group "${n.group}" or does not exist — grouped steps run concurrently, so they cannot read each other` : `step "${n.id}" references {{${i}}} which is not a brief field or a prior step outputKey`);
1205
+ for (let i of jt(n.prompt ?? "")) r.has(i) || t.push(e.steps.length > 1 ? `step "${n.id}" references {{${i}}} which is produced inside its OWN group "${n.group}" or does not exist — grouped steps run concurrently, so they cannot read each other` : `step "${n.id}" references {{${i}}} which is not a brief field or a prior step outputKey`);
1169
1206
  for (let [e, i] of Object.entries(n.mediaInputs ?? {})) i.from === "step" && !r.has(i.ref) && t.push(`step "${n.id}" media input "${e}" references "${i.ref}" which is not a brief field or an earlier segment's outputKey`);
1170
1207
  n.when !== void 0 && !r.has(n.when.ref) && t.push(`step "${n.id}" has a when-condition on {{${n.when.ref}}} which is not a brief field or a prior step outputKey — it would never run`);
1171
1208
  }
@@ -1176,11 +1213,11 @@ var Vt = (e, t = {}) => {
1176
1213
  message: `flow "${e.name}" has ${t.length} problem(s)`,
1177
1214
  issues: t
1178
1215
  });
1179
- }, hn = (e) => {
1216
+ }, Sn = (e) => {
1180
1217
  let t = d({
1181
1218
  name: e.name,
1182
1219
  mode: e.mode,
1183
- steps: pn(e.steps),
1220
+ steps: bn(e.steps),
1184
1221
  maxSteps: e.maxSteps,
1185
1222
  brief: e.brief,
1186
1223
  orchestratorModel: e.orchestrator?.model,
@@ -1189,21 +1226,21 @@ var Vt = (e, t = {}) => {
1189
1226
  cadence: e.cadence,
1190
1227
  humanTimeoutMs: e.humanTimeoutMs
1191
1228
  });
1192
- return mn(t), it(t), t;
1193
- }, q = async (e, t, n) => {
1194
- let r = T.decodeUnknownSync(Pe.pipe(T.filter((e) => e.workflowName === "flow.run" && e.id.length > 0)))(n);
1195
- if (await e.store.update(L.tableName, t, { workflowStart: r }) === null) throw Error("flow start receipt could not be recorded; workflow submission may have succeeded");
1229
+ return xn(t), ct(t), t;
1230
+ }, Cn = async (e, t, n) => {
1231
+ let r = T.decodeUnknownSync(Fe.pipe(T.filter((e) => e.workflowName === "flow.run" && e.id.length > 0)))(n);
1232
+ if (await e.store.update(I.tableName, t, { workflowStart: r }) === null) throw Error("flow start receipt could not be recorded; workflow submission may have succeeded");
1196
1233
  return r;
1197
- }, gn = (e, t, n) => {
1234
+ }, wn = (e, t, n) => {
1198
1235
  if (!Number.isFinite(t.getTime())) throw Error("cadence timestamp must be valid");
1199
- return `cron-${rt("sha256").update(JSON.stringify([
1236
+ return `cron-${st("sha256").update(JSON.stringify([
1200
1237
  n,
1201
1238
  e,
1202
1239
  Math.floor(t.getTime() / 6e4)
1203
1240
  ])).digest("hex")}`;
1204
- }, _n = async (e) => {
1241
+ }, Tn = async (e) => {
1205
1242
  let t = [];
1206
- for (let n of ot()) n.cadence && (n.cadence.repeats?.length ?? 0) > 0 && t.push({
1243
+ for (let n of P()) n.cadence && (n.cadence.repeats?.length ?? 0) > 0 && t.push({
1207
1244
  tenantId: e.request.subject.tenantId,
1208
1245
  flowRef: n.name,
1209
1246
  cadence: n.cadence,
@@ -1217,8 +1254,8 @@ var Vt = (e, t = {}) => {
1217
1254
  defaultInput: r.cadence.defaultInput ?? {}
1218
1255
  });
1219
1256
  return t;
1220
- }, vn = async (e, t = /* @__PURE__ */ new Date()) => {
1221
- let r = [], i = 0, a = [], o = e.workflows ? await ft(e) : {
1257
+ }, En = async (e, t = /* @__PURE__ */ new Date()) => {
1258
+ let r = [], i = 0, a = [], o = e.workflows ? await ht(e) : {
1222
1259
  examined: 0,
1223
1260
  accepted: 0,
1224
1261
  notExecuted: 0,
@@ -1226,11 +1263,11 @@ var Vt = (e, t = {}) => {
1226
1263
  failures: []
1227
1264
  };
1228
1265
  a.push(...o.failures.map((e) => Error(`flow run ${e.runId}: start reconciliation failed`, { cause: e.cause })));
1229
- let s = await _n(e);
1266
+ let s = await Tn(e);
1230
1267
  for (let o of s) {
1231
1268
  if (!je(o.cadence, t)) continue;
1232
1269
  i += 1;
1233
- let s = gn(o.flowRef, t, o.tenantId), c = `run-${s}`;
1270
+ let s = wn(o.flowRef, t, o.tenantId), c = `run-${s}`;
1234
1271
  try {
1235
1272
  if (!e.workflows) throw Error("workflow runtime unavailable; no cadence start was submitted");
1236
1273
  (await e.transaction(async (e) => {
@@ -1251,7 +1288,7 @@ var Vt = (e, t = {}) => {
1251
1288
  ...r,
1252
1289
  runId: r.id
1253
1290
  });
1254
- return q(e, c, await t.start("flow.run", i));
1291
+ return Cn(e, c, await t.start("flow.run", i));
1255
1292
  }, o.tenantId === null ? void 0 : { tenantId: o.tenantId })).status === "running" && r.push(s);
1256
1293
  } catch (e) {
1257
1294
  a.push(e);
@@ -1263,42 +1300,42 @@ var Vt = (e, t = {}) => {
1263
1300
  started: r,
1264
1301
  reconciled: o
1265
1302
  };
1266
- }, J = (e) => T.optionalWith(e, { exact: !0 }), yn = T.Int.pipe(T.positive(), T.lessThanOrEqualTo(2 ** 53 - 1)), bn = T.Int.pipe(T.between(-(2 ** 53 - 1), 2 ** 53 - 1)), xn = T.TemplateLiteral(T.Number, "x", T.Number).pipe(T.pattern(/^[1-9]\d*x[1-9]\d*$/)), Sn = T.TemplateLiteral(T.Number, ":", T.Number).pipe(T.pattern(/^[1-9]\d*:[1-9]\d*$/)), Cn = T.Struct({
1267
- n: J(yn),
1268
- seed: J(bn),
1269
- size: J(xn),
1270
- aspectRatio: J(Sn),
1271
- providerOptions: J(R)
1272
- }), wn = T.Struct({
1273
- voice: J(T.NonEmptyString),
1274
- outputFormat: J(T.NonEmptyString),
1275
- instructions: J(T.String),
1276
- speed: J(T.Finite.pipe(T.positive())),
1277
- language: J(T.NonEmptyString),
1278
- providerOptions: J(R)
1279
- }), Tn = T.Struct({
1280
- aspectRatio: J(Sn),
1281
- durationSeconds: J(T.Finite.pipe(T.positive())),
1282
- resolution: J(xn),
1283
- fps: J(T.Finite.pipe(T.positive())),
1284
- seed: J(bn),
1285
- generateAudio: J(T.Boolean),
1286
- maxInlineBytes: J(yn),
1287
- providerOptions: J(R)
1288
- }), Y = (e, t, n) => w.try({
1303
+ }, Y = (e) => T.optionalWith(e, { exact: !0 }), Dn = T.Int.pipe(T.positive(), T.lessThanOrEqualTo(2 ** 53 - 1)), On = T.Int.pipe(T.between(-(2 ** 53 - 1), 2 ** 53 - 1)), kn = T.TemplateLiteral(T.Number, "x", T.Number).pipe(T.pattern(/^[1-9]\d*x[1-9]\d*$/)), An = T.TemplateLiteral(T.Number, ":", T.Number).pipe(T.pattern(/^[1-9]\d*:[1-9]\d*$/)), jn = T.Struct({
1304
+ n: Y(Dn),
1305
+ seed: Y(On),
1306
+ size: Y(kn),
1307
+ aspectRatio: Y(An),
1308
+ providerOptions: Y(R)
1309
+ }), Mn = T.Struct({
1310
+ voice: Y(T.NonEmptyString),
1311
+ outputFormat: Y(T.NonEmptyString),
1312
+ instructions: Y(T.String),
1313
+ speed: Y(T.Finite.pipe(T.positive())),
1314
+ language: Y(T.NonEmptyString),
1315
+ providerOptions: Y(R)
1316
+ }), Nn = T.Struct({
1317
+ aspectRatio: Y(An),
1318
+ durationSeconds: Y(T.Finite.pipe(T.positive())),
1319
+ resolution: Y(kn),
1320
+ fps: Y(T.Finite.pipe(T.positive())),
1321
+ seed: Y(On),
1322
+ generateAudio: Y(T.Boolean),
1323
+ maxInlineBytes: Y(Dn),
1324
+ providerOptions: Y(R)
1325
+ }), Pn = (e, t, n) => w.try({
1289
1326
  try: () => T.decodeUnknownSync(e, { onExcessProperty: "error" })(t === void 0 ? {} : t),
1290
1327
  catch: () => `invalid ${n} media params: check the built-in adapter's supported options and value ranges`
1291
- }), En = (e) => Y(Cn, e, "image"), Dn = (e) => Y(wn, e, "audio"), On = (e) => Y(Tn, e, "video"), kn = (e) => ({
1328
+ }), Fn = (e) => Pn(jn, e, "image"), In = (e) => Pn(Mn, e, "audio"), Ln = (e) => Pn(Nn, e, "video"), Rn = (e) => ({
1292
1329
  name: "gateway",
1293
1330
  model: e
1294
- }), An = (e) => Math.round(e * 1e6), X = (e, t, n) => {
1295
- let r = Je(t);
1331
+ }), zn = (e) => Math.round(e * 1e6), X = (e, t, n) => {
1332
+ let r = Qe(t);
1296
1333
  if (typeof r == "number") return {
1297
- costMicroUsd: An(r),
1334
+ costMicroUsd: zn(r),
1298
1335
  costSource: "gateway"
1299
1336
  };
1300
1337
  if (e) {
1301
- let t = qe(e, { model: n ?? "unknown" });
1338
+ let t = Ze(e, { model: n ?? "unknown" });
1302
1339
  return {
1303
1340
  costMicroUsd: t.costMicroUsd ?? 0,
1304
1341
  costSource: t.costSource ?? "unpriced"
@@ -1310,7 +1347,7 @@ var Vt = (e, t = {}) => {
1310
1347
  };
1311
1348
  }, Z = (e) => {
1312
1349
  if (e === void 0) return { status: "unreported" };
1313
- let [t, n, r] = nt(e) ? [
1350
+ let [t, n, r] = ot(e) ? [
1314
1351
  e.unit,
1315
1352
  e.input,
1316
1353
  e.output
@@ -1328,18 +1365,18 @@ var Vt = (e, t = {}) => {
1328
1365
  }, Q = (e, t, n) => ({
1329
1366
  ...X(e, t, n),
1330
1367
  usage: Z(e)
1331
- }), jn = (e, t) => (n) => {
1332
- let r = n.model, i = (e) => t?.resolveModel?.(e) ?? kn(e);
1368
+ }), Bn = (e, t) => (n) => {
1369
+ let r = n.model, i = (e) => t?.resolveModel?.(e) ?? Rn(e);
1333
1370
  return w.gen(function* () {
1334
- let t = yield* Ht(n.modality, n.inputs).pipe(w.mapError((e) => new S({
1371
+ let t = yield* Ut(n.modality, n.inputs).pipe(w.mapError((e) => new S({
1335
1372
  capability: `media:${n.modality}`,
1336
1373
  message: e
1337
1374
  })));
1338
1375
  if (n.modality === "image") {
1339
- let a = yield* En(n.params).pipe(w.mapError((e) => new S({
1376
+ let a = yield* Fn(n.params).pipe(w.mapError((e) => new S({
1340
1377
  capability: "media:image",
1341
1378
  message: e
1342
- }))), o = t.referenceImageUrl, s = t.maskImageUrl, c = yield* Ye({
1379
+ }))), o = t.referenceImageUrl, s = t.maskImageUrl, c = yield* $e({
1343
1380
  ...a,
1344
1381
  prompt: n.prompt,
1345
1382
  ...o === void 0 ? {} : { inputs: {
@@ -1378,10 +1415,10 @@ var Vt = (e, t = {}) => {
1378
1415
  };
1379
1416
  }
1380
1417
  if (n.modality === "audio") {
1381
- let t = yield* Dn(n.params).pipe(w.mapError((e) => new S({
1418
+ let t = yield* In(n.params).pipe(w.mapError((e) => new S({
1382
1419
  capability: "media:audio",
1383
1420
  message: e
1384
- }))), a = yield* $e({
1421
+ }))), a = yield* rt({
1385
1422
  ...t,
1386
1423
  text: n.prompt,
1387
1424
  ...r ? { provider: i(r) } : {}
@@ -1405,10 +1442,10 @@ var Vt = (e, t = {}) => {
1405
1442
  usage: Z(a.usage)
1406
1443
  };
1407
1444
  }
1408
- let { maxInlineBytes: a, providerOptions: o, ...s } = yield* On(n.params).pipe(w.mapError((e) => new S({
1445
+ let { maxInlineBytes: a, providerOptions: o, ...s } = yield* Ln(n.params).pipe(w.mapError((e) => new S({
1409
1446
  capability: "media:video",
1410
1447
  message: e
1411
- }))), c = yield* tt({
1448
+ }))), c = yield* at({
1412
1449
  prompt: n.prompt,
1413
1450
  inputs: {
1414
1451
  ...t.referenceImageUrl === void 0 ? {} : { image: t.referenceImageUrl },
@@ -1458,22 +1495,22 @@ var Vt = (e, t = {}) => {
1458
1495
  capability: `media:${n.modality}`,
1459
1496
  message: String(e.message ?? e)
1460
1497
  }))));
1461
- }, Mn = () => globalThis.crypto?.randomUUID?.() ?? `req-${Date.now().toString(36)}`, Nn = (e) => e.request?.subject?.id ?? null, $ = (e, t) => w.promise(() => e.store.query(A(L).where(D("id", t)).descriptor)).pipe(w.map((e) => e[0])), Pn = (e) => w.sync(() => {
1498
+ }, Vn = () => globalThis.crypto?.randomUUID?.() ?? `req-${Date.now().toString(36)}`, Hn = (e) => e.request?.subject?.id ?? null, $ = (e, t) => w.promise(() => e.store.query(k(I).where(E("id", t)).descriptor)).pipe(w.map((e) => e[0])), Un = (e) => w.sync(() => {
1462
1499
  let t = e.workflows;
1463
1500
  if (!t) throw Error("workflow runtime unavailable; no flow start was submitted");
1464
1501
  return t;
1465
- }), Fn = (t, n) => w.gen(function* () {
1466
- yield* Pn(t);
1467
- let r = yield* tn(t, n.flowRef), i = n.input ?? {}, a = r.brief.filter((e) => e.required && e.type !== "boolean" && (i[e.key] === void 0 || i[e.key] === null || i[e.key] === "")).map((e) => e.key);
1502
+ }), Wn = (t, n) => w.gen(function* () {
1503
+ yield* Un(t);
1504
+ let r = yield* J(t, n.flowRef), i = n.input ?? {}, a = r.brief.filter((e) => e.required && e.type !== "boolean" && (i[e.key] === void 0 || i[e.key] === null || i[e.key] === "")).map((e) => e.key);
1468
1505
  if (a.length > 0) return yield* w.fail(new we({
1469
1506
  missing: a,
1470
1507
  message: `missing required brief field(s): ${a.join(", ")}`
1471
1508
  }));
1472
- let o = Mn(), s = `run-${o}`, c = n.source ?? "manual";
1509
+ let o = Vn(), s = `run-${o}`, c = n.source ?? "manual";
1473
1510
  return yield* w.promise(() => t.transaction(async (t) => {
1474
1511
  let a = t.workflows;
1475
1512
  if (!a) throw Error("workflow runtime unavailable in transaction; no flow start was submitted");
1476
- await t.store.insert(L.tableName, {
1513
+ await t.store.insert(I.tableName, {
1477
1514
  id: s,
1478
1515
  flowRef: n.flowRef,
1479
1516
  flowName: r.name,
@@ -1482,27 +1519,27 @@ var Vt = (e, t = {}) => {
1482
1519
  source: c,
1483
1520
  requestId: o,
1484
1521
  input: i,
1485
- ownerId: Nn(t)
1522
+ ownerId: Hn(t)
1486
1523
  });
1487
- let l = await q(t, s, await a.start(e, {
1524
+ let l = await Cn(t, s, await a.start(e, {
1488
1525
  runId: s,
1489
1526
  flowRef: n.flowRef,
1490
1527
  input: i,
1491
1528
  source: c,
1492
1529
  requestId: o
1493
1530
  }));
1494
- return y.make({
1531
+ return ae.make({
1495
1532
  runId: s,
1496
1533
  requestId: o,
1497
1534
  admission: l
1498
1535
  });
1499
1536
  }));
1500
- }), In = (t, r) => w.gen(function* () {
1501
- return yield* Pn(t), yield* w.tryPromise({
1537
+ }), Gn = (t, r) => w.gen(function* () {
1538
+ return yield* Un(t), yield* w.tryPromise({
1502
1539
  try: () => t.transaction(async (t) => {
1503
1540
  let i = t.workflows;
1504
1541
  if (!i) throw Error("workflow runtime unavailable in transaction; no flow start was submitted");
1505
- let a = (await t.store.query(A(L).where(D("id", r.runId)).descriptor))[0];
1542
+ let a = (await t.store.query(k(I).where(E("id", r.runId)).descriptor))[0];
1506
1543
  if (!a) throw new C({
1507
1544
  runId: r.runId,
1508
1545
  message: "run not found"
@@ -1514,8 +1551,8 @@ var Vt = (e, t = {}) => {
1514
1551
  runId: a.id
1515
1552
  });
1516
1553
  if (s._tag === "Left") throw Error("stored workflow payload is incomplete or invalid; retry refused without changing the run");
1517
- let c = await q(t, r.runId, await i.start(e, s.right));
1518
- return y.make({
1554
+ let c = await Cn(t, r.runId, await i.start(e, s.right));
1555
+ return ae.make({
1519
1556
  runId: r.runId,
1520
1557
  requestId: o,
1521
1558
  admission: c
@@ -1523,23 +1560,23 @@ var Vt = (e, t = {}) => {
1523
1560
  }),
1524
1561
  catch: (e) => e
1525
1562
  }).pipe(w.catchAll((e) => e instanceof C ? w.fail(e) : w.die(e)));
1526
- }), Ln = (t, r) => w.gen(function* () {
1563
+ }), Kn = (t, r) => w.gen(function* () {
1527
1564
  let i = yield* $(t, r.runId);
1528
1565
  if (!i) return yield* w.fail(new C({
1529
1566
  runId: r.runId,
1530
1567
  message: "run not found"
1531
1568
  }));
1532
- if (Rn(i.status)) return x.make({
1569
+ if (qn(i.status)) return x.make({
1533
1570
  runId: r.runId,
1534
1571
  status: i.status,
1535
1572
  engine: "not-requested",
1536
1573
  control: null
1537
1574
  });
1538
1575
  let a = (/* @__PURE__ */ new Date()).toISOString();
1539
- yield* w.promise(() => t.store.updateMany(L.tableName, {
1576
+ yield* w.promise(() => t.store.updateMany(I.tableName, {
1540
1577
  status: "cancelling",
1541
1578
  cancelledAt: a
1542
- }, { where: E(D("id", r.runId), ze("status", [
1579
+ }, { where: Re(E("id", r.runId), Ve("status", [
1543
1580
  "pending",
1544
1581
  "running",
1545
1582
  "waiting"
@@ -1549,7 +1586,7 @@ var Vt = (e, t = {}) => {
1549
1586
  runId: r.runId,
1550
1587
  message: "run not found"
1551
1588
  }));
1552
- if (Rn(o.status)) return x.make({
1589
+ if (qn(o.status)) return x.make({
1553
1590
  runId: r.runId,
1554
1591
  status: o.status,
1555
1592
  engine: "not-requested",
@@ -1568,17 +1605,17 @@ var Vt = (e, t = {}) => {
1568
1605
  ...i,
1569
1606
  runId: i.id
1570
1607
  }), l = s === void 0 || c._tag === "None" ? null : yield* w.flatMap(n.executionId(c.value), (t) => w.tryPromise(async () => {
1571
- let n = T.decodeUnknownSync(Ne)(await s.cancel(e, t));
1608
+ let n = T.decodeUnknownSync(Pe)(await s.cancel(e, t));
1572
1609
  if (n.operation !== "cancel" || n.snapshot.workflowName !== "flow.run" || n.snapshot.executionId !== t) throw Error("workflow cancellation receipt does not match the flow execution");
1573
1610
  return n;
1574
- })).pipe(w.catchAll(() => w.succeed(null))), u = l === null ? s === void 0 || c._tag === "None" ? "unreachable" : "unknown" : l.snapshot.status === "cancelled" && (l.kind === "confirmed" || l.kind === "already-terminal") ? "cancelled" : l.kind === "accepted" ? "accepted" : l.kind === "already-terminal" ? "already-terminal" : "unknown", d = E(D("id", r.runId), D("status", "cancelling"), D("cancelledAt", o.cancelledAt));
1575
- if (u === "cancelled") yield* w.promise(() => t.store.updateMany(L.tableName, {
1611
+ })).pipe(w.catchAll(() => w.succeed(null))), u = l === null ? s === void 0 || c._tag === "None" ? "unreachable" : "unknown" : l.snapshot.status === "cancelled" && (l.kind === "confirmed" || l.kind === "already-terminal") ? "cancelled" : l.kind === "accepted" ? "accepted" : l.kind === "already-terminal" ? "already-terminal" : "unknown", d = Re(E("id", r.runId), E("status", "cancelling"), E("cancelledAt", o.cancelledAt));
1612
+ if (u === "cancelled") yield* w.promise(() => t.store.updateMany(I.tableName, {
1576
1613
  status: "cancelled",
1577
1614
  completedAt: o.completedAt ?? (/* @__PURE__ */ new Date()).toISOString()
1578
1615
  }, { where: d }));
1579
1616
  else if (l?.kind === "already-terminal") {
1580
1617
  let e = T.decodeUnknownOption(n.successSchema)(l.snapshot.output), i = l.snapshot.status === "failed" ? "failed" : e._tag === "Some" && e.value.runId === r.runId && e.value.status !== "waiting" ? e.value.status : void 0;
1581
- i !== void 0 && (yield* w.promise(() => t.store.updateMany(L.tableName, {
1618
+ i !== void 0 && (yield* w.promise(() => t.store.updateMany(I.tableName, {
1582
1619
  status: i,
1583
1620
  completedAt: o.completedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
1584
1621
  ...i === "cancelled" ? {} : { cancelledAt: null }
@@ -1594,11 +1631,11 @@ var Vt = (e, t = {}) => {
1594
1631
  runId: r.runId,
1595
1632
  message: "run not found"
1596
1633
  }));
1597
- }), Rn = (e) => e === "succeeded" || e === "failed" || e === "cancelled", zn = (e) => {
1634
+ }), qn = (e) => e === "succeeded" || e === "failed" || e === "cancelled", Jn = (e) => {
1598
1635
  let t = e.steps?.filter((e) => e.status === "waiting"), n = t?.[0];
1599
1636
  if (t?.length !== 1 || n?.type !== "human" || !Number.isSafeInteger(n.id) || n.id < 0) throw Error("expected exactly one waiting human step with a nonnegative integer index");
1600
1637
  return n.id;
1601
- }, Bn = (t, i) => w.gen(function* () {
1638
+ }, Yn = (t, i) => w.gen(function* () {
1602
1639
  let a = (e, t) => new Oe({
1603
1640
  runId: i.runId,
1604
1641
  reason: e,
@@ -1619,7 +1656,7 @@ var Vt = (e, t = {}) => {
1619
1656
  message: `run is "${l}", not awaiting a response`
1620
1657
  }));
1621
1658
  let u = yield* w.try({
1622
- try: () => zn(c),
1659
+ try: () => Jn(c),
1623
1660
  catch: () => a("invalid-run", "stored run has no unambiguous waiting review")
1624
1661
  });
1625
1662
  if (u !== o.stepIndex) return yield* w.fail(new Ee({
@@ -1656,22 +1693,22 @@ var Vt = (e, t = {}) => {
1656
1693
  eventId: h.eventId,
1657
1694
  status: "accepted"
1658
1695
  }).pipe(w.mapError(() => a("delivery-unknown", "workflow runtime returned no valid review delivery receipt")));
1659
- }), Vn = (e, t) => w.promise(() => e.store.query(A(I).where(D("id", t.id)).descriptor)).pipe(w.map((e) => e[0])), Hn = (e) => w.promise(() => e.store.query(A(I).descriptor)), Un = (e, t) => w.promise(() => e.store.insert(I.tableName, {
1660
- id: t.id ?? `flow-${Mn()}`,
1696
+ }), Xn = (e, t) => w.promise(() => e.store.query(k(F).where(E("id", t.id)).descriptor)).pipe(w.map((e) => e[0])), Zn = (e) => w.promise(() => e.store.query(k(F).descriptor)), Qn = (e, t) => w.promise(() => e.store.insert(F.tableName, {
1697
+ id: t.id ?? `flow-${Vn()}`,
1661
1698
  ...t
1662
- })), Wn = (e, t) => w.promise(() => e.store.update(I.tableName, t.id, t.patch)), Gn = (e, t) => w.promise(() => e.store.delete(I.tableName, t.id)), Kn = "aiFlows", qn = (e = {}) => {
1663
- let t = Ie({
1664
- base: Kn,
1699
+ })), $n = (e, t) => w.promise(() => e.store.update(F.tableName, t.id, t.patch)), er = (e, t) => w.promise(() => e.store.delete(F.tableName, t.id)), tr = "aiFlows", nr = (e = {}) => {
1700
+ let t = Le({
1701
+ base: tr,
1665
1702
  alias: e.alias
1666
1703
  });
1667
- bt(e.humanReviewTimeoutMs === void 0 ? {} : { humanReviewTimeoutMs: e.humanReviewTimeoutMs }), Ve({
1704
+ Ct(e.humanReviewTimeoutMs === void 0 ? {} : { humanReviewTimeoutMs: e.humanReviewTimeoutMs }), Ue({
1668
1705
  source: "plugin",
1669
- table: L.tableName,
1706
+ table: I.tableName,
1670
1707
  timeColumn: "createdAt",
1671
- ttlMs: e.runsTtlMs ?? Ct(process.env.VOLTRO_AI_FLOW_RUNS_TTL_HOURS, 2160),
1672
- envVar: gt,
1708
+ ttlMs: e.runsTtlMs ?? Et(process.env.VOLTRO_AI_FLOW_RUNS_TTL_HOURS, 2160),
1709
+ envVar: yt,
1673
1710
  label: "ai flow runs",
1674
- where: ze("status", [
1711
+ where: Ve("status", [
1675
1712
  "succeeded",
1676
1713
  "failed",
1677
1714
  "cancelled"
@@ -1689,7 +1726,7 @@ var Vt = (e, t = {}) => {
1689
1726
  if (!o) return a(503, "store not bound yet");
1690
1727
  let s = await o.query({
1691
1728
  table: e,
1692
- predicate: n === void 0 ? void 0 : D("id", n),
1729
+ predicate: n === void 0 ? void 0 : E("id", n),
1693
1730
  order: [{
1694
1731
  column: "createdAt",
1695
1732
  direction: "desc"
@@ -1730,14 +1767,14 @@ var Vt = (e, t = {}) => {
1730
1767
  handler: (e) => w.promise(async () => {
1731
1768
  let t = r.current;
1732
1769
  if (!t) return a(503, "store not bound yet");
1733
- let o = s(e.url, Math.min(200, n)), c = [...ot()].sort((e, t) => e.name < t.name ? -1 : +(e.name > t.name)), l = c.slice(0, o).map((e) => ({
1770
+ let o = s(e.url, Math.min(200, n)), c = [...P()].sort((e, t) => e.name < t.name ? -1 : +(e.name > t.name)), l = c.slice(0, o).map((e) => ({
1734
1771
  id: e.name,
1735
1772
  name: e.name,
1736
1773
  mode: e.mode,
1737
1774
  definitionSource: "code"
1738
1775
  })), u = l.length === o ? [] : await t.query({
1739
1776
  table: "_voltro_ai_flows",
1740
- predicate: c.length === 0 ? void 0 : Be("id", c.map((e) => e.name)),
1777
+ predicate: c.length === 0 ? void 0 : He("id", c.map((e) => e.name)),
1741
1778
  order: [{
1742
1779
  column: "createdAt",
1743
1780
  direction: "desc"
@@ -1765,16 +1802,16 @@ var Vt = (e, t = {}) => {
1765
1802
  description: "List recent run summaries (`?take=` bounded); `?runId=` reads one run with payloads and steps.",
1766
1803
  handler: (e) => o("_voltro_ai_flow_runs", s(e.url, Math.min(100, n)), new URL(e.url, "http://inspect.local").searchParams.get("runId") ?? void 0)
1767
1804
  }];
1768
- return Fe({
1805
+ return Ie({
1769
1806
  name: t,
1770
- baseName: Kn,
1807
+ baseName: tr,
1771
1808
  description: "AI Flows — durable multi-step AI pipelines (deterministic + agentic) with human-in-the-loop, chaining, and cadence. Code-first (defineFlow) or data-driven.",
1772
1809
  permissions: [
1773
1810
  "store:write",
1774
1811
  "inspect:read",
1775
1812
  "store:changes:read"
1776
1813
  ],
1777
- ...e.tables === !1 ? {} : { extendSchema: { tables: ct } },
1814
+ ...e.tables === !1 ? {} : { extendSchema: { tables: dt } },
1778
1815
  inspectEndpoints: c,
1779
1816
  bindDataStore: (e) => {
1780
1817
  r.current = e;
@@ -1787,14 +1824,14 @@ var Vt = (e, t = {}) => {
1787
1824
  if (n === void 0) return;
1788
1825
  let i = t.payload, a = (typeof i == "string" ? JSON.parse(i) : i)?.runId;
1789
1826
  if (typeof a != "string") return;
1790
- let o = (yield* w.promise(() => n.query(A(L).where(D("id", a)).descriptor)))[0];
1827
+ let o = (yield* w.promise(() => n.query(k(I).where(E("id", a)).descriptor)))[0];
1791
1828
  if (o === void 0) return;
1792
1829
  let s = o.status, c = t.executionId, l = o.workflowStart;
1793
- s === "pending" && l?.status === "queued" && typeof c == "string" && c.length > 0 && (yield* w.promise(() => n.update(L.tableName, a, { workflowStart: ut(c) })));
1830
+ s === "pending" && l?.status === "queued" && typeof c == "string" && c.length > 0 && (yield* w.promise(() => n.update(I.tableName, a, { workflowStart: pt(c) })));
1794
1831
  let u = e.old?.status === "cancelled";
1795
1832
  if (e.op !== "update" || t.status !== "cancelled" || u || s === "cancelled" || s === "succeeded" || s === "failed") return;
1796
1833
  let d = (/* @__PURE__ */ new Date()).toISOString(), f = typeof o.cancelledAt == "string" ? o.cancelledAt : d;
1797
- yield* w.promise(() => n.update(L.tableName, a, {
1834
+ yield* w.promise(() => n.update(I.tableName, a, {
1798
1835
  status: "cancelled",
1799
1836
  cancelledAt: f,
1800
1837
  completedAt: d
@@ -1803,4 +1840,4 @@ var Vt = (e, t = {}) => {
1803
1840
  });
1804
1841
  };
1805
1842
  //#endregion
1806
- export { _e as BriefField, pe as ChainPending, g as ConditionOp, he as CostCompleteness, b as CostSource, gt as FLOW_RUNS_TTL_ENV, ht as FLOW_RUNS_TTL_HOURS_DEFAULT, e as FLOW_RUN_WORKFLOW, ie as FlowCadence, x as FlowCancelReceipt, ge as FlowChain, ae as FlowMode, de as FlowReviewInput, ve as FlowReviewReceipt, y as FlowStartReceipt, oe as FlowStatus, me as FlowStep, t as HUMAN_RESPONSE_SIGNAL_PREFIX, mt as HUMAN_REVIEW_TIMEOUT_ENV, pt as HUMAN_REVIEW_TIMEOUT_HOURS_DEFAULT, fe as HumanResponse, ce as Json, _t as MAX_CHAIN_DEPTH_DEFAULT, vt as MAX_CHAIN_DEPTH_ENV, se as MAX_STEPS_DEFAULT, re as MAX_STEPS_MAX, ye as MAX_STEPS_MIN, Se as MediaArtifact, v as MediaArtifacts, xe as MediaInputSlot, te as MediaInputs, o as MediaReceipt, be as Modality, ne as ReviewMode, c as ReviewOption, s as RunReview, h as RunSource, ue as RunStatus, i as RunStep, le as RunStepStatus, Ce as StepCondition, p as StepType, m as StepUsage, ee as Visibility, ut as admittedStartHandle, L as aiFlowRunsTable, qn as aiFlowsPlugin, I as aiFlowsTable, ct as aiFlowsTables, dn as buildFlowRunExecute, je as cadenceMatches, Ln as cancelFlow, l as clampMaxSteps, st as clearRegistry, Ot as collectRefs, Un as createFlow, gn as cronRequestId, hn as defineFlow, Gn as deleteFlow, a as describeCondition, _ as evaluateCondition, jt as flowSegments, fn as flowStep, xt as getAiFlowsDefaults, Vn as getFlow, at as getRegisteredFlow, r as humanResponseSignalName, kt as interpolate, u as isTruthy, Fn as launchFlow, Hn as listFlows, ot as listRegisteredFlows, jn as makeMediaGenerator, Ae as nextRuns, Mt as nonContiguousGroups, d as normalizeFlow, ft as reconcileFlowStarts, it as registerFlow, St as resetAiFlowsDefaults, Tt as resolveHumanReviewTimeoutMs, tn as resolveIr, Et as resolveMaxChainDepth, Bn as respondToFlow, In as retryFlow, vn as runCadenceTick, f as sanitizeOutputKey, bt as setAiFlowsDefaults, At as unresolvedRefs, Wn as updateFlow, mn as validateFlow, zn as waitingStepIndex };
1843
+ export { _e as BriefField, pe as ChainPending, te as ConditionOp, he as CostCompleteness, b as CostSource, yt as FLOW_RUNS_TTL_ENV, vt as FLOW_RUNS_TTL_HOURS_DEFAULT, e as FLOW_RUN_WORKFLOW, ne as FlowCadence, x as FlowCancelReceipt, ge as FlowChain, ie as FlowMode, de as FlowReviewInput, ve as FlowReviewReceipt, ae as FlowStartReceipt, oe as FlowStatus, me as FlowStep, t as HUMAN_RESPONSE_SIGNAL_PREFIX, _t as HUMAN_REVIEW_TIMEOUT_ENV, gt as HUMAN_REVIEW_TIMEOUT_HOURS_DEFAULT, fe as HumanResponse, ce as Json, bt as MAX_CHAIN_DEPTH_DEFAULT, xt as MAX_CHAIN_DEPTH_ENV, se as MAX_STEPS_DEFAULT, y as MAX_STEPS_MAX, ye as MAX_STEPS_MIN, Se as MediaArtifact, re as MediaArtifacts, xe as MediaInputSlot, g as MediaInputs, o as MediaReceipt, be as Modality, _ as ReviewMode, c as ReviewOption, s as RunReview, h as RunSource, ue as RunStatus, i as RunStep, le as RunStepStatus, Ce as StepCondition, p as StepType, m as StepUsage, ee as Visibility, pt as admittedStartHandle, I as aiFlowRunsTable, nr as aiFlowsPlugin, F as aiFlowsTable, dt as aiFlowsTables, vn as buildFlowRunExecute, je as cadenceMatches, Kn as cancelFlow, l as clampMaxSteps, ut as clearRegistry, jt as collectRefs, Qn as createFlow, wn as cronRequestId, Sn as defineFlow, er as deleteFlow, a as describeCondition, v as evaluateCondition, Pt as flowSegments, yn as flowStep, wt as getAiFlowsDefaults, Xn as getFlow, lt as getRegisteredFlow, r as humanResponseSignalName, Mt as interpolate, u as isTruthy, Wn as launchFlow, Zn as listFlows, P as listRegisteredFlows, Bn as makeMediaGenerator, Ae as nextRuns, Ft as nonContiguousGroups, d as normalizeFlow, ht as reconcileFlowStarts, ct as registerFlow, Tt as resetAiFlowsDefaults, Ot as resolveHumanReviewTimeoutMs, J as resolveIr, kt as resolveMaxChainDepth, Yn as respondToFlow, Gn as retryFlow, En as runCadenceTick, f as sanitizeOutputKey, Ct as setAiFlowsDefaults, Nt as unresolvedRefs, $n as updateFlow, xn as validateFlow, Jn as waitingStepIndex };