@voltro/ai 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1263 @@
1
+ import { a as e, c as t, d as n, f as r, g as i, h as a, i as o, l as s, m as c, n as l, o as u, p as d, r as f, s as p, t as ee, u as te } from "./provider-BOC5wBxx.js";
2
+ import { AgentErrorCode as ne, AgentEvent as re, SeqEvent as ie } from "./events.js";
3
+ import { a as ae, i as oe, n as se, o as m, r as ce, s as h, t as le } from "./agentDescriptor-DCd4F9zj.js";
4
+ import { createGateway as ue, gateway as de } from "@ai-sdk/gateway";
5
+ import { Output as fe, cosineSimilarity as pe, embed as me, embedMany as he, generateImage as ge, generateObject as _e, generateSpeech as ve, generateText as ye, jsonSchema as g, rerank as be, stepCountIs as xe, streamText as Se, tool as Ce } from "ai";
6
+ import { Chunk as _, Context as we, Duration as Te, Effect as v, JSONSchema as Ee, Metric as y, MetricBoundaries as De, Option as b, Runtime as Oe, Schema as x, Stream as S } from "effect";
7
+ import { and as C, boolean as ke, contains as Ae, eq as w, generateId as je, gt as Me, gte as Ne, id as T, inSet as Pe, integer as E, json as Fe, lt as Ie, lte as Le, neq as Re, queryFor as ze, registerRetention as Be, retentionTtlMsFromEnv as Ve, table as D, text as O, timestamp as k } from "@voltro/database";
8
+ //#region src/tools.ts
9
+ var He = (e, t) => e(t), Ue = Symbol.for("@voltro/ai/Tool"), We = (e) => ({
10
+ ...e,
11
+ [Ue]: !0
12
+ }), Ge = (e) => typeof e == "object" && !!e && e[Ue] === !0, Ke = (e) => {
13
+ let t = e.default;
14
+ if (typeof t != "function") return 0;
15
+ let n = 0;
16
+ for (let r of Object.values(e)) Ge(r) && r.execute === void 0 && r.handler === void 0 && (r.handler = t, n += 1);
17
+ return n;
18
+ }, qe = (e, t) => {
19
+ let n = t ?? Oe.defaultRuntime;
20
+ return Oe.runPromise(n)(e);
21
+ }, Je = (e, t, n) => n ? e.pipe(v.timeoutFail({
22
+ duration: `${n} millis`,
23
+ onTimeout: () => /* @__PURE__ */ Error(`tool '${t}' timed out`)
24
+ })) : e, Ye = (e, t, n) => {
25
+ if (e.execute) return qe(Je(He(e.execute, t), e.name, e.timeoutMs), n.runtime);
26
+ if (e.handler) {
27
+ let r = e.handler, i = r(t, n);
28
+ return v.isEffect(i) ? qe(Je(i, e.name, e.timeoutMs), n.runtime) : i;
29
+ }
30
+ return Promise.reject(/* @__PURE__ */ Error(`tool '${e.name}' has neither execute nor handler`));
31
+ }, Xe = (e) => {
32
+ let t = Ee.make(e);
33
+ return t && t.type === "object" ? t : {
34
+ type: "object",
35
+ properties: {},
36
+ additionalProperties: !1
37
+ };
38
+ }, A = (e, t = { store: void 0 }) => {
39
+ let n = {};
40
+ for (let [r, i] of Object.entries(e)) n[i.name || r] = Ce({
41
+ description: i.description,
42
+ inputSchema: g(Xe(i.input)),
43
+ execute: async (e) => {
44
+ let n = await v.runPromise(x.decodeUnknown(i.input)(e)), r = await Ye(i, n, t);
45
+ return i.output ? v.runPromise(x.decodeUnknown(i.output)(r)) : r;
46
+ }
47
+ });
48
+ return n;
49
+ }, Ze = {
50
+ "claude-opus-4-8": {
51
+ inputPer1M: 15,
52
+ outputPer1M: 75
53
+ },
54
+ "claude-opus-4-6": {
55
+ inputPer1M: 15,
56
+ outputPer1M: 75
57
+ },
58
+ "claude-sonnet-4-6": {
59
+ inputPer1M: 3,
60
+ outputPer1M: 15
61
+ },
62
+ "claude-haiku-4-5": {
63
+ inputPer1M: 1,
64
+ outputPer1M: 5
65
+ },
66
+ "claude-haiku-4-5-20251001": {
67
+ inputPer1M: 1,
68
+ outputPer1M: 5
69
+ },
70
+ "gpt-5.5": {
71
+ inputPer1M: 5,
72
+ outputPer1M: 30
73
+ },
74
+ "gpt-4o": {
75
+ inputPer1M: 2.5,
76
+ outputPer1M: 10
77
+ },
78
+ "gpt-4o-mini": {
79
+ inputPer1M: .15,
80
+ outputPer1M: .6
81
+ },
82
+ "gemini-2.5-pro": {
83
+ inputPer1M: 1.25,
84
+ outputPer1M: 10
85
+ },
86
+ "gemini-2.5-flash": {
87
+ inputPer1M: .3,
88
+ outputPer1M: 2.5
89
+ },
90
+ "gemini-2.0-flash": {
91
+ inputPer1M: .1,
92
+ outputPer1M: .4
93
+ }
94
+ }, j = {}, Qe = (e) => {
95
+ let t = j;
96
+ return j = { ...e }, t;
97
+ }, $e = () => ({
98
+ ...Ze,
99
+ ...j
100
+ }), et = (e) => {
101
+ let t = $e();
102
+ if (t[e] !== void 0) return t[e];
103
+ let n = e.indexOf("/");
104
+ if (n > 0) {
105
+ let r = e.slice(n + 1);
106
+ if (t[r] !== void 0) return t[r];
107
+ }
108
+ }, M = (e, t) => {
109
+ let n = e.inputTokens ?? 0, r = e.outputTokens ?? 0;
110
+ if (t.actualCostUsd !== void 0) {
111
+ let e = n + r, i = e > 0 ? n / e : 0;
112
+ return {
113
+ inputTokens: n,
114
+ outputTokens: r,
115
+ inputCostUsd: t.actualCostUsd * i,
116
+ outputCostUsd: t.actualCostUsd * (1 - i),
117
+ totalCostUsd: t.actualCostUsd,
118
+ costSource: "gateway"
119
+ };
120
+ }
121
+ let i = t.price ?? et(t.model) ?? {
122
+ inputPer1M: 0,
123
+ outputPer1M: 0
124
+ }, a = n / 1e6 * i.inputPer1M, o = r / 1e6 * i.outputPer1M;
125
+ return {
126
+ inputTokens: n,
127
+ outputTokens: r,
128
+ inputCostUsd: a,
129
+ outputCostUsd: o,
130
+ totalCostUsd: a + o,
131
+ costSource: "estimated"
132
+ };
133
+ }, N = "_voltro_ai_usage", tt = D(N, {
134
+ id: T({ prefix: "aiu" }),
135
+ tenantId: O().nullable(),
136
+ provider: O(),
137
+ model: O(),
138
+ operation: O(),
139
+ agent: O().nullable(),
140
+ inputTokens: E().default(0),
141
+ outputTokens: E().default(0),
142
+ costMicroUsd: E().default(0),
143
+ costSource: O().default("estimated"),
144
+ calledAt: k().default("now")
145
+ }).index(["tenantId"]).reactive(), nt = (e) => {
146
+ let t = e?.gateway?.cost, n = typeof t == "number" ? t : typeof t == "string" ? Number(t) : NaN;
147
+ return Number.isFinite(n) ? n : void 0;
148
+ }, rt = (e, t) => (Be({
149
+ table: N,
150
+ timeColumn: "calledAt",
151
+ ttlMs: Ve(process.env.VOLTRO_AI_USAGE_TTL_HOURS, 24 * 365)
152
+ }), v.promise(async () => {
153
+ let n = M(t.usage, {
154
+ model: t.model,
155
+ ...t.price === void 0 ? {} : { price: t.price },
156
+ ...t.actualCostUsd === void 0 ? {} : { actualCostUsd: t.actualCostUsd }
157
+ });
158
+ return await e.insert(N, {
159
+ tenantId: t.tenantId ?? null,
160
+ provider: t.provider,
161
+ model: t.model,
162
+ operation: t.operation,
163
+ agent: t.agent ?? null,
164
+ inputTokens: n.inputTokens,
165
+ outputTokens: n.outputTokens,
166
+ costMicroUsd: Math.round(n.totalCostUsd * 1e6),
167
+ costSource: n.costSource,
168
+ calledAt: t.calledAt ?? /* @__PURE__ */ new Date()
169
+ }), n;
170
+ })), it = (e, t = {}) => v.promise(async () => {
171
+ let n = [...t.tenantId === void 0 ? [] : [w("tenantId", t.tenantId)], ...t.since === void 0 ? [] : [Ne("calledAt", t.since)]], r = ze(tt), i = n.length === 0 ? r : r.where(n.length === 1 ? n[0] : C(...n));
172
+ return (await e.query(i.descriptor)).reduce((e, t) => e + (Number(t.costMicroUsd) || 0), 0) / 1e6;
173
+ }), at = class extends x.TaggedError()("AiBudgetExceeded", {
174
+ tenantId: x.NullOr(x.String),
175
+ limitUsd: x.Number,
176
+ spentUsd: x.Number,
177
+ attemptedUsd: x.Number
178
+ }) {}, P = "_voltro_ai_budget", ot = D(P, {
179
+ id: T({ prefix: "aib" }),
180
+ bucket: O().maxLength(191),
181
+ tenantId: O().nullable(),
182
+ reservedMicroUsd: E().default(0),
183
+ updatedAt: k().default("now")
184
+ }).unique("byAiBudgetBucket", ["bucket"]), st = (e, t) => `${e ?? "global"}::${t === void 0 ? "all" : String(t.getTime())}`, ct = 32, lt = (e, t) => v.gen(function* () {
185
+ Be({
186
+ table: P,
187
+ timeColumn: "updatedAt",
188
+ ttlMs: Ve(process.env.VOLTRO_AI_USAGE_TTL_HOURS, 24 * 365)
189
+ });
190
+ let n = t.addUsd ?? 0, r = Math.round(n * 1e6), i = Math.round(t.limitUsd * 1e6), a = st(t.tenantId, t.since), o = t.tenantId ?? null, s = (e) => new at({
191
+ tenantId: o,
192
+ limitUsd: t.limitUsd,
193
+ spentUsd: e / 1e6,
194
+ attemptedUsd: n
195
+ }), c = yield* v.promise(async () => {
196
+ for (let t = 0; t < ct; t++) {
197
+ t > 0 && await new Promise((e) => setTimeout(e, t));
198
+ let n = (await e.query(ze(ot).where(w("bucket", a)).descriptor))[0], s = n && Number(n.reservedMicroUsd) || 0;
199
+ if (s + r > i) return {
200
+ ok: !1,
201
+ reservedMicro: s
202
+ };
203
+ if (r === 0) return { ok: !0 };
204
+ if (n) {
205
+ if (await e.updateMany("_voltro_ai_budget", {
206
+ reservedMicroUsd: s + r,
207
+ updatedAt: /* @__PURE__ */ new Date()
208
+ }, { where: C(w("id", String(n.id)), w("reservedMicroUsd", s)) }) === 1) return { ok: !0 };
209
+ } else {
210
+ let t = je({
211
+ kind: "typeid",
212
+ prefix: "aib"
213
+ }, P), n = await e.insertIgnore(P, {
214
+ id: t,
215
+ bucket: a,
216
+ tenantId: o,
217
+ reservedMicroUsd: r,
218
+ updatedAt: /* @__PURE__ */ new Date()
219
+ }, { conflictColumns: ["bucket"] });
220
+ if (String(n.id) === t) return { ok: !0 };
221
+ }
222
+ }
223
+ throw Error(`requireAiBudget: contention on bucket '${a}' exceeded ${ct} attempts`);
224
+ });
225
+ if (!c.ok) return yield* v.fail(s(c.reservedMicro));
226
+ }), ut = De.exponential({
227
+ start: .001,
228
+ factor: 2,
229
+ count: 16
230
+ }), F = y.counter("voltro_ai_calls_total", { description: "Total AI provider calls (generate + stream)." }), dt = y.counter("voltro_ai_call_errors_total", { description: "AI provider calls that errored." }), I = y.histogram("voltro_ai_call_duration_seconds", ut, "AI provider call duration in seconds."), ft = y.counter("voltro_ai_input_tokens_total", {
231
+ description: "Total prompt (input) tokens across AI calls.",
232
+ incremental: !0
233
+ }), pt = y.counter("voltro_ai_output_tokens_total", {
234
+ description: "Total completion (output) tokens across AI calls.",
235
+ incremental: !0
236
+ }), mt = y.counter("voltro_ai_cost_microusd_total", {
237
+ description: "Total estimated AI spend in micro-USD (USD × 1e6).",
238
+ incremental: !0
239
+ }), L = (e, t) => ({
240
+ provider: e.name,
241
+ model: e.model ?? e.name,
242
+ operation: t
243
+ }), R = (e, t, n) => e.pipe(v.tagMetrics("provider", t.provider), v.tagMetrics("model", t.model), v.tagMetrics("operation", t.operation), v.tagMetrics("status", n)), ht = (e, t) => {
244
+ let n = t.inputTokens ?? 0, r = t.outputTokens ?? 0, i = M({
245
+ inputTokens: n,
246
+ outputTokens: r
247
+ }, { model: e.model }), a = Math.round(i.totalCostUsd * 1e6);
248
+ return v.all([
249
+ R(y.incrementBy(ft, n), e, "ok"),
250
+ R(y.incrementBy(pt, r), e, "ok"),
251
+ R(y.incrementBy(mt, a), e, "ok")
252
+ ], { discard: !0 });
253
+ }, z = (e, t, n) => v.gen(function* () {
254
+ let r = yield* v.clockWith((e) => e.currentTimeMillis);
255
+ return yield* n.pipe(v.tap((n) => ht(e, t(n))), v.tap(() => R(y.increment(F), e, "ok").pipe(v.zipRight(v.clockWith((e) => e.currentTimeMillis).pipe(v.flatMap((t) => R(y.update(I, (t - r) / 1e3), e, "ok")))))), v.tapError(() => R(y.increment(F), e, "error").pipe(v.zipRight(R(y.increment(dt), e, "error")), v.zipRight(v.clockWith((e) => e.currentTimeMillis).pipe(v.flatMap((t) => R(y.update(I, (t - r) / 1e3), e, "error")))))), v.withSpan("voltro.ai.call", { attributes: {
256
+ "ai.provider": e.provider,
257
+ "ai.model": e.model,
258
+ "ai.operation": e.operation
259
+ } }));
260
+ }), gt = (e, t) => {
261
+ let n = Date.now();
262
+ return t.pipe(S.tap((t) => t._tag === "done" ? R(y.increment(F), e, "ok").pipe(v.zipRight(R(y.update(I, (Date.now() - n) / 1e3), e, "ok")), v.zipRight(ht(e, t.usage ?? {}))) : t._tag === "error" ? R(y.increment(F), e, "error").pipe(v.zipRight(R(y.increment(dt), e, "error")), v.zipRight(R(y.update(I, (Date.now() - n) / 1e3), e, "error"))) : v.void), S.withSpan("voltro.ai.call", { attributes: {
263
+ "ai.provider": e.provider,
264
+ "ai.model": e.model,
265
+ "ai.operation": e.operation
266
+ } }));
267
+ }, B = class extends x.TaggedError()("AiError", {
268
+ reason: x.Literal("generation", "decode"),
269
+ message: x.String
270
+ }) {}, V = (e, t, n) => {
271
+ let r = [e, ...t ?? []], i = (e) => n(r[e]).pipe(v.catchTag("AiError", (t) => t.reason === "generation" && e + 1 < r.length ? i(e + 1) : v.fail(t)));
272
+ return i(0);
273
+ }, _t = (t) => V(t.provider ?? f(), t.fallbacks, (n) => z(L(n, "generateText"), (e) => e.usage, v.tryPromise({
274
+ try: async () => {
275
+ let r = await ye({
276
+ model: e(n),
277
+ prompt: t.prompt,
278
+ ...t.system === void 0 ? {} : { system: t.system },
279
+ ...t.maxTokens === void 0 ? {} : { maxOutputTokens: t.maxTokens },
280
+ ...t.providerOptions === void 0 ? {} : { providerOptions: t.providerOptions }
281
+ });
282
+ return {
283
+ text: r.text,
284
+ usage: {
285
+ inputTokens: r.usage.inputTokens,
286
+ outputTokens: r.usage.outputTokens,
287
+ totalTokens: r.usage.totalTokens
288
+ },
289
+ providerMetadata: r.providerMetadata
290
+ };
291
+ },
292
+ catch: (e) => new B({
293
+ reason: "generation",
294
+ message: String(e?.message ?? e)
295
+ })
296
+ }))), vt = (e, t) => v.gen(function* () {
297
+ let n = Ee.make(e);
298
+ if (n?.type !== "object") {
299
+ let e = n?.anyOf === void 0 ? `type:${JSON.stringify(n?.type ?? null)}` : "anyOf (e.g. Schema.Struct({}) or a union)";
300
+ return yield* v.fail(new B({
301
+ reason: "generation",
302
+ message: `${t}: the output schema must render as a top-level JSON object (type:"object"), but got ${e}. Use a Schema.Struct({ ... }) as the output schema — wrap arrays/scalars in a field (e.g. Schema.Struct({ items: Schema.Array(...) })).`
303
+ }));
304
+ }
305
+ return n;
306
+ }), yt = (t) => v.gen(function* () {
307
+ let n = yield* vt(t.schema, "generateObject");
308
+ return yield* V(t.provider ?? f(), t.fallbacks, (r) => z(L(r, "generateObject"), (e) => e.usage, v.gen(function* () {
309
+ let i = e(r), a = yield* v.tryPromise({
310
+ try: () => _e({
311
+ model: i,
312
+ schema: g(n),
313
+ prompt: t.prompt,
314
+ ...t.system === void 0 ? {} : { system: t.system },
315
+ ...t.maxTokens === void 0 ? {} : { maxOutputTokens: t.maxTokens },
316
+ ...t.providerOptions === void 0 ? {} : { providerOptions: t.providerOptions }
317
+ }),
318
+ catch: (e) => new B({
319
+ reason: "generation",
320
+ message: String(e?.message ?? e)
321
+ })
322
+ });
323
+ return {
324
+ object: yield* x.decodeUnknown(t.schema)(a.object).pipe(v.mapError((e) => new B({
325
+ reason: "decode",
326
+ message: `model output failed schema decode: ${String(e)}`
327
+ }))),
328
+ usage: {
329
+ inputTokens: a.usage.inputTokens,
330
+ outputTokens: a.usage.outputTokens,
331
+ totalTokens: a.usage.totalTokens
332
+ },
333
+ providerMetadata: a.providerMetadata
334
+ };
335
+ })));
336
+ }), bt = (t) => v.gen(function* () {
337
+ let n = yield* v.runtime(), r = yield* vt(t.schema, "generateObjectWithTools"), i = {
338
+ store: void 0,
339
+ ...t.toolContext,
340
+ runtime: n
341
+ }, a = A(t.tools, i);
342
+ return yield* V(t.provider ?? f(), t.fallbacks, (n) => z(L(n, "generateObjectWithTools"), (e) => e.usage, v.gen(function* () {
343
+ let i = e(n), o = yield* v.tryPromise({
344
+ try: () => ye({
345
+ model: i,
346
+ prompt: t.prompt,
347
+ tools: a,
348
+ stopWhen: xe(t.maxSteps ?? 8),
349
+ output: fe.object({ schema: g(r) }),
350
+ ...t.system === void 0 ? {} : { system: t.system },
351
+ ...t.maxTokens === void 0 ? {} : { maxOutputTokens: t.maxTokens },
352
+ ...t.providerOptions === void 0 ? {} : { providerOptions: t.providerOptions }
353
+ }),
354
+ catch: (e) => new B({
355
+ reason: "generation",
356
+ message: String(e?.message ?? e)
357
+ })
358
+ });
359
+ return {
360
+ object: yield* x.decodeUnknown(t.schema)(o.output).pipe(v.mapError((e) => new B({
361
+ reason: "decode",
362
+ message: `model output failed schema decode: ${String(e)}`
363
+ }))),
364
+ usage: {
365
+ inputTokens: o.usage.inputTokens,
366
+ outputTokens: o.usage.outputTokens,
367
+ totalTokens: o.usage.totalTokens
368
+ },
369
+ providerMetadata: o.providerMetadata
370
+ };
371
+ })));
372
+ }), xt = class extends we.Tag("@voltro/AiService")() {}, St = {
373
+ generateText: (e) => _t(e),
374
+ generateObject: (e) => yt(e)
375
+ }, Ct = (e) => e === void 0 ? {} : { providerOptions: e }, H = (e) => new B({
376
+ reason: "generation",
377
+ message: String(e?.message ?? e)
378
+ }), wt = (e) => {
379
+ let t = e.provider ?? f();
380
+ return z(L(t, "generateImage"), (e) => e.usage ?? {}, v.tryPromise({
381
+ try: async () => {
382
+ let n = await ge({
383
+ model: o(t),
384
+ prompt: e.prompt,
385
+ ...e.n === void 0 ? {} : { n: e.n },
386
+ ...e.size === void 0 ? {} : { size: e.size },
387
+ ...e.aspectRatio === void 0 ? {} : { aspectRatio: e.aspectRatio },
388
+ ...Ct(e.providerOptions)
389
+ });
390
+ return {
391
+ images: n.images.map((e) => ({
392
+ data: e.uint8Array,
393
+ mediaType: e.mediaType
394
+ })),
395
+ usage: {
396
+ inputTokens: n.usage.inputTokens,
397
+ outputTokens: n.usage.outputTokens,
398
+ totalTokens: n.usage.totalTokens
399
+ },
400
+ providerMetadata: n.providerMetadata
401
+ };
402
+ },
403
+ catch: H
404
+ }));
405
+ }, Tt = (e) => {
406
+ let t = e.provider ?? f();
407
+ return z(L(t, "generateSpeech"), () => ({}), v.tryPromise({
408
+ try: async () => {
409
+ let n = await ve({
410
+ model: u(t),
411
+ text: e.text,
412
+ ...e.voice === void 0 ? {} : { voice: e.voice },
413
+ ...e.outputFormat === void 0 ? {} : { outputFormat: e.outputFormat },
414
+ ...e.instructions === void 0 ? {} : { instructions: e.instructions },
415
+ ...e.speed === void 0 ? {} : { speed: e.speed },
416
+ ...e.language === void 0 ? {} : { language: e.language },
417
+ ...Ct(e.providerOptions)
418
+ });
419
+ return {
420
+ audio: {
421
+ data: n.audio.uint8Array,
422
+ mediaType: n.audio.mediaType
423
+ },
424
+ providerMetadata: n.providerMetadata
425
+ };
426
+ },
427
+ catch: H
428
+ }));
429
+ }, Et = (e) => ({
430
+ type: "url",
431
+ url: e
432
+ }), Dt = (e) => Uint8Array.from(Buffer.from(e, "base64")), Ot = (e) => {
433
+ let t = e.provider ?? f();
434
+ return z(L(t, "generateVideo"), () => ({}), v.tryPromise({
435
+ try: async () => {
436
+ let n = await p(t).doGenerate({
437
+ prompt: e.prompt,
438
+ n: 1,
439
+ aspectRatio: e.params?.aspectRatio,
440
+ resolution: e.params?.resolution,
441
+ duration: e.params?.durationSeconds,
442
+ fps: e.params?.fps,
443
+ seed: e.params?.seed,
444
+ image: e.inputs?.image === void 0 ? void 0 : Et(e.inputs.image),
445
+ frameImages: void 0,
446
+ inputReferences: e.inputs?.references?.map(Et),
447
+ generateAudio: void 0,
448
+ providerOptions: e.providerOptions ?? {}
449
+ }), r = n.videos[0];
450
+ if (r === void 0) throw Error("video model returned no videos");
451
+ return {
452
+ video: r.type === "url" ? {
453
+ url: r.url,
454
+ mediaType: r.mediaType
455
+ } : r.type === "base64" ? {
456
+ data: Dt(r.data),
457
+ mediaType: r.mediaType
458
+ } : {
459
+ data: r.data,
460
+ mediaType: r.mediaType
461
+ },
462
+ providerMetadata: n.providerMetadata
463
+ };
464
+ },
465
+ catch: H
466
+ }));
467
+ }, kt = (e) => RegExp("^" + e.split("*").map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$"), At = (e, t) => t instanceof RegExp ? t.test(e) : t.some((t) => kt(t).test(e)), U = (e, t) => !(t.deny !== void 0 && At(e, t.deny) || t.allow !== void 0 && !At(e, t.allow)), W = (e) => e === "mutation" || e === "action", jt = (e) => ({
468
+ id: e,
469
+ via: "agent"
470
+ }), G = (e, t) => {
471
+ let n = e.exposeAsTool;
472
+ if (n === void 0 || n === !1 || n === !0) return null;
473
+ let r = W(e.kind), i = n.confirm ?? (r && (t.requireConfirmForWrites ?? !0));
474
+ return {
475
+ description: n.description,
476
+ confirm: i,
477
+ ...n.maxPerRun === void 0 ? {} : { maxPerRun: n.maxPerRun }
478
+ };
479
+ }, Mt = (e, t = {}) => e.filter((e) => U(e.descriptor.name, t)).map((e) => ({
480
+ entry: e,
481
+ exposure: G(e.descriptor, t)
482
+ })).filter((e) => e.exposure !== null).map(({ entry: e, exposure: t }) => ({
483
+ name: e.descriptor.name,
484
+ kind: e.descriptor.kind,
485
+ description: t.description,
486
+ write: W(e.descriptor.kind),
487
+ confirm: t.confirm,
488
+ ...t.maxPerRun === void 0 ? {} : { maxPerRun: t.maxPerRun }
489
+ })).sort((e, t) => e.name.localeCompare(t.name)), Nt = (e, t = {}) => e.filter((e) => U(e.descriptor.name, t)).filter((e) => G(e.descriptor, t) !== null).filter((e) => t.includeWrites === !0 || !W(e.descriptor.kind)).map((e) => {
490
+ let n = G(e.descriptor, t);
491
+ return We({
492
+ name: e.descriptor.name,
493
+ description: n.description,
494
+ input: e.descriptor.input,
495
+ ...e.descriptor.output === void 0 ? {} : { output: e.descriptor.output },
496
+ handler: (t) => Promise.resolve(e.invoke(t))
497
+ });
498
+ }), K = /* @__PURE__ */ new Map(), Pt = (e) => {
499
+ let t = K.get(e);
500
+ if (t) return t;
501
+ let n = new AbortController();
502
+ return K.set(e, n), n;
503
+ }, Ft = (e) => {
504
+ let t = K.get(e);
505
+ return t ? (K.delete(e), t.abort(), !0) : !1;
506
+ }, It = (e) => K.has(e), Lt = (e) => {
507
+ K.delete(e);
508
+ }, Rt = () => K.size, zt = (e) => {
509
+ let t = e?.name, n = String(e?.message ?? e ?? "");
510
+ return t === "AbortError" || t === "TimeoutError" || /\babort(ed)?\b/i.test(n);
511
+ }, Bt = (e) => {
512
+ switch (e?.type) {
513
+ case "text-delta": return {
514
+ _tag: "token",
515
+ text: e.text ?? e.delta ?? ""
516
+ };
517
+ case "reasoning-delta":
518
+ case "reasoning": return {
519
+ _tag: "reasoning",
520
+ text: e.text ?? e.delta ?? ""
521
+ };
522
+ case "tool-call": return {
523
+ _tag: "toolCall",
524
+ id: e.toolCallId ?? "",
525
+ name: e.toolName ?? "",
526
+ input: e.input
527
+ };
528
+ case "tool-result": return {
529
+ _tag: "toolResult",
530
+ id: e.toolCallId ?? "",
531
+ name: e.toolName ?? "",
532
+ output: e.output
533
+ };
534
+ case "tool-error": return {
535
+ _tag: "toolResult",
536
+ id: e.toolCallId ?? "",
537
+ name: e.toolName ?? "",
538
+ error: String(e.error?.message ?? e.error ?? "tool error")
539
+ };
540
+ case "source": return {
541
+ _tag: "source",
542
+ sourceType: e.sourceType === "document" ? "document" : "url",
543
+ id: e.id ?? "",
544
+ ...e.url === void 0 ? {} : { url: e.url },
545
+ ...e.title === void 0 ? {} : { title: e.title },
546
+ ...e.mediaType === void 0 ? {} : { mediaType: e.mediaType },
547
+ ...e.filename === void 0 ? {} : { filename: e.filename }
548
+ };
549
+ case "file": return e.file ? {
550
+ _tag: "file",
551
+ mediaType: e.file.mediaType,
552
+ data: e.file.base64
553
+ } : null;
554
+ case "abort": return {
555
+ _tag: "error",
556
+ code: "cancelled",
557
+ message: "stream aborted",
558
+ retryable: !1
559
+ };
560
+ case "finish": return {
561
+ _tag: "done",
562
+ finishReason: String(e.finishReason ?? "stop"),
563
+ usage: {
564
+ inputTokens: e.totalUsage?.inputTokens,
565
+ outputTokens: e.totalUsage?.outputTokens,
566
+ totalTokens: e.totalUsage?.totalTokens
567
+ }
568
+ };
569
+ case "error": return {
570
+ _tag: "error",
571
+ code: "provider",
572
+ message: String(e.error),
573
+ retryable: !0
574
+ };
575
+ default: return null;
576
+ }
577
+ }, q = (t) => S.unwrap(v.gen(function* () {
578
+ let n = yield* v.runtime(), r = t.provider ?? f(), i = e(r), a = t.tools ? {
579
+ store: void 0,
580
+ ...t.toolContext,
581
+ runtime: n
582
+ } : t.toolContext, o = t.tools ? A(t.tools, a) : void 0, s = t.streamId === void 0 ? new AbortController() : Pt(t.streamId);
583
+ t.signal !== void 0 && (t.signal.aborted ? s.abort() : t.signal.addEventListener("abort", () => s.abort(), { once: !0 }));
584
+ let c = s.signal, l = Se({
585
+ model: i,
586
+ ...t.messages === void 0 ? { prompt: t.prompt } : { messages: [...t.messages] },
587
+ ...t.system === void 0 ? {} : { system: t.system },
588
+ ...t.maxTokens === void 0 ? {} : { maxOutputTokens: t.maxTokens },
589
+ ...t.providerOptions === void 0 ? {} : { providerOptions: t.providerOptions },
590
+ ...t.maxRetries === void 0 ? {} : { maxRetries: t.maxRetries },
591
+ abortSignal: c,
592
+ ...o ? {
593
+ tools: o,
594
+ stopWhen: xe(t.maxSteps ?? 8)
595
+ } : {}
596
+ });
597
+ return gt(L(r, "streamText"), S.fromAsyncIterable(l.fullStream, (e) => e).pipe(S.map(Bt), S.filter((e) => e !== null), S.catchAll((e) => {
598
+ let t = c.aborted || zt(e);
599
+ return S.make({
600
+ _tag: "error",
601
+ code: t ? "cancelled" : "provider",
602
+ message: t ? "stream aborted" : String(e),
603
+ retryable: !t
604
+ });
605
+ }), S.ensuring(v.sync(() => {
606
+ s.abort(), t.streamId !== void 0 && Lt(t.streamId);
607
+ }))));
608
+ })), Vt = (e) => e._tag === "token" || e._tag === "reasoning" || e._tag === "toolCall" || e._tag === "toolResult" || e._tag === "source" || e._tag === "file" || e._tag === "message", Ht = (e) => e._tag === "done" || e._tag === "error", Ut = (e, t = {}) => {
609
+ let n = Math.max(1, t.maxAttempts ?? 3), r = t.backoffMs ?? 250, i = t.maxBackoffMs ?? 5e3, a = [e.provider, ...e.fallbacks ?? []], o = (t, s) => {
610
+ let c = !1, l = a[t];
611
+ return q(l === void 0 ? e : {
612
+ ...e,
613
+ provider: l
614
+ }).pipe(S.takeUntil(Ht), S.flatMap((e) => {
615
+ if (e._tag === "error" && e.retryable && !c) {
616
+ if (s + 1 < n) {
617
+ let e = Math.min(i, r * 2 ** s);
618
+ return S.unwrap(v.as(v.sleep(Te.millis(e)), o(t, s + 1)));
619
+ }
620
+ if (t + 1 < a.length) return o(t + 1, 0);
621
+ }
622
+ return Vt(e) && (c = !0), S.make(e);
623
+ }, { concurrency: 1 }));
624
+ };
625
+ return o(0, 0);
626
+ }, Wt = (e) => {
627
+ let t = [e.provider, ...e.fallbacks ?? []], n = (r) => {
628
+ let i = !1, a = t[r];
629
+ return q(a === void 0 ? e : {
630
+ ...e,
631
+ provider: a
632
+ }).pipe(S.takeUntil(Ht), S.flatMap((e) => e._tag === "error" && e.retryable && !i && r + 1 < t.length ? n(r + 1) : (Vt(e) && (i = !0), S.make(e)), { concurrency: 1 }));
633
+ };
634
+ return n(0);
635
+ }, Gt = (e, t, n = {}) => {
636
+ let r = n.pollMs ?? 50, i = n.fromSeq ?? 0, a = n.idleTimeoutMs, o = [_.empty(), b.none()];
637
+ return S.paginateChunkEffect({
638
+ cursor: i,
639
+ finishing: !1,
640
+ idleMs: 0
641
+ }, (n) => v.gen(function* () {
642
+ if (n.finishing) return o;
643
+ let i = yield* t.read(e, n.cursor);
644
+ if (i.length > 0) {
645
+ let e = i[i.length - 1].seq;
646
+ return [_.fromIterable(i), b.some({
647
+ cursor: e,
648
+ finishing: !1,
649
+ idleMs: 0
650
+ })];
651
+ }
652
+ if (yield* t.isDone(e)) {
653
+ let r = yield* t.read(e, n.cursor);
654
+ if (r.length === 0) return o;
655
+ let i = r[r.length - 1].seq;
656
+ return [_.fromIterable(r), b.some({
657
+ cursor: i,
658
+ finishing: !0,
659
+ idleMs: 0
660
+ })];
661
+ }
662
+ let s = n.idleMs + r;
663
+ return a !== void 0 && s >= a ? o : (yield* v.sleep(Te.millis(r)), [_.empty(), b.some({
664
+ ...n,
665
+ idleMs: s
666
+ })]);
667
+ }));
668
+ }, Kt = (e, t, n) => {
669
+ let r = 0;
670
+ return n().pipe(S.runForEach((n) => (r += 1, t.append(e, {
671
+ seq: r,
672
+ event: n
673
+ }))), v.ensuring(t.markDone(e)), v.catchAllCause(() => v.void));
674
+ }, qt = (e) => S.unwrap(v.gen(function* () {
675
+ return (yield* e.store.claimProducer(e.streamId)) && (yield* v.forkDaemon(Kt(e.streamId, e.store, e.source))), Gt(e.streamId, e.store, {
676
+ fromSeq: e.fromSeq ?? 0,
677
+ pollMs: e.pollMs ?? 50,
678
+ ...e.idleTimeoutMs === void 0 ? {} : { idleTimeoutMs: e.idleTimeoutMs }
679
+ });
680
+ })), Jt = (e) => qt({
681
+ streamId: e.streamId,
682
+ store: e.store,
683
+ source: () => q(e.options),
684
+ ...e.fromSeq === void 0 ? {} : { fromSeq: e.fromSeq },
685
+ ...e.pollMs === void 0 ? {} : { pollMs: e.pollMs },
686
+ ...e.idleTimeoutMs === void 0 ? {} : { idleTimeoutMs: e.idleTimeoutMs }
687
+ }), Yt = () => {
688
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set(), n = (t) => {
689
+ let n = e.get(t);
690
+ return n || (n = {
691
+ events: [],
692
+ done: !1
693
+ }, e.set(t, n)), n;
694
+ };
695
+ return {
696
+ claimProducer: (e) => v.sync(() => t.has(e) ? !1 : (t.add(e), !0)),
697
+ append: (e, t) => v.sync(() => {
698
+ n(e).events.push(t);
699
+ }),
700
+ read: (e, t) => v.sync(() => n(e).events.filter((e) => e.seq > t)),
701
+ markDone: (e) => v.sync(() => {
702
+ n(e).done = !0;
703
+ }),
704
+ isDone: (e) => v.sync(() => n(e).done)
705
+ };
706
+ }, J = "_voltro_stream_events", Y = "_voltro_stream_state", Xt = D(J, {
707
+ id: T({ prefix: "sev" }),
708
+ streamId: O(),
709
+ seq: E(),
710
+ event: Fe(),
711
+ createdAt: k().default("now")
712
+ }).unique(["streamId", "seq"]).index(["streamId"]), Zt = D(Y, {
713
+ id: T({ prefix: "sst" }),
714
+ streamId: O().unique(),
715
+ done: ke().default(!1),
716
+ createdAt: k().default("now"),
717
+ updatedAt: k().default("now")
718
+ }).index(["createdAt"]), Qt = (e) => e === !0 || e === 1 || e === "1" || e === "t", $t = async (e, t) => (await e.query({
719
+ table: "_voltro_stream_state",
720
+ predicate: w("streamId", t),
721
+ order: [],
722
+ take: 1,
723
+ skip: void 0,
724
+ projection: void 0
725
+ }))[0]?.id ?? null, en = (e) => ({
726
+ claimProducer: (t) => v.promise(async () => {
727
+ let n = je({
728
+ kind: "typeid",
729
+ prefix: "sst"
730
+ }, Y);
731
+ return (await e.insertIgnore(Y, {
732
+ id: n,
733
+ streamId: t,
734
+ done: !1,
735
+ createdAt: /* @__PURE__ */ new Date(),
736
+ updatedAt: /* @__PURE__ */ new Date()
737
+ }, { conflictColumns: ["streamId"] })).id === n;
738
+ }),
739
+ append: (t, n) => v.promise(async () => {
740
+ await e.insert(J, {
741
+ streamId: t,
742
+ seq: n.seq,
743
+ event: n.event,
744
+ createdAt: /* @__PURE__ */ new Date()
745
+ });
746
+ }),
747
+ read: (t, n) => v.promise(async () => (await e.query({
748
+ table: J,
749
+ predicate: C(w("streamId", t), Me("seq", n)),
750
+ order: [{
751
+ column: "seq",
752
+ direction: "asc"
753
+ }],
754
+ take: void 0,
755
+ skip: void 0,
756
+ projection: void 0
757
+ })).map((e) => ({
758
+ seq: Number(e.seq),
759
+ event: e.event
760
+ }))),
761
+ markDone: (t) => v.promise(async () => {
762
+ let n = await $t(e, t);
763
+ n !== null && await e.update(Y, n, {
764
+ done: !0,
765
+ updatedAt: /* @__PURE__ */ new Date()
766
+ });
767
+ }),
768
+ isDone: (t) => v.promise(async () => {
769
+ let n = (await e.query({
770
+ table: Y,
771
+ predicate: w("streamId", t),
772
+ order: [],
773
+ take: 1,
774
+ skip: void 0,
775
+ projection: void 0
776
+ }))[0];
777
+ return n !== void 0 && Qt(n.done);
778
+ })
779
+ }), tn = (e, t) => v.promise(async () => {
780
+ let n = await e.query({
781
+ table: Y,
782
+ predicate: w("done", !0),
783
+ order: [],
784
+ take: void 0,
785
+ skip: void 0,
786
+ projection: void 0
787
+ }), r = 0;
788
+ for (let i of n) {
789
+ let n = i;
790
+ if ((n.createdAt instanceof Date ? n.createdAt : new Date(String(n.createdAt))).getTime() >= t.olderThan.getTime()) continue;
791
+ let a = await e.query({
792
+ table: J,
793
+ predicate: w("streamId", n.streamId),
794
+ order: [],
795
+ take: void 0,
796
+ skip: void 0,
797
+ projection: void 0
798
+ });
799
+ for (let t of a) await e.delete(J, t.id);
800
+ await e.delete(Y, n.id), r += 1;
801
+ }
802
+ return r;
803
+ }), nn = (e, t = {}) => {
804
+ let n = t.keyPrefix ?? "voltro:rstream", r = t.ttlSeconds ?? 3600, i = (e) => `${n}:log:${e}`, a = (e) => `${n}:producer:${e}`, o = (e) => `${n}:done:${e}`;
805
+ return {
806
+ claimProducer: (t) => v.promise(() => e.setNx(a(t), "1", r)),
807
+ append: (t, n) => v.promise(async () => {
808
+ await e.rpush(i(t), JSON.stringify(n)), e.expire && await e.expire(i(t), r);
809
+ }),
810
+ read: (t, n) => v.promise(async () => {
811
+ let r = await e.lrange(i(t), n, -1), a = [];
812
+ for (let e of r) try {
813
+ let t = JSON.parse(e);
814
+ t.seq > n && a.push(t);
815
+ } catch {}
816
+ return a;
817
+ }),
818
+ markDone: (t) => v.promise(() => e.set(o(t), "1", r)),
819
+ isDone: (t) => v.promise(() => e.exists(o(t)))
820
+ };
821
+ }, rn = D(h, {
822
+ id: T({ prefix: "thread" }),
823
+ tenantId: O().nullable(),
824
+ title: O().nullable(),
825
+ createdAt: k(),
826
+ updatedAt: k()
827
+ }).index(["tenantId"]), an = D(m, {
828
+ id: T({ prefix: "msg" }),
829
+ threadId: O(),
830
+ tenantId: O().nullable(),
831
+ role: O(),
832
+ content: O(),
833
+ streaming: ke(),
834
+ order: E(),
835
+ stepOrder: E(),
836
+ parts: Fe(),
837
+ createdAt: k()
838
+ }).index(["threadId"]), on = (e, t = {}) => v.promise(async () => {
839
+ let n = /* @__PURE__ */ new Date();
840
+ return await e.insert(h, {
841
+ tenantId: t.tenantId ?? null,
842
+ title: t.title ?? null,
843
+ createdAt: n,
844
+ updatedAt: n
845
+ });
846
+ }), sn = (e, t) => v.promise(async () => {
847
+ let n = t.parts ?? (t.content ? [{
848
+ type: "text",
849
+ text: t.content
850
+ }] : []), r = await e.insert(m, {
851
+ threadId: t.threadId,
852
+ tenantId: t.tenantId ?? null,
853
+ role: t.role,
854
+ content: t.content,
855
+ streaming: t.streaming ?? !1,
856
+ order: t.order ?? 0,
857
+ stepOrder: t.stepOrder ?? 0,
858
+ parts: n,
859
+ createdAt: /* @__PURE__ */ new Date()
860
+ });
861
+ return await e.update(h, t.threadId, { updatedAt: /* @__PURE__ */ new Date() }).catch(() => null), r;
862
+ }), X = (e, t) => v.promise(async () => await e.query({
863
+ table: m,
864
+ predicate: {
865
+ _tag: "leaf",
866
+ column: "threadId",
867
+ op: "eq",
868
+ value: t
869
+ },
870
+ order: [{
871
+ column: "createdAt",
872
+ direction: "asc"
873
+ }],
874
+ take: void 0,
875
+ skip: void 0,
876
+ projection: void 0
877
+ })), cn = (e, t) => v.promise(async () => (await e.query({
878
+ table: "agent_threads",
879
+ predicate: {
880
+ _tag: "leaf",
881
+ column: "id",
882
+ op: "eq",
883
+ value: t
884
+ },
885
+ order: [],
886
+ take: 1,
887
+ skip: void 0,
888
+ projection: void 0
889
+ }))[0] ?? null), ln = (e) => [...e].sort((e, t) => e.order - t.order || e.stepOrder - t.stepOrder).filter((e) => !e.streaming && e.content.length > 0 && (e.role === "user" || e.role === "assistant")).map((e) => e.role === "user" ? {
890
+ role: "user",
891
+ content: e.content
892
+ } : {
893
+ role: "assistant",
894
+ content: e.content
895
+ }), un = (e, t) => v.promise(async () => {
896
+ let n = await e.insert(m, {
897
+ threadId: t.threadId,
898
+ tenantId: t.tenantId ?? null,
899
+ role: "assistant",
900
+ content: "",
901
+ streaming: !0,
902
+ order: t.order,
903
+ stepOrder: 0,
904
+ parts: [],
905
+ createdAt: /* @__PURE__ */ new Date()
906
+ });
907
+ return await e.update(h, t.threadId, { updatedAt: /* @__PURE__ */ new Date() }).catch(() => null), n.id;
908
+ }), dn = (e, t, n) => v.promise(async () => {
909
+ await e.update(m, t, {
910
+ parts: n,
911
+ content: Z(n)
912
+ });
913
+ }), Z = (e) => e.filter((e) => e.type === "text").map((e) => e.text).join(""), fn = (e, t) => v.gen(function* () {
914
+ let n = yield* un(e, {
915
+ threadId: t.threadId,
916
+ tenantId: t.tenantId ?? null,
917
+ order: t.order
918
+ }), r = "", i = "", a = /* @__PURE__ */ new Map(), o = [], s = [], c = 0, l = null, u = t.throttleMs ?? 100, d = () => {
919
+ let e = [];
920
+ r.length > 0 && e.push({
921
+ type: "reasoning",
922
+ text: r
923
+ }), i.length > 0 && e.push({
924
+ type: "text",
925
+ text: i
926
+ });
927
+ for (let t of a.values()) e.push(t);
928
+ for (let t of o) e.push(t);
929
+ for (let t of s) e.push(t);
930
+ return e;
931
+ }, f = (t) => {
932
+ let r = Date.now();
933
+ return !t && r - c < u ? v.void : (c = r, dn(e, n, d()));
934
+ };
935
+ yield* q({
936
+ prompt: t.prompt,
937
+ ...t.messages === void 0 ? {} : { messages: t.messages },
938
+ ...t.system === void 0 ? {} : { system: t.system },
939
+ ...t.tools === void 0 ? {} : { tools: t.tools },
940
+ ...t.provider === void 0 ? {} : { provider: t.provider },
941
+ ...t.maxSteps === void 0 ? {} : { maxSteps: t.maxSteps },
942
+ ...t.toolContext === void 0 ? {} : { toolContext: t.toolContext },
943
+ ...t.providerOptions === void 0 ? {} : { providerOptions: t.providerOptions }
944
+ }).pipe(S.runForEach((e) => v.gen(function* () {
945
+ switch (e._tag) {
946
+ case "token":
947
+ i += e.text, yield* f(!1);
948
+ break;
949
+ case "toolCall":
950
+ a.set(e.id, {
951
+ type: "tool",
952
+ toolCallId: e.id,
953
+ toolName: e.name,
954
+ state: "input-available",
955
+ input: e.input
956
+ }), yield* f(!0);
957
+ break;
958
+ case "toolResult": {
959
+ let t = a.get(e.id);
960
+ a.set(e.id, {
961
+ type: "tool",
962
+ toolCallId: e.id,
963
+ toolName: e.name,
964
+ state: e.error ? "output-error" : "output-available",
965
+ input: t?.input,
966
+ output: e.output,
967
+ ...e.error ? { errorText: e.error } : {}
968
+ }), yield* f(!0);
969
+ break;
970
+ }
971
+ case "reasoning":
972
+ r += e.text, yield* f(!1);
973
+ break;
974
+ case "source":
975
+ o.push({
976
+ type: "source",
977
+ sourceType: e.sourceType,
978
+ id: e.id,
979
+ ...e.url === void 0 ? {} : { url: e.url },
980
+ ...e.title === void 0 ? {} : { title: e.title },
981
+ ...e.mediaType === void 0 ? {} : { mediaType: e.mediaType },
982
+ ...e.filename === void 0 ? {} : { filename: e.filename }
983
+ }), yield* f(!0);
984
+ break;
985
+ case "file":
986
+ s.push({
987
+ type: "file",
988
+ mediaType: e.mediaType,
989
+ data: e.data
990
+ }), yield* f(!0);
991
+ break;
992
+ case "error":
993
+ l = e.message;
994
+ break;
995
+ case "done":
996
+ case "message": break;
997
+ }
998
+ })));
999
+ let p = d();
1000
+ return yield* v.promise(() => e.update(m, n, {
1001
+ parts: p,
1002
+ content: Z(p),
1003
+ streaming: !1
1004
+ })), l ? yield* v.fail(Error(l)) : Z(p);
1005
+ }), pn = "@voltro/ai/AgentExecutor", mn = Symbol.for("@voltro/ai/AgentExecutor"), hn = (e, t) => ({
1006
+ [mn]: !0,
1007
+ _brand: pn,
1008
+ descriptor: e,
1009
+ config: t
1010
+ }), gn = (e) => typeof e == "object" && !!e && e._brand === pn, _n = (e, t) => {
1011
+ let n = e.config.system;
1012
+ if (n !== void 0) return typeof n == "function" ? n(t) : n;
1013
+ }, vn = (e, t) => {
1014
+ let n = e.config.model;
1015
+ return typeof n == "function" ? n(t) : n;
1016
+ }, yn = (e, t, n) => v.gen(function* () {
1017
+ let r = n.promptOf ? n.promptOf(n.input) : String(n.input?.prompt ?? ""), i = _n(e, n.input), a = vn(e, n.input);
1018
+ yield* sn(t, {
1019
+ threadId: n.threadId,
1020
+ role: "user",
1021
+ content: r,
1022
+ tenantId: n.tenantId ?? null,
1023
+ order: n.order
1024
+ });
1025
+ let o = ln(yield* X(t, n.threadId));
1026
+ return yield* fn(t, {
1027
+ threadId: n.threadId,
1028
+ tenantId: n.tenantId ?? null,
1029
+ prompt: r,
1030
+ ...o.length > 0 ? { messages: o } : {},
1031
+ ...i === void 0 ? {} : { system: i },
1032
+ ...e.config.tools === void 0 ? {} : { tools: e.config.tools },
1033
+ ...a === void 0 ? {} : { provider: a },
1034
+ ...e.config.maxSteps === void 0 ? {} : { maxSteps: e.config.maxSteps },
1035
+ ...e.config.providerOptions === void 0 ? {} : { providerOptions: e.config.providerOptions },
1036
+ ...n.toolContext === void 0 ? {} : { toolContext: n.toolContext },
1037
+ order: n.order + 1,
1038
+ ...n.throttleMs === void 0 ? {} : { throttleMs: n.throttleMs }
1039
+ });
1040
+ }), bn = (e, t) => X(e, t), xn = (e, t) => ({
1041
+ specificationVersion: "v4",
1042
+ provider: "mock",
1043
+ modelId: e,
1044
+ maxEmbeddingsPerCall: 2048,
1045
+ supportsParallelCalls: !0,
1046
+ doEmbed: async ({ values: e }) => ({
1047
+ embeddings: e.map((e) => Sn(e, t)),
1048
+ usage: { tokens: e.reduce((e, t) => e + t.length, 0) },
1049
+ warnings: []
1050
+ })
1051
+ }), Sn = (e, t) => {
1052
+ let n = Array(t);
1053
+ for (let r = 0; r < t; r++) {
1054
+ let t = 2166136261 ^ r * 16777619;
1055
+ for (let n = 0; n < e.length; n++) t ^= e.charCodeAt(n), t = Math.imul(t, 16777619);
1056
+ n[r] = (t >>> 0) / 4294967295 * 2 - 1;
1057
+ }
1058
+ return n;
1059
+ }, Cn = async (e) => {
1060
+ switch (e.name) {
1061
+ case "mock": return xn(e.model, e.mockDim ?? 8);
1062
+ case "openai": return (await wn("@ai-sdk/openai", "openai")).openai.textEmbeddingModel(e.model);
1063
+ case "voyage": return (await wn("voyage-ai-provider", "voyage")).voyage.textEmbeddingModel(e.model);
1064
+ case "cohere": return (await wn("@ai-sdk/cohere", "cohere")).cohere.textEmbeddingModel(e.model);
1065
+ }
1066
+ }, wn = async (e, t) => {
1067
+ try {
1068
+ return await import(
1069
+ /* @vite-ignore */
1070
+ e
1071
+ );
1072
+ } catch {
1073
+ throw Error(`embedding provider '${t}' needs the '${e}' package — install it (pnpm add ${e}) or use AI_EMBED_PROVIDER=mock for tests/demos.`);
1074
+ }
1075
+ }, Tn = (e = process.env) => {
1076
+ let t = (e.AI_EMBED_PROVIDER ?? "mock").toLowerCase(), n = t === "openai" ? "text-embedding-3-small" : t === "voyage" ? "voyage-3" : t === "cohere" ? "embed-english-v3.0" : "mock", r = e.AI_EMBED_MODEL ?? n, i = e.AI_EMBED_MOCK_DIM === void 0 ? void 0 : Number(e.AI_EMBED_MOCK_DIM);
1077
+ return {
1078
+ name: t,
1079
+ model: r,
1080
+ ...i !== void 0 && Number.isFinite(i) ? { mockDim: i } : {}
1081
+ };
1082
+ }, En = (e, t) => v.tryPromise({
1083
+ try: async () => (await me({
1084
+ model: await Cn(t ?? Tn()),
1085
+ value: e
1086
+ })).embedding,
1087
+ catch: (e) => new B({
1088
+ reason: "generation",
1089
+ message: String(e?.message ?? e)
1090
+ })
1091
+ }), Dn = (e, t) => v.tryPromise({
1092
+ try: async () => (await he({
1093
+ model: await Cn(t ?? Tn()),
1094
+ values: [...e]
1095
+ })).embeddings,
1096
+ catch: (e) => new B({
1097
+ reason: "generation",
1098
+ message: String(e?.message ?? e)
1099
+ })
1100
+ }), On = (e, t) => pe([...e], [...t]), kn = (e) => v.tryPromise({
1101
+ try: async () => {
1102
+ let t = e.getText ?? ((e) => String(e)), n = e.provider ?? "mock", r = [...n === "mock" ? An(e.query, e.documents, t) : await Mn(n, e.query, e.documents, t, e.model)].sort((e, t) => t.score - e.score);
1103
+ return e.topN === void 0 ? r : r.slice(0, e.topN);
1104
+ },
1105
+ catch: (e) => new B({
1106
+ reason: "generation",
1107
+ message: String(e?.message ?? e)
1108
+ })
1109
+ }), An = (e, t, n) => {
1110
+ let r = jn(e), i = new Set(r);
1111
+ return t.map((e) => {
1112
+ let t = new Set(jn(n(e))), r = 0;
1113
+ for (let e of i) t.has(e) && r++;
1114
+ return {
1115
+ document: e,
1116
+ score: i.size === 0 ? 0 : r / i.size
1117
+ };
1118
+ });
1119
+ }, jn = (e) => e.toLowerCase().split(/[^a-z0-9]+/).filter((e) => e.length > 0), Mn = async (e, t, n, r, i) => {
1120
+ let a = e === "cohere" ? "@ai-sdk/cohere" : "voyage-ai-provider", o;
1121
+ try {
1122
+ o = await import(
1123
+ /* @vite-ignore */
1124
+ a
1125
+ );
1126
+ } catch {
1127
+ throw Error(`rerank provider '${e}' needs the '${a}' package — install it or use the default mock provider for tests/demos.`);
1128
+ }
1129
+ let s = o[e], c = s?.rerankingModel ?? s?.reranking;
1130
+ if (typeof c != "function") throw Error(`rerank provider '${e}' does not expose a reranking model in '${a}'.`);
1131
+ return (await be({
1132
+ model: c(i ?? (e === "cohere" ? "rerank-english-v3.0" : "rerank-2")),
1133
+ query: t,
1134
+ documents: n.map(r)
1135
+ })).ranking.map((e) => ({
1136
+ document: n[e.originalIndex],
1137
+ score: e.score
1138
+ }));
1139
+ }, Q = (e) => {
1140
+ if (e === void 0) return;
1141
+ let t = Number(e);
1142
+ return Number.isFinite(t) ? t * 1e6 : void 0;
1143
+ }, Nn = (e) => {
1144
+ let t = Q(e.pricing?.input), n = Q(e.pricing?.output), r = Q(e.pricing?.cachedInputTokens ?? void 0);
1145
+ return {
1146
+ id: e.id,
1147
+ name: e.name,
1148
+ ...e.description == null ? {} : { description: e.description },
1149
+ modality: e.modelType ?? "unknown",
1150
+ ...t !== void 0 && n !== void 0 ? { pricing: {
1151
+ inputPer1M: t,
1152
+ outputPer1M: n,
1153
+ ...r === void 0 ? {} : { cachedInputPer1M: r }
1154
+ } } : {}
1155
+ };
1156
+ }, Pn = async (e = {}) => {
1157
+ let t = (await (e.gatewayProvider ?? (e.apiKey !== void 0 || e.baseURL !== void 0 ? ue({
1158
+ ...e.apiKey === void 0 ? {} : { apiKey: e.apiKey },
1159
+ ...e.baseURL === void 0 ? {} : { baseURL: e.baseURL }
1160
+ }) : de)).getAvailableModels()).models.map(Nn);
1161
+ return e.modality === void 0 ? t : t.filter((t) => t.modality === e.modality);
1162
+ }, Fn = class extends x.TaggedError()("CopilotRejected", {
1163
+ reason: x.Literal("unknown-table", "unknown-column", "bad-op", "bad-aggregate", "empty"),
1164
+ detail: x.String
1165
+ }) {}, In = 200, Ln = 50, Rn = /* @__PURE__ */ new Set([
1166
+ "eq",
1167
+ "neq",
1168
+ "gt",
1169
+ "gte",
1170
+ "lt",
1171
+ "lte",
1172
+ "contains",
1173
+ "in"
1174
+ ]), zn = (e) => {
1175
+ switch (e.op) {
1176
+ case "eq": return w(e.column, e.value);
1177
+ case "neq": return Re(e.column, e.value);
1178
+ case "gt": return Me(e.column, e.value);
1179
+ case "gte": return Ne(e.column, e.value);
1180
+ case "lt": return Ie(e.column, e.value);
1181
+ case "lte": return Le(e.column, e.value);
1182
+ case "contains": return Ae(e.column, e.value);
1183
+ case "in": return Pe(e.column, Array.isArray(e.value) ? e.value : [e.value]);
1184
+ }
1185
+ }, $ = (e, t) => ({
1186
+ ok: !1,
1187
+ rejection: new Fn({
1188
+ reason: e,
1189
+ detail: t
1190
+ })
1191
+ }), Bn = (e, t) => {
1192
+ let n = t.tables.find((t) => t.name === e.table);
1193
+ if (n === void 0) return $("unknown-table", e.table);
1194
+ let r = new Set(n.columns.map((e) => e.name));
1195
+ for (let t of e.columns ?? []) if (!r.has(t)) return $("unknown-column", `${e.table}.${t}`);
1196
+ for (let t of e.filters ?? []) {
1197
+ if (!Rn.has(t.op)) return $("bad-op", String(t.op));
1198
+ if (!r.has(t.column)) return $("unknown-column", `${e.table}.${t.column}`);
1199
+ }
1200
+ if (e.orderBy !== void 0 && !r.has(e.orderBy.column)) return $("unknown-column", `${e.table}.${e.orderBy.column}`);
1201
+ if (e.aggregate !== void 0) {
1202
+ let { fn: t, column: n } = e.aggregate;
1203
+ if (t !== "count" && (n === void 0 || !r.has(n))) return $("bad-aggregate", `${t}(${n ?? "∅"})`);
1204
+ }
1205
+ let i = e.filters ?? [], a = i.length === 0 ? void 0 : i.length === 1 ? zn(i[0]) : C(...i.map(zn)), o = Math.min(Math.max(1, e.limit ?? Ln), 200), s = {
1206
+ table: e.table,
1207
+ predicate: a,
1208
+ order: e.orderBy ? [{
1209
+ column: e.orderBy.column,
1210
+ direction: e.orderBy.direction ?? "asc"
1211
+ }] : [],
1212
+ take: o,
1213
+ skip: void 0,
1214
+ projection: e.columns && e.columns.length > 0 ? [...e.columns] : void 0
1215
+ };
1216
+ return e.aggregate ? {
1217
+ ok: !0,
1218
+ descriptor: s,
1219
+ table: e.table,
1220
+ aggregate: e.aggregate
1221
+ } : {
1222
+ ok: !0,
1223
+ descriptor: s,
1224
+ table: e.table
1225
+ };
1226
+ }, Vn = x.Struct({
1227
+ table: x.String,
1228
+ columns: x.optional(x.Array(x.String)),
1229
+ filters: x.optional(x.Array(x.Struct({
1230
+ column: x.String,
1231
+ op: x.Literal("eq", "neq", "gt", "gte", "lt", "lte", "contains", "in"),
1232
+ value: x.Unknown
1233
+ }))),
1234
+ orderBy: x.optional(x.Struct({
1235
+ column: x.String,
1236
+ direction: x.optional(x.Literal("asc", "desc"))
1237
+ })),
1238
+ limit: x.optional(x.Number),
1239
+ aggregate: x.optional(x.Struct({
1240
+ fn: x.Literal("count", "sum", "avg", "min", "max"),
1241
+ column: x.optional(x.String)
1242
+ }))
1243
+ }), Hn = (e) => [
1244
+ "You are a data copilot. Translate the user question into a JSON query proposal.",
1245
+ "",
1246
+ "You may ONLY reference these tables and columns:",
1247
+ e.tables.map((e) => `- ${e.name}(${e.columns.map((e) => e.name).join(", ")})`).join("\n"),
1248
+ "",
1249
+ "Rules:",
1250
+ "- Pick EXACTLY ONE table from the list as `table`.",
1251
+ "- Every column in `columns`, `filters`, `orderBy`, and `aggregate` MUST be one of that table's listed columns.",
1252
+ "- NEVER invent a table or column. If the question cannot be answered from the listed schema, pick the closest table and leave filters empty.",
1253
+ "- The query is READ-ONLY. You cannot insert, update, or delete.",
1254
+ "- Keep the result small (limit ≤ 200)."
1255
+ ].join("\n"), Un = async (e, t, n) => {
1256
+ let r = Hn(t);
1257
+ return Bn(await n.propose({
1258
+ system: r,
1259
+ prompt: e
1260
+ }), t);
1261
+ };
1262
+ //#endregion
1263
+ export { m as AGENT_MESSAGES_TABLE, h as AGENT_THREADS_TABLE, P as AI_BUDGET_TABLE, N as AI_USAGE_TABLE, ne as AgentErrorCode, re as AgentEvent, at as AiBudgetExceeded, B as AiError, xt as AiService, In as COPILOT_MAX_LIMIT, Vn as CopilotProposalSchema, Fn as CopilotRejected, Ze as MODEL_PRICING_DEFAULTS, ee as MockScript, J as STREAM_EVENTS_TABLE, Y as STREAM_STATE_TABLE, ie as SeqEvent, Rt as activeStreamCount, jt as agentActor, le as agentInputSchema, se as agentMessageSchema, an as agentMessagesTable, ce as agentRouteDescriptors, rn as agentThreadsTable, ot as aiBudgetTable, L as aiCallAttributes, it as aiSpendUsd, tt as aiUsageTable, Nt as appTools, sn as appendMessage, un as appendStreamingMessage, s as applyMiddleware, Hn as buildCopilotSystemPrompt, A as buildSdkTools, Ft as cancelStream, te as clearAiMiddleware, Gt as consumeResumableStream, On as cosineSimilarity, on as createThread, en as dataStoreResumableStreamStore, St as defaultAiService, n as defaultSettingsMiddleware, oe as defineAgent, hn as defineAgentExecutor, We as defineTool, En as embed, Dn as embedMany, Tn as embeddingProviderFromEnv, M as estimateCostUsd, r as extractReasoningMiddleware, nt as gatewayCostUsd, tn as gcResumableStreams, wt as generateImage, yt as generateObject, bt as generateObjectWithTools, Tt as generateSpeech, _t as generateText, Ot as generateVideo, d as getAiMiddleware, Pn as getAvailableModels, X as getMessages, l as getProviderOverride, cn as getThread, Sn as hashToVector, ln as historyToModelMessages, ae as isAgentDescriptor, gn as isAgentExecutor, It as isStreamActive, Ge as isTool, bn as loadAgentMessages, c as loggingMiddleware, Yt as memoryResumableStreamStore, $e as modelPricing, gt as observeStream, U as passesPolicy, dn as patchStreamingMessage, et as priceForModel, f as providerFromEnv, rt as recordAiUsage, nn as redisResumableStreamStore, Pt as registerStream, lt as requireAiBudget, kn as rerank, vn as resolveAgentModel, Cn as resolveEmbeddingModel, o as resolveImageModel, e as resolveModel, u as resolveSpeechModel, _n as resolveSystem, Ke as resolveToolModuleHandlers, p as resolveVideoModel, qt as resumableStream, Jt as resumableStreamText, yn as runAgentTurn, fn as runAssistant, Un as runDataCopilot, a as setAiMiddleware, Qe as setModelPricing, t as setProviderOverride, i as simulateStreamingMiddleware, Kt as startResumableProducer, Xt as streamEventsTable, Zt as streamStateTable, q as streamText, Wt as streamTextWithFallback, Ut as streamTextWithRetry, Mt as synthesizeToolSpecs, Nn as toModelInfo, Lt as unregisterStream, Bn as validateCopilotProposal, z as withAiCallSpan };