@voltro/ai 0.84.0 → 0.86.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/CHANGELOG.md +1215 -0
- package/THIRD-PARTY-NOTICES.md +5 -151
- package/dist/agent.d.ts +34 -41
- package/dist/agent.js +64 -2
- package/dist/agentConstants.js +4 -0
- package/dist/agentExecutor.js +51 -0
- package/dist/api.js +199 -0
- package/dist/appTools.js +80 -0
- package/dist/budget.js +201 -0
- package/dist/callEvidence.js +51 -0
- package/dist/copilot.js +126 -0
- package/dist/cost.js +242 -0
- package/dist/embed.js +41 -0
- package/dist/embeddingProvider.js +51 -0
- package/dist/eval.js +130 -0
- package/dist/events.d.ts +171 -168
- package/dist/events.js +81 -2
- package/dist/executableModalities.js +13 -0
- package/dist/gateway.js +58 -0
- package/dist/gatewayCatalog.js +47 -0
- package/dist/gatewayMedia.js +88 -0
- package/dist/index.d.ts +328 -326
- package/dist/index.js +42 -2581
- package/dist/inferenceDispatch.js +493 -0
- package/dist/inferenceQueue.js +96 -0
- package/dist/jsonOutputValidation.js +27 -0
- package/dist/mcpClient.js +332 -0
- package/dist/mcpTools.js +80 -0
- package/dist/media.js +182 -0
- package/dist/mediaBytes.js +19 -0
- package/dist/mediaCall.js +13 -0
- package/dist/mediaTaskProvider.js +16 -0
- package/dist/middleware.js +32 -0
- package/dist/observe.js +52 -0
- package/dist/prompts.js +103 -0
- package/dist/provider.js +303 -0
- package/dist/realtimeEvent.js +97 -0
- package/dist/realtimeSession.js +154 -0
- package/dist/rerank.js +61 -0
- package/dist/resumableStream.js +321 -0
- package/dist/retrieveReranked.js +16 -0
- package/dist/runAndPersist.js +148 -0
- package/dist/semanticCache.js +66 -0
- package/dist/speechProvider.js +16 -0
- package/dist/streamRegistry.js +14 -0
- package/dist/streamText.js +170 -0
- package/dist/streamTranscribe.js +74 -0
- package/dist/streamWakeups.js +44 -0
- package/dist/structuredEvidence.js +48 -0
- package/dist/test.js +1 -1
- package/dist/threads.js +92 -0
- package/dist/tools.js +68 -0
- package/dist/transcribe.js +64 -0
- package/dist/transcriptionEvent.js +46 -0
- package/dist/workflow.d.ts +12 -10
- package/dist/workflow.js +117 -112
- package/package.json +6 -6
- package/dist/agentDescriptor-DuxvWGDi.js +0 -63
- package/dist/agentEvent-BuXA7sRt.js +0 -152
- package/dist/inferenceQueue-BmtEm3YI.js +0 -1061
- package/dist/provider-BnemgE4D.js +0 -409
package/dist/appTools.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { defineTool as e } from "./tools.js";
|
|
2
|
+
//#region src/appTools.ts
|
|
3
|
+
var t = /* @__PURE__ */ new Map(), n = (e) => {
|
|
4
|
+
let n = t.get(e);
|
|
5
|
+
if (n !== void 0) return n;
|
|
6
|
+
let r = RegExp("^" + e.split("*").map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$");
|
|
7
|
+
return t.size >= 256 && t.delete(t.keys().next().value), t.set(e, r), r;
|
|
8
|
+
}, r = (e, t) => {
|
|
9
|
+
let n = t.lastIndex;
|
|
10
|
+
try {
|
|
11
|
+
return t.lastIndex = 0, t.test(e);
|
|
12
|
+
} finally {
|
|
13
|
+
t.lastIndex = n;
|
|
14
|
+
}
|
|
15
|
+
}, i = (e, t) => t instanceof RegExp ? r(e, t) : t.some((t) => n(t).test(e)), a = (e, t) => !(t.deny !== void 0 && i(e, t.deny) || t.allow !== void 0 && !i(e, t.allow)), o = (e) => e === "mutation" || e === "action", s = (e) => ({
|
|
16
|
+
id: e,
|
|
17
|
+
via: "agent"
|
|
18
|
+
}), c = (e, t) => {
|
|
19
|
+
let n = e.exposeAsTool;
|
|
20
|
+
if (n === void 0 || n === !1 || n === !0) return null;
|
|
21
|
+
let r = o(e.kind), i = n.confirm ?? (r && (t.requireConfirmForWrites ?? !0));
|
|
22
|
+
return {
|
|
23
|
+
description: n.description,
|
|
24
|
+
confirm: i,
|
|
25
|
+
...n.maxPerRun === void 0 ? {} : { maxPerRun: n.maxPerRun }
|
|
26
|
+
};
|
|
27
|
+
}, l = (e, t) => {
|
|
28
|
+
if (!a(e.name, t)) return {
|
|
29
|
+
admitted: !1,
|
|
30
|
+
reason: "blocked by the allow/deny policy"
|
|
31
|
+
};
|
|
32
|
+
let n = c(e, t);
|
|
33
|
+
if (n === null) return {
|
|
34
|
+
admitted: !1,
|
|
35
|
+
reason: "not exposed as a tool (no `exposeAsTool: { description }` on the descriptor)"
|
|
36
|
+
};
|
|
37
|
+
let r = o(e.kind);
|
|
38
|
+
if (r && t.includeWrites !== !0) return {
|
|
39
|
+
admitted: !1,
|
|
40
|
+
reason: "a write tool, and includeWrites is not enabled"
|
|
41
|
+
};
|
|
42
|
+
let i = e.requiresApproval !== void 0 && e.requiresApproval !== null;
|
|
43
|
+
return n.confirm && !i ? {
|
|
44
|
+
admitted: !1,
|
|
45
|
+
reason: "the tool requires human confirmation (`confirm`) and nothing enforces it — add `requiresApproval: { approvers: [...] }` to the descriptor so the call parks as a durable approval, or set `exposeAsTool: { confirm: false }` if an agent may run it unattended"
|
|
46
|
+
} : {
|
|
47
|
+
admitted: !0,
|
|
48
|
+
spec: {
|
|
49
|
+
name: e.name,
|
|
50
|
+
kind: e.kind,
|
|
51
|
+
description: n.description,
|
|
52
|
+
write: r,
|
|
53
|
+
confirm: n.confirm,
|
|
54
|
+
approvalBacked: i,
|
|
55
|
+
...n.maxPerRun === void 0 ? {} : { maxPerRun: n.maxPerRun }
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}, u = (e, t = {}) => e.filter((e) => a(e.descriptor.name, t)).map((e) => ({
|
|
59
|
+
entry: e,
|
|
60
|
+
exposure: c(e.descriptor, t)
|
|
61
|
+
})).filter((e) => e.exposure !== null).map(({ entry: e, exposure: t }) => ({
|
|
62
|
+
name: e.descriptor.name,
|
|
63
|
+
kind: e.descriptor.kind,
|
|
64
|
+
description: t.description,
|
|
65
|
+
write: o(e.descriptor.kind),
|
|
66
|
+
confirm: t.confirm,
|
|
67
|
+
approvalBacked: e.descriptor.requiresApproval !== void 0 && e.descriptor.requiresApproval !== null,
|
|
68
|
+
...t.maxPerRun === void 0 ? {} : { maxPerRun: t.maxPerRun }
|
|
69
|
+
})).sort((e, t) => e.name.localeCompare(t.name)), d = (t, n = {}) => t.map((e) => ({
|
|
70
|
+
entry: e,
|
|
71
|
+
decision: l(e.descriptor, n)
|
|
72
|
+
})).filter((e) => e.decision.admitted).map(({ entry: t, decision: n }) => e({
|
|
73
|
+
name: t.descriptor.name,
|
|
74
|
+
description: n.spec.description,
|
|
75
|
+
input: t.descriptor.input,
|
|
76
|
+
...t.descriptor.output === void 0 ? {} : { output: t.descriptor.output },
|
|
77
|
+
handler: (e) => Promise.resolve(t.invoke(e))
|
|
78
|
+
}));
|
|
79
|
+
//#endregion
|
|
80
|
+
export { s as agentActor, l as appToolDecision, d as appTools, a as passesPolicy, u as synthesizeToolSpecs };
|
package/dist/budget.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { Effect as e, Schema as t } from "effect";
|
|
2
|
+
import { and as n, bigint as r, eq as i, generateId as a, id as o, isNull as s, queryFor as c, registerRetention as l, retentionTtlMsFromEnv as u, table as d, text as f, timestamp as p } from "@voltro/database";
|
|
3
|
+
//#region src/budget.ts
|
|
4
|
+
var m = class extends t.TaggedError()("AiBudgetExceeded", {
|
|
5
|
+
tenantId: t.NullOr(t.String),
|
|
6
|
+
limitUsd: t.Number,
|
|
7
|
+
spentUsd: t.Number,
|
|
8
|
+
attemptedUsd: t.Number
|
|
9
|
+
}) {}, h = class extends t.TaggedError()("AiBudgetInvalidInput", {
|
|
10
|
+
field: t.Literals([
|
|
11
|
+
"limitUsd",
|
|
12
|
+
"addUsd",
|
|
13
|
+
"since",
|
|
14
|
+
"reservationId",
|
|
15
|
+
"tenantId"
|
|
16
|
+
]),
|
|
17
|
+
message: t.String
|
|
18
|
+
}) {}, g = class extends t.TaggedError()("AiBudgetReservationConflict", {
|
|
19
|
+
reason: t.Literals(["identity-bound", "already-released"]),
|
|
20
|
+
message: t.String
|
|
21
|
+
}) {}, _ = "_voltro_ai_budget", v = "_voltro_ai_budget_reservations", y = d(_, {
|
|
22
|
+
id: o({ prefix: "aib" }),
|
|
23
|
+
bucket: f().maxLength(191),
|
|
24
|
+
tenantId: f().nullable(),
|
|
25
|
+
reservedMicroUsd: r().default("0").narrowedFrom("integer"),
|
|
26
|
+
updatedAt: p().default("now")
|
|
27
|
+
}).unique("byAiBudgetBucket", ["bucket"]), b = d(v, {
|
|
28
|
+
id: o({ prefix: "air" }),
|
|
29
|
+
reservationId: f().maxLength(191),
|
|
30
|
+
bucket: f().maxLength(191),
|
|
31
|
+
tenantId: f().nullable(),
|
|
32
|
+
amountMicroUsd: r(),
|
|
33
|
+
releasedAt: p().nullable(),
|
|
34
|
+
updatedAt: p().default("now")
|
|
35
|
+
}).unique("byAiBudgetReservation", ["reservationId"]), x = class extends Error {}, S = (e, t, n) => {
|
|
36
|
+
if (!Number.isFinite(e) || e < 0) throw new h({
|
|
37
|
+
field: t,
|
|
38
|
+
message: `${t} must be finite and non-negative`
|
|
39
|
+
});
|
|
40
|
+
let r = e * 1e6, i = n === "up" ? Math.ceil(r) : Math.floor(r);
|
|
41
|
+
if (!Number.isSafeInteger(i)) throw new h({
|
|
42
|
+
field: t,
|
|
43
|
+
message: `${t} exceeds the safe micro-USD range`
|
|
44
|
+
});
|
|
45
|
+
return BigInt(i);
|
|
46
|
+
}, C = (e) => {
|
|
47
|
+
if (typeof e == "number" && !Number.isSafeInteger(e)) throw Error("AI budget counter is not an exact integer");
|
|
48
|
+
let t = String(e);
|
|
49
|
+
if (!/^(0|[1-9][0-9]*)$/.test(t)) throw Error("AI budget counter is invalid; refusing to assume zero");
|
|
50
|
+
return BigInt(t);
|
|
51
|
+
}, w = (e) => {
|
|
52
|
+
if (typeof e != "string" || e.length === 0 || e.length > 191) throw new h({
|
|
53
|
+
field: "reservationId",
|
|
54
|
+
message: "AI budget reservationId must contain 1–191 characters"
|
|
55
|
+
});
|
|
56
|
+
return e;
|
|
57
|
+
}, T = () => {
|
|
58
|
+
let e = u(process.env.VOLTRO_AI_USAGE_TTL_HOURS, 8760);
|
|
59
|
+
for (let t of [_, v]) l({
|
|
60
|
+
source: "plugin",
|
|
61
|
+
table: t,
|
|
62
|
+
timeColumn: "updatedAt",
|
|
63
|
+
ttlMs: e
|
|
64
|
+
});
|
|
65
|
+
}, E = async (e, t) => {
|
|
66
|
+
for (let n = 0;; n++) try {
|
|
67
|
+
return await e.transactional(t);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
if (!(e instanceof x) || n >= 31) throw e;
|
|
70
|
+
await new Promise((e) => setTimeout(e, n + 1));
|
|
71
|
+
}
|
|
72
|
+
}, D = (t) => t instanceof m || t instanceof h || t instanceof g ? e.fail(t) : e.die(t), O = (t) => e.tryPromise({
|
|
73
|
+
try: t,
|
|
74
|
+
catch: (e) => e
|
|
75
|
+
}).pipe(e.catch(D)), k = (t, r) => e.gen(function* () {
|
|
76
|
+
let { limit: o, amount: s, tenantId: l, bucket: u, reservationId: d } = yield* e.try({
|
|
77
|
+
try: () => {
|
|
78
|
+
let e = S(r.limitUsd, "limitUsd", "down"), t = S(r.addUsd ?? 0, "addUsd", "up"), n = r.tenantId ?? null;
|
|
79
|
+
if (r.since !== void 0 && (!(r.since instanceof Date) || !Number.isFinite(r.since.getTime()))) throw new h({
|
|
80
|
+
field: "since",
|
|
81
|
+
message: "AI budget since must be a valid Date"
|
|
82
|
+
});
|
|
83
|
+
let i = `${n ?? "global"}::${r.since === void 0 ? "all" : r.since.getTime()}`;
|
|
84
|
+
if (i.length > 191) throw new h({
|
|
85
|
+
field: "tenantId",
|
|
86
|
+
message: "AI budget tenant/window key exceeds 191 characters"
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
limit: e,
|
|
90
|
+
amount: t,
|
|
91
|
+
tenantId: n,
|
|
92
|
+
bucket: i,
|
|
93
|
+
reservationId: w(r.reservationId ?? a({
|
|
94
|
+
kind: "typeid",
|
|
95
|
+
prefix: "air"
|
|
96
|
+
}, "_voltro_ai_budget_reservations"))
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
catch: (e) => e
|
|
100
|
+
}).pipe(e.catch(D));
|
|
101
|
+
T();
|
|
102
|
+
let f = async (e) => {
|
|
103
|
+
let [t] = await e.query(c(y).where(i("bucket", u)).descriptor);
|
|
104
|
+
if (t && t.tenantId !== l) throw Error("AI budget bucket belongs to a different tenant");
|
|
105
|
+
return t;
|
|
106
|
+
}, p = (e) => {
|
|
107
|
+
if (s === 0n ? e >= o : e + s > o) throw new m({
|
|
108
|
+
tenantId: l,
|
|
109
|
+
limitUsd: r.limitUsd,
|
|
110
|
+
spentUsd: Number(e) / 1e6,
|
|
111
|
+
attemptedUsd: r.addUsd ?? 0
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
return s === 0n ? yield* O(async () => {
|
|
115
|
+
let e = await f(t);
|
|
116
|
+
return p(e ? C(e.reservedMicroUsd) : 0n), null;
|
|
117
|
+
}) : yield* O(() => E(t, async (e) => {
|
|
118
|
+
let t = a({
|
|
119
|
+
kind: "typeid",
|
|
120
|
+
prefix: "air"
|
|
121
|
+
}, v), r = /* @__PURE__ */ new Date(), o = await e.insertIgnore(v, {
|
|
122
|
+
id: t,
|
|
123
|
+
reservationId: d,
|
|
124
|
+
bucket: u,
|
|
125
|
+
tenantId: l,
|
|
126
|
+
amountMicroUsd: String(s),
|
|
127
|
+
releasedAt: null,
|
|
128
|
+
updatedAt: r
|
|
129
|
+
}, { conflictColumns: ["reservationId"] });
|
|
130
|
+
if (o.id !== t) {
|
|
131
|
+
if (o.tenantId !== l || o.bucket !== u || C(o.amountMicroUsd) !== s) throw new g({
|
|
132
|
+
reason: "identity-bound",
|
|
133
|
+
message: "AI budget reservationId is already bound to another tenant, amount or window"
|
|
134
|
+
});
|
|
135
|
+
if (o.releasedAt !== null) throw new g({
|
|
136
|
+
reason: "already-released",
|
|
137
|
+
message: "AI budget reservation was released; new spend requires a new reservationId"
|
|
138
|
+
});
|
|
139
|
+
return {
|
|
140
|
+
reservationId: d,
|
|
141
|
+
tenantId: l,
|
|
142
|
+
amountMicroUsd: String(s),
|
|
143
|
+
status: "replayed"
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
let c = await f(e), m = c ? C(c.reservedMicroUsd) : 0n;
|
|
147
|
+
if (p(m), c) {
|
|
148
|
+
if (await e.updateMany("_voltro_ai_budget", {
|
|
149
|
+
reservedMicroUsd: String(m + s),
|
|
150
|
+
updatedAt: r
|
|
151
|
+
}, { where: n(i("id", c.id), i("reservedMicroUsd", c.reservedMicroUsd)) }) !== 1) throw new x("AI budget counter changed; discard this receipt and retry");
|
|
152
|
+
} else {
|
|
153
|
+
let t = a({
|
|
154
|
+
kind: "typeid",
|
|
155
|
+
prefix: "aib"
|
|
156
|
+
}, _);
|
|
157
|
+
if ((await e.insertIgnore("_voltro_ai_budget", {
|
|
158
|
+
id: t,
|
|
159
|
+
bucket: u,
|
|
160
|
+
tenantId: l,
|
|
161
|
+
reservedMicroUsd: String(s),
|
|
162
|
+
updatedAt: r
|
|
163
|
+
}, { conflictColumns: ["bucket"] })).id !== t) throw new x("AI budget counter was created concurrently; discard this receipt and retry");
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
reservationId: d,
|
|
167
|
+
tenantId: l,
|
|
168
|
+
amountMicroUsd: String(s),
|
|
169
|
+
status: "reserved"
|
|
170
|
+
};
|
|
171
|
+
}));
|
|
172
|
+
}), A = (t, r) => e.gen(function* () {
|
|
173
|
+
return yield* e.try({
|
|
174
|
+
try: () => w(r.reservationId),
|
|
175
|
+
catch: (e) => e
|
|
176
|
+
}).pipe(e.catch((t) => t instanceof h ? e.fail(t) : e.die(t))), yield* e.promise(() => E(t, async (e) => {
|
|
177
|
+
let t = c(b).where(n(i("reservationId", r.reservationId), r.tenantId === null ? s("tenantId") : i("tenantId", r.tenantId))).descriptor, [a] = await e.query(t);
|
|
178
|
+
if (!a) return "not-found";
|
|
179
|
+
if (a.releasedAt !== null) return "already-released";
|
|
180
|
+
let o = /* @__PURE__ */ new Date();
|
|
181
|
+
if (await e.updateMany("_voltro_ai_budget_reservations", {
|
|
182
|
+
releasedAt: o,
|
|
183
|
+
updatedAt: o
|
|
184
|
+
}, { where: n(i("id", a.id), s("releasedAt")) }) !== 1) {
|
|
185
|
+
let [n] = await e.query(t);
|
|
186
|
+
if (n !== void 0 && n.releasedAt !== null) return "already-released";
|
|
187
|
+
throw new x("AI budget release raced; retry");
|
|
188
|
+
}
|
|
189
|
+
let [l] = await e.query(c(y).where(i("bucket", a.bucket)).descriptor);
|
|
190
|
+
if (!l || l.tenantId !== r.tenantId) throw Error("AI budget counter missing or mismatched; refusing unproved credit");
|
|
191
|
+
let u = C(l.reservedMicroUsd), d = C(a.amountMicroUsd);
|
|
192
|
+
if (d > u) throw Error("AI budget receipt exceeds its counter; refusing unproved credit");
|
|
193
|
+
if (await e.updateMany("_voltro_ai_budget", {
|
|
194
|
+
reservedMicroUsd: String(u - d),
|
|
195
|
+
updatedAt: o
|
|
196
|
+
}, { where: n(i("id", l.id), i("reservedMicroUsd", l.reservedMicroUsd)) }) !== 1) throw new x("AI budget counter changed; discard this release and retry");
|
|
197
|
+
return "released";
|
|
198
|
+
}));
|
|
199
|
+
});
|
|
200
|
+
//#endregion
|
|
201
|
+
export { v as AI_BUDGET_RESERVATIONS_TABLE, _ as AI_BUDGET_TABLE, m as AiBudgetExceeded, h as AiBudgetInvalidInput, g as AiBudgetReservationConflict, b as aiBudgetReservationsTable, y as aiBudgetTable, A as releaseAiBudget, k as requireAiBudget };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { gatewayCostUsd as e } from "./cost.js";
|
|
2
|
+
import { Schema as t } from "effect";
|
|
3
|
+
//#region src/callEvidence.ts
|
|
4
|
+
var n = t.Number.pipe(t.check(t.isInt()), t.check(t.isGreaterThanOrEqualTo(0)), t.check(t.isLessThanOrEqualTo(2 ** 53 - 1))), r = t.Struct({
|
|
5
|
+
provider: t.String,
|
|
6
|
+
model: t.String,
|
|
7
|
+
usage: t.Struct({
|
|
8
|
+
inputTokens: t.optional(n),
|
|
9
|
+
outputTokens: t.optional(n),
|
|
10
|
+
totalTokens: t.optional(n),
|
|
11
|
+
completeness: t.Literals([
|
|
12
|
+
"complete",
|
|
13
|
+
"partial",
|
|
14
|
+
"unknown"
|
|
15
|
+
])
|
|
16
|
+
}),
|
|
17
|
+
cost: t.Union([t.Struct({
|
|
18
|
+
status: t.Literal("actual"),
|
|
19
|
+
source: t.Literal("gateway"),
|
|
20
|
+
usd: t.Number.pipe(t.check(t.isFinite()), t.check(t.isGreaterThanOrEqualTo(0)))
|
|
21
|
+
}), t.Struct({
|
|
22
|
+
status: t.Literal("unknown"),
|
|
23
|
+
source: t.Literal("unreported")
|
|
24
|
+
})])
|
|
25
|
+
}), i = (e) => typeof e == "number" && Number.isSafeInteger(e) && e >= 0 ? e : void 0, a = (t, n, r, a) => {
|
|
26
|
+
let o = typeof r == "object" && r ? r : {}, s = i("inputTokens" in o ? o.inputTokens : void 0), c = i("outputTokens" in o ? o.outputTokens : void 0), l = i("totalTokens" in o ? o.totalTokens : void 0), u = [
|
|
27
|
+
s,
|
|
28
|
+
c,
|
|
29
|
+
l
|
|
30
|
+
].filter((e) => e !== void 0).length, d = e(a);
|
|
31
|
+
return {
|
|
32
|
+
provider: t,
|
|
33
|
+
model: n,
|
|
34
|
+
usage: {
|
|
35
|
+
...s === void 0 ? {} : { inputTokens: s },
|
|
36
|
+
...c === void 0 ? {} : { outputTokens: c },
|
|
37
|
+
...l === void 0 ? {} : { totalTokens: l },
|
|
38
|
+
completeness: u === 3 ? "complete" : u === 0 ? "unknown" : "partial"
|
|
39
|
+
},
|
|
40
|
+
cost: d === void 0 ? {
|
|
41
|
+
status: "unknown",
|
|
42
|
+
source: "unreported"
|
|
43
|
+
} : {
|
|
44
|
+
status: "actual",
|
|
45
|
+
source: "gateway",
|
|
46
|
+
usd: d
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
//#endregion
|
|
51
|
+
export { r as AiCallEvidenceSchema, a as normalizeAiCallEvidence };
|
package/dist/copilot.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { Schema as e } from "effect";
|
|
2
|
+
import { and as t, contains as n, eq as r, gt as i, gte as a, inSet as o, lt as s, lte as c, neq as l } from "@voltro/database";
|
|
3
|
+
//#region src/copilot.ts
|
|
4
|
+
var u = class extends e.TaggedError()("CopilotRejected", {
|
|
5
|
+
reason: e.Literals([
|
|
6
|
+
"unknown-table",
|
|
7
|
+
"unknown-column",
|
|
8
|
+
"bad-op",
|
|
9
|
+
"bad-aggregate",
|
|
10
|
+
"empty"
|
|
11
|
+
]),
|
|
12
|
+
detail: e.String
|
|
13
|
+
}) {}, d = 200, f = 50, p = /* @__PURE__ */ new Set([
|
|
14
|
+
"eq",
|
|
15
|
+
"neq",
|
|
16
|
+
"gt",
|
|
17
|
+
"gte",
|
|
18
|
+
"lt",
|
|
19
|
+
"lte",
|
|
20
|
+
"contains",
|
|
21
|
+
"in"
|
|
22
|
+
]), m = (e) => {
|
|
23
|
+
switch (e.op) {
|
|
24
|
+
case "eq": return r(e.column, e.value);
|
|
25
|
+
case "neq": return l(e.column, e.value);
|
|
26
|
+
case "gt": return i(e.column, e.value);
|
|
27
|
+
case "gte": return a(e.column, e.value);
|
|
28
|
+
case "lt": return s(e.column, e.value);
|
|
29
|
+
case "lte": return c(e.column, e.value);
|
|
30
|
+
case "contains": return n(e.column, e.value);
|
|
31
|
+
case "in": return o(e.column, Array.isArray(e.value) ? e.value : [e.value]);
|
|
32
|
+
}
|
|
33
|
+
}, h = (e, t) => ({
|
|
34
|
+
ok: !1,
|
|
35
|
+
rejection: new u({
|
|
36
|
+
reason: e,
|
|
37
|
+
detail: t
|
|
38
|
+
})
|
|
39
|
+
}), g = (e, n) => {
|
|
40
|
+
let r = n.tables.find((t) => t.name === e.table);
|
|
41
|
+
if (r === void 0) return h("unknown-table", e.table);
|
|
42
|
+
let i = new Set(r.columns.map((e) => e.name));
|
|
43
|
+
for (let t of e.columns ?? []) if (!i.has(t)) return h("unknown-column", `${e.table}.${t}`);
|
|
44
|
+
for (let t of e.filters ?? []) {
|
|
45
|
+
if (!p.has(t.op)) return h("bad-op", String(t.op));
|
|
46
|
+
if (!i.has(t.column)) return h("unknown-column", `${e.table}.${t.column}`);
|
|
47
|
+
}
|
|
48
|
+
if (e.orderBy !== void 0 && !i.has(e.orderBy.column)) return h("unknown-column", `${e.table}.${e.orderBy.column}`);
|
|
49
|
+
if (e.aggregate !== void 0) {
|
|
50
|
+
let { fn: t, column: n } = e.aggregate;
|
|
51
|
+
if (t !== "count" && (n === void 0 || !i.has(n))) return h("bad-aggregate", `${t}(${n ?? "∅"})`);
|
|
52
|
+
}
|
|
53
|
+
let a = e.filters ?? [], o = a.length === 0 ? void 0 : a.length === 1 ? m(a[0]) : t(...a.map(m)), s = Math.min(Math.max(1, e.limit ?? f), 200), c = {
|
|
54
|
+
table: e.table,
|
|
55
|
+
predicate: o,
|
|
56
|
+
order: e.orderBy ? [{
|
|
57
|
+
column: e.orderBy.column,
|
|
58
|
+
direction: e.orderBy.direction ?? "asc"
|
|
59
|
+
}] : [],
|
|
60
|
+
take: s,
|
|
61
|
+
skip: void 0,
|
|
62
|
+
projection: e.columns && e.columns.length > 0 ? [...e.columns] : void 0
|
|
63
|
+
};
|
|
64
|
+
return e.aggregate ? {
|
|
65
|
+
ok: !0,
|
|
66
|
+
descriptor: c,
|
|
67
|
+
table: e.table,
|
|
68
|
+
aggregate: e.aggregate
|
|
69
|
+
} : {
|
|
70
|
+
ok: !0,
|
|
71
|
+
descriptor: c,
|
|
72
|
+
table: e.table
|
|
73
|
+
};
|
|
74
|
+
}, _ = e.Struct({
|
|
75
|
+
table: e.String,
|
|
76
|
+
columns: e.optional(e.Array(e.String)),
|
|
77
|
+
filters: e.optional(e.Array(e.Struct({
|
|
78
|
+
column: e.String,
|
|
79
|
+
op: e.Literals([
|
|
80
|
+
"eq",
|
|
81
|
+
"neq",
|
|
82
|
+
"gt",
|
|
83
|
+
"gte",
|
|
84
|
+
"lt",
|
|
85
|
+
"lte",
|
|
86
|
+
"contains",
|
|
87
|
+
"in"
|
|
88
|
+
]),
|
|
89
|
+
value: e.Unknown
|
|
90
|
+
}))),
|
|
91
|
+
orderBy: e.optional(e.Struct({
|
|
92
|
+
column: e.String,
|
|
93
|
+
direction: e.optional(e.Literals(["asc", "desc"]))
|
|
94
|
+
})),
|
|
95
|
+
limit: e.optional(e.Number),
|
|
96
|
+
aggregate: e.optional(e.Struct({
|
|
97
|
+
fn: e.Literals([
|
|
98
|
+
"count",
|
|
99
|
+
"sum",
|
|
100
|
+
"avg",
|
|
101
|
+
"min",
|
|
102
|
+
"max"
|
|
103
|
+
]),
|
|
104
|
+
column: e.optional(e.String)
|
|
105
|
+
}))
|
|
106
|
+
}), v = (e) => [
|
|
107
|
+
"You are a data copilot. Translate the user question into a JSON query proposal.",
|
|
108
|
+
"",
|
|
109
|
+
"You may ONLY reference these tables and columns:",
|
|
110
|
+
e.tables.map((e) => `- ${e.name}(${e.columns.map((e) => e.name).join(", ")})`).join("\n"),
|
|
111
|
+
"",
|
|
112
|
+
"Rules:",
|
|
113
|
+
"- Pick EXACTLY ONE table from the list as `table`.",
|
|
114
|
+
"- Every column in `columns`, `filters`, `orderBy`, and `aggregate` MUST be one of that table's listed columns.",
|
|
115
|
+
"- NEVER invent a table or column. If the question cannot be answered from the listed schema, pick the closest table and leave filters empty.",
|
|
116
|
+
"- The query is READ-ONLY. You cannot insert, update, or delete.",
|
|
117
|
+
"- Keep the result small (limit ≤ 200)."
|
|
118
|
+
].join("\n"), y = async (e, t, n) => {
|
|
119
|
+
let r = v(t);
|
|
120
|
+
return g(await n.propose({
|
|
121
|
+
system: r,
|
|
122
|
+
prompt: e
|
|
123
|
+
}), t);
|
|
124
|
+
};
|
|
125
|
+
//#endregion
|
|
126
|
+
export { d as COPILOT_MAX_LIMIT, _ as CopilotProposalSchema, u as CopilotRejected, v as buildCopilotSystemPrompt, y as runDataCopilot, g as validateCopilotProposal };
|
package/dist/cost.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { AI_BUDGET_RESERVATIONS_TABLE as e, AI_BUDGET_TABLE as t, AiBudgetExceeded as n, AiBudgetInvalidInput as r, AiBudgetReservationConflict as i, aiBudgetReservationsTable as a, aiBudgetTable as o, releaseAiBudget as s, requireAiBudget as c } from "./budget.js";
|
|
2
|
+
import { Data as l, Effect as u } from "effect";
|
|
3
|
+
import { and as d, eq as f, generateId as p, gte as m, id as h, integer as g, queryFor as _, registerRetention as v, retentionTtlMsFromEnv as y, table as b, text as x, timestamp as S } from "@voltro/database";
|
|
4
|
+
//#region src/cost.ts
|
|
5
|
+
var C = {
|
|
6
|
+
"claude-opus-4-8": {
|
|
7
|
+
inputPer1M: 15,
|
|
8
|
+
outputPer1M: 75
|
|
9
|
+
},
|
|
10
|
+
"claude-opus-4-6": {
|
|
11
|
+
inputPer1M: 15,
|
|
12
|
+
outputPer1M: 75
|
|
13
|
+
},
|
|
14
|
+
"claude-sonnet-4-6": {
|
|
15
|
+
inputPer1M: 3,
|
|
16
|
+
outputPer1M: 15
|
|
17
|
+
},
|
|
18
|
+
"claude-haiku-4-5": {
|
|
19
|
+
inputPer1M: 1,
|
|
20
|
+
outputPer1M: 5
|
|
21
|
+
},
|
|
22
|
+
"claude-haiku-4-5-20251001": {
|
|
23
|
+
inputPer1M: 1,
|
|
24
|
+
outputPer1M: 5
|
|
25
|
+
},
|
|
26
|
+
"gpt-5.5": {
|
|
27
|
+
inputPer1M: 5,
|
|
28
|
+
outputPer1M: 30
|
|
29
|
+
},
|
|
30
|
+
"gpt-4o": {
|
|
31
|
+
inputPer1M: 2.5,
|
|
32
|
+
outputPer1M: 10
|
|
33
|
+
},
|
|
34
|
+
"gpt-4o-mini": {
|
|
35
|
+
inputPer1M: .15,
|
|
36
|
+
outputPer1M: .6
|
|
37
|
+
},
|
|
38
|
+
"gemini-2.5-pro": {
|
|
39
|
+
inputPer1M: 1.25,
|
|
40
|
+
outputPer1M: 10
|
|
41
|
+
},
|
|
42
|
+
"gemini-2.5-flash": {
|
|
43
|
+
inputPer1M: .3,
|
|
44
|
+
outputPer1M: 2.5
|
|
45
|
+
},
|
|
46
|
+
"gemini-2.0-flash": {
|
|
47
|
+
inputPer1M: .1,
|
|
48
|
+
outputPer1M: .4
|
|
49
|
+
}
|
|
50
|
+
}, w = {}, T = (e) => {
|
|
51
|
+
let t = w;
|
|
52
|
+
return w = { ...e }, t;
|
|
53
|
+
}, E = () => ({
|
|
54
|
+
...C,
|
|
55
|
+
...w
|
|
56
|
+
}), D = (e) => {
|
|
57
|
+
let t = E();
|
|
58
|
+
if (t[e] !== void 0) return t[e];
|
|
59
|
+
let n = e.indexOf("/");
|
|
60
|
+
if (n > 0) {
|
|
61
|
+
let r = e.slice(n + 1);
|
|
62
|
+
if (t[r] !== void 0) return t[r];
|
|
63
|
+
}
|
|
64
|
+
}, O = (e) => typeof e.unit == "string", k = (e) => O(e) ? {
|
|
65
|
+
unit: e.unit,
|
|
66
|
+
input: e.input ?? 0,
|
|
67
|
+
output: e.output ?? 0
|
|
68
|
+
} : {
|
|
69
|
+
unit: "tokens",
|
|
70
|
+
input: e.inputTokens ?? 0,
|
|
71
|
+
output: e.outputTokens ?? 0
|
|
72
|
+
}, A = (e, t) => {
|
|
73
|
+
let { unit: n, input: r, output: i } = k(e);
|
|
74
|
+
if (t.actualCostUsd !== void 0) {
|
|
75
|
+
if (!Number.isFinite(t.actualCostUsd) || t.actualCostUsd < 0) throw RangeError("estimateCostUsd: actualCostUsd must be a finite, non-negative USD amount.");
|
|
76
|
+
let e = r + i, a = e > 0 ? r / e : 0;
|
|
77
|
+
return {
|
|
78
|
+
inputTokens: r,
|
|
79
|
+
outputTokens: i,
|
|
80
|
+
inputCostUsd: t.actualCostUsd * a,
|
|
81
|
+
outputCostUsd: t.actualCostUsd * (1 - a),
|
|
82
|
+
totalCostUsd: t.actualCostUsd,
|
|
83
|
+
costSource: "gateway",
|
|
84
|
+
unit: n
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (n !== "tokens" && t.price === void 0) return {
|
|
88
|
+
inputTokens: r,
|
|
89
|
+
outputTokens: i,
|
|
90
|
+
inputCostUsd: 0,
|
|
91
|
+
outputCostUsd: 0,
|
|
92
|
+
totalCostUsd: 0,
|
|
93
|
+
costSource: "unpriced",
|
|
94
|
+
unit: n
|
|
95
|
+
};
|
|
96
|
+
let a = t.price ?? D(t.model) ?? {
|
|
97
|
+
inputPer1M: 0,
|
|
98
|
+
outputPer1M: 0
|
|
99
|
+
}, o = r / 1e6 * a.inputPer1M, s = i / 1e6 * a.outputPer1M;
|
|
100
|
+
return {
|
|
101
|
+
inputTokens: r,
|
|
102
|
+
outputTokens: i,
|
|
103
|
+
inputCostUsd: o,
|
|
104
|
+
outputCostUsd: s,
|
|
105
|
+
totalCostUsd: o + s,
|
|
106
|
+
costSource: "estimated",
|
|
107
|
+
unit: n
|
|
108
|
+
};
|
|
109
|
+
}, j = "_voltro_ai_usage", M = b(j, {
|
|
110
|
+
id: h({ prefix: "aiu" }),
|
|
111
|
+
tenantId: x().nullable(),
|
|
112
|
+
provider: x(),
|
|
113
|
+
model: x(),
|
|
114
|
+
operation: x(),
|
|
115
|
+
agent: x().nullable(),
|
|
116
|
+
inputTokens: g().default(0),
|
|
117
|
+
outputTokens: g().default(0),
|
|
118
|
+
costMicroUsd: g().default(0),
|
|
119
|
+
costSource: x().default("estimated"),
|
|
120
|
+
unit: x().default("tokens"),
|
|
121
|
+
promptId: x().nullable(),
|
|
122
|
+
promptDigest: x().nullable(),
|
|
123
|
+
promptRevision: g().nullable(),
|
|
124
|
+
requestId: x().maxLength(191).nullable(),
|
|
125
|
+
attempt: g().nullable(),
|
|
126
|
+
receiptKey: x().maxLength(191).backfill((e) => `aiu-pre-receipt-${String(e.id)}`),
|
|
127
|
+
calledAt: S().default("now")
|
|
128
|
+
}).index(["tenantId"]).index(["promptDigest"]).unique("byAiUsageReceipt", ["receiptKey"]), N = (e) => {
|
|
129
|
+
let t = typeof e == "string" ? e.trim() : void 0, n = typeof e == "number" ? e : t !== void 0 && /^(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(t) ? Number(t) : NaN;
|
|
130
|
+
return Number.isFinite(n) && n >= 0 ? n : void 0;
|
|
131
|
+
}, P = (e) => {
|
|
132
|
+
let t = e?.gateway, n = N(t?.cost);
|
|
133
|
+
if (n === void 0) return;
|
|
134
|
+
let r = (Array.isArray(t?.routing?.modelAttempts) ? t.routing.modelAttempts : []).findLast((e) => e?.success === !0);
|
|
135
|
+
if ((Array.isArray(r?.providerAttempts) ? r.providerAttempts : []).findLast((e) => e?.success === !0)?.credentialType !== "byok") return n;
|
|
136
|
+
let i = N(t?.marketCost);
|
|
137
|
+
return i === void 0 ? void 0 : n + i;
|
|
138
|
+
}, F = class extends l.TaggedError("AiUsageReceiptConflict") {
|
|
139
|
+
get message() {
|
|
140
|
+
let e = Object.keys(this.recorded).filter((e) => this.recorded[e] !== this.attempted[e]).map((e) => `${e} ${String(this.recorded[e])} → ${String(this.attempted[e])}`);
|
|
141
|
+
return `AI usage receipt ${this.receiptKey} was recorded again with different values (${e.join(", ")}). A replay of the same paid call has the same values; the row keeps what was recorded first.`;
|
|
142
|
+
}
|
|
143
|
+
}, I = class extends l.TaggedError("AiUsageLedgerError") {
|
|
144
|
+
get message() {
|
|
145
|
+
return `AI usage receipt ${this.receiptKey} could not be written: ${this.cause instanceof Error ? this.cause.message : String(this.cause)}`;
|
|
146
|
+
}
|
|
147
|
+
}, L = (e) => ({
|
|
148
|
+
tenantId: e.tenantId ?? null,
|
|
149
|
+
provider: String(e.provider),
|
|
150
|
+
model: String(e.model),
|
|
151
|
+
operation: String(e.operation),
|
|
152
|
+
inputTokens: Number(e.inputTokens),
|
|
153
|
+
outputTokens: Number(e.outputTokens),
|
|
154
|
+
costMicroUsd: Number(e.costMicroUsd)
|
|
155
|
+
}), R = (e, t) => (v({
|
|
156
|
+
source: "plugin",
|
|
157
|
+
table: j,
|
|
158
|
+
timeColumn: "calledAt",
|
|
159
|
+
ttlMs: y(process.env.VOLTRO_AI_USAGE_TTL_HOURS, 8760)
|
|
160
|
+
}), u.gen(function* () {
|
|
161
|
+
let n = A(t.usage, {
|
|
162
|
+
model: t.model,
|
|
163
|
+
...t.price === void 0 ? {} : { price: t.price },
|
|
164
|
+
...t.actualCostUsd === void 0 ? {} : { actualCostUsd: t.actualCostUsd }
|
|
165
|
+
}), r = t.receiptKey ?? (t.requestId === void 0 ? p({
|
|
166
|
+
kind: "typeid",
|
|
167
|
+
prefix: "aiu"
|
|
168
|
+
}, "_voltro_ai_usage") : `${t.requestId}#${t.attempt ?? 0}`), i = {
|
|
169
|
+
tenantId: t.tenantId ?? null,
|
|
170
|
+
provider: t.provider,
|
|
171
|
+
model: t.model,
|
|
172
|
+
operation: t.operation,
|
|
173
|
+
agent: t.agent ?? null,
|
|
174
|
+
inputTokens: n.inputTokens,
|
|
175
|
+
outputTokens: n.outputTokens,
|
|
176
|
+
costMicroUsd: Math.round(n.totalCostUsd * 1e6),
|
|
177
|
+
costSource: n.costSource,
|
|
178
|
+
unit: n.unit,
|
|
179
|
+
promptId: t.prompt?.promptId ?? null,
|
|
180
|
+
promptDigest: t.prompt?.digest ?? null,
|
|
181
|
+
promptRevision: t.prompt?.revision ?? null,
|
|
182
|
+
requestId: t.requestId ?? null,
|
|
183
|
+
attempt: t.attempt ?? null,
|
|
184
|
+
receiptKey: r,
|
|
185
|
+
calledAt: t.calledAt ?? /* @__PURE__ */ new Date()
|
|
186
|
+
}, a = yield* u.tryPromise({
|
|
187
|
+
try: () => e.insertIgnoreWithOutcome(j, i, { conflictColumns: ["receiptKey"] }),
|
|
188
|
+
catch: (e) => new I({
|
|
189
|
+
receiptKey: String(r),
|
|
190
|
+
cause: e
|
|
191
|
+
})
|
|
192
|
+
});
|
|
193
|
+
if (a.outcome === "inserted") return {
|
|
194
|
+
...n,
|
|
195
|
+
receipt: "recorded"
|
|
196
|
+
};
|
|
197
|
+
let o = L(a.row), s = L(i);
|
|
198
|
+
return Object.keys(o).some((e) => o[e] !== s[e]) ? yield* u.fail(new F({
|
|
199
|
+
receiptKey: String(r),
|
|
200
|
+
recorded: o,
|
|
201
|
+
attempted: s
|
|
202
|
+
})) : {
|
|
203
|
+
...z(a.row, n),
|
|
204
|
+
receipt: "replayed"
|
|
205
|
+
};
|
|
206
|
+
})), z = (e, t) => {
|
|
207
|
+
let n = Number(e.costMicroUsd) / 1e6;
|
|
208
|
+
return {
|
|
209
|
+
...t,
|
|
210
|
+
inputTokens: Number(e.inputTokens),
|
|
211
|
+
outputTokens: Number(e.outputTokens),
|
|
212
|
+
totalCostUsd: n,
|
|
213
|
+
costSource: e.costSource ?? t.costSource
|
|
214
|
+
};
|
|
215
|
+
}, B = (e, t) => R(e, t).pipe(u.asVoid, u.catchCause((e) => u.logError("AI usage NOT booked as recorded — the call itself succeeded and was returned", e).pipe(u.annotateLogs({
|
|
216
|
+
scope: "voltro:ai:usage",
|
|
217
|
+
provider: t.provider,
|
|
218
|
+
model: t.model,
|
|
219
|
+
operation: t.operation,
|
|
220
|
+
...O(t.usage) ? {
|
|
221
|
+
unit: t.usage.unit,
|
|
222
|
+
input: t.usage.input ?? null,
|
|
223
|
+
output: t.usage.output ?? null
|
|
224
|
+
} : {
|
|
225
|
+
inputTokens: t.usage.inputTokens ?? null,
|
|
226
|
+
outputTokens: t.usage.outputTokens ?? null
|
|
227
|
+
},
|
|
228
|
+
...t.requestId === void 0 ? {} : {
|
|
229
|
+
requestId: t.requestId,
|
|
230
|
+
attempt: t.attempt ?? 0
|
|
231
|
+
},
|
|
232
|
+
...t.actualCostUsd === void 0 ? {} : { actualCostUsd: t.actualCostUsd }
|
|
233
|
+
})))), V = (e, t = {}) => u.promise(async () => {
|
|
234
|
+
let n = [
|
|
235
|
+
...t.tenantId === void 0 ? [] : [f("tenantId", t.tenantId)],
|
|
236
|
+
...t.since === void 0 ? [] : [m("calledAt", t.since)],
|
|
237
|
+
...t.promptDigest === void 0 ? [] : [f("promptDigest", t.promptDigest)]
|
|
238
|
+
], r = _(M), i = n.length === 0 ? r : r.where(n.length === 1 ? n[0] : d(...n));
|
|
239
|
+
return (await e.query(i.descriptor)).reduce((e, t) => e + (Number(t.costMicroUsd) || 0), 0) / 1e6;
|
|
240
|
+
});
|
|
241
|
+
//#endregion
|
|
242
|
+
export { e as AI_BUDGET_RESERVATIONS_TABLE, t as AI_BUDGET_TABLE, j as AI_USAGE_TABLE, n as AiBudgetExceeded, r as AiBudgetInvalidInput, i as AiBudgetReservationConflict, I as AiUsageLedgerError, F as AiUsageReceiptConflict, C as MODEL_PRICING_DEFAULTS, a as aiBudgetReservationsTable, o as aiBudgetTable, V as aiSpendUsd, M as aiUsageTable, A as estimateCostUsd, P as gatewayCostUsd, O as isMeteredUsage, E as modelPricing, k as normaliseUsage, D as priceForModel, R as recordAiUsage, B as recordAiUsageBestEffort, s as releaseAiBudget, c as requireAiBudget, T as setModelPricing };
|