@lightblues/jig 0.0.6 → 0.0.8

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.
@@ -0,0 +1,211 @@
1
+ export const initialState = { messages: [], live: null, error: null, connected: false, last: null, history: false };
2
+ /**
3
+ * Folds one AG-UI event into the thread state, without changing `state`. Follows the follower contract of
4
+ * agent-paseo and agent-pi: `CUSTOM READY` drops the run being drawn (the stream resyncs: `RUN_STARTED` and a replay
5
+ * follow when one is running), so a reconnect or a server-side gap never duplicates text. Unknown events return
6
+ * `state` unchanged.
7
+ */
8
+ export function reduce(state, event) {
9
+ const e = event;
10
+ const meta = (e.metadata ?? {});
11
+ switch (e.type) {
12
+ case "CUSTOM": {
13
+ if (e.name !== "READY")
14
+ return state;
15
+ const running = Boolean(e.value?.running);
16
+ const last = state.live && !running ? { runId: state.live.runId, status: "unknown" } : state.last;
17
+ return { ...state, live: null, last };
18
+ }
19
+ case "MESSAGES_SNAPSHOT":
20
+ return { ...state, messages: Array.isArray(e.messages) ? e.messages : [], history: true };
21
+ case "RUN_STARTED": {
22
+ // A run still open here missed its end (the server closes it before the next starts; this is the fallback).
23
+ const prev = state.live && state.live.runId !== String(e.runId) ? settle(state) : state;
24
+ return {
25
+ ...prev,
26
+ error: null,
27
+ live: { runId: String(e.runId), threadId: String(e.threadId), metadata: e.metadata ?? null, user: null, text: "", reasoning: "", tools: [], activities: [], parts: [] },
28
+ };
29
+ }
30
+ case "RUN_FINISHED": {
31
+ if (!state.live && state.last?.runId === e.runId)
32
+ return state;
33
+ // The end of another run (a recovered one announced late) is recorded, but does not end the one being drawn.
34
+ const other = Boolean(state.live && e.runId && state.live.runId !== String(e.runId));
35
+ const error = typeof meta.error === "string" ? meta.error : undefined;
36
+ const stopped = Boolean(meta.stopped) || e.outcome?.type === "cancelled";
37
+ const status = error ? "error" : stopped ? "stopped" : "done";
38
+ const last = { runId: String(e.runId), status, ...(e.result !== undefined ? { result: e.result } : {}), ...(error ? { error } : {}) };
39
+ return other ? { ...state, last } : { ...settle(state), live: null, last, error: null };
40
+ }
41
+ case "RUN_ERROR": {
42
+ const message = String(e.message ?? "error");
43
+ const runId = String(meta.runId ?? state.live?.runId ?? "");
44
+ const last = { runId, status: "error", error: message };
45
+ if (state.live && meta.runId && state.live.runId !== runId)
46
+ return { ...state, last };
47
+ return { ...settle(state), live: null, error: message, last };
48
+ }
49
+ }
50
+ const live = state.live;
51
+ if (!live)
52
+ return activityOutside(state, e);
53
+ const next = run(live, e, meta);
54
+ return next === live ? state : { ...state, live: next };
55
+ }
56
+ /** One event of the run in progress. Returns `live` itself when nothing changed. */
57
+ function run(live, e, meta) {
58
+ switch (e.type) {
59
+ case "TEXT_MESSAGE_START":
60
+ case "TEXT_MESSAGE_CHUNK":
61
+ case "TEXT_MESSAGE_CONTENT": {
62
+ const id = String(e.messageId ?? "");
63
+ const delta = typeof e.delta === "string" ? e.delta : "";
64
+ if (e.role === "user" || (live.user && live.user.id === id)) {
65
+ const user = live.user?.id === id ? live.user : { id, text: "" };
66
+ return delta ? { ...live, user: { id, text: user.text + delta } } : live.user === user ? live : { ...live, user };
67
+ }
68
+ if (e.type !== "TEXT_MESSAGE_START" && !delta)
69
+ return live;
70
+ return withText(live, "text", id, delta);
71
+ }
72
+ case "REASONING_MESSAGE_START":
73
+ case "REASONING_MESSAGE_CHUNK":
74
+ case "REASONING_MESSAGE_CONTENT": {
75
+ const delta = typeof e.delta === "string" ? e.delta : "";
76
+ if (e.type !== "REASONING_MESSAGE_START" && !delta)
77
+ return live;
78
+ return withText(live, "reasoning", String(e.messageId ?? ""), delta);
79
+ }
80
+ case "TOOL_CALL_START": {
81
+ const id = String(e.toolCallId);
82
+ if (live.tools.some((t) => t.id === id))
83
+ return live;
84
+ const tool = { id, name: String(e.toolCallName ?? ""), summary: str(meta.summary), args: "", status: "running", done: false };
85
+ return { ...live, tools: [...live.tools, tool], parts: [...live.parts, { kind: "tool", id }] };
86
+ }
87
+ case "TOOL_CALL_ARGS": {
88
+ const delta = typeof e.delta === "string" ? e.delta : "";
89
+ return tool(live, String(e.toolCallId), (t) => {
90
+ let summary = t.summary;
91
+ try {
92
+ const v = JSON.parse(delta);
93
+ if (v && typeof v === "object" && "summary" in v)
94
+ summary = str(v.summary) ?? summary;
95
+ }
96
+ catch { }
97
+ return { ...t, args: t.args + delta, summary };
98
+ });
99
+ }
100
+ case "TOOL_CALL_END":
101
+ return tool(live, String(e.toolCallId), (t) => ({
102
+ ...t,
103
+ done: true,
104
+ status: str(meta.status) ?? (meta.isError === true ? "failed" : "completed"),
105
+ }));
106
+ case "ACTIVITY_SNAPSHOT": {
107
+ const id = String(e.messageId);
108
+ const at = live.activities.findIndex((a) => a.id === id);
109
+ const a = { id, activityType: String(e.activityType), content: (e.content ?? {}) };
110
+ if (at < 0)
111
+ return { ...live, activities: [...live.activities, a], parts: [...live.parts, { kind: "activity", id }] };
112
+ if (e.replace === false)
113
+ return live;
114
+ return { ...live, activities: live.activities.map((x, i) => (i === at ? a : x)) };
115
+ }
116
+ }
117
+ return live;
118
+ }
119
+ function withText(live, kind, id, delta) {
120
+ const at = live.parts.findIndex((p) => p.kind === kind && p.id === id);
121
+ const parts = live.parts.slice();
122
+ if (at < 0)
123
+ parts.push({ kind, id, text: delta });
124
+ else if (delta)
125
+ parts[at] = { kind, id, text: parts[at].text + delta };
126
+ else
127
+ return live;
128
+ const joined = parts
129
+ .filter((p) => p.kind === kind)
130
+ .map((p) => p.text)
131
+ .filter(Boolean)
132
+ .join("\n\n");
133
+ return { ...live, parts, [kind]: joined };
134
+ }
135
+ function tool(live, id, f) {
136
+ const at = live.tools.findIndex((t) => t.id === id);
137
+ if (at < 0)
138
+ return live;
139
+ return { ...live, tools: live.tools.map((t, i) => (i === at ? f(t) : t)) };
140
+ }
141
+ /** A card outside a run joins the history when the stream carries one; otherwise it has nowhere to go. */
142
+ function activityOutside(state, e) {
143
+ if (e.type !== "ACTIVITY_SNAPSHOT" || !state.history)
144
+ return state;
145
+ const m = { id: String(e.messageId), role: "activity", activityType: String(e.activityType), content: e.content ?? {} };
146
+ const at = state.messages.findIndex((x) => x.id === m.id);
147
+ if (at >= 0 && e.replace === false)
148
+ return state;
149
+ return { ...state, messages: at < 0 ? [...state.messages, m] : state.messages.map((x, i) => (i === at ? m : x)) };
150
+ }
151
+ /** A run that ended moves into the history, when the stream carries one. */
152
+ function settle(state) {
153
+ if (!state.history || !state.live)
154
+ return state;
155
+ return { ...state, messages: [...state.messages, ...runMessages(state.live)] };
156
+ }
157
+ /** A finished run as AG-UI messages, in agent-paseo's snapshot shape: tool calls grouped in an assistant message, `arguments` = JSON `{summary, status}`. */
158
+ export function runMessages(live) {
159
+ const out = [];
160
+ if (live.user)
161
+ out.push({ id: live.user.id, role: "user", content: live.user.text });
162
+ let group = null;
163
+ for (const p of live.parts) {
164
+ if (p.kind === "text") {
165
+ group = null;
166
+ if (p.text.trim())
167
+ out.push({ id: p.id, role: "assistant", content: p.text });
168
+ }
169
+ else if (p.kind === "reasoning") {
170
+ if (p.text.trim())
171
+ out.push({ id: p.id, role: "reasoning", content: p.text });
172
+ }
173
+ else if (p.kind === "tool") {
174
+ const t = live.tools.find((x) => x.id === p.id);
175
+ if (!group)
176
+ out.push((group = { id: `tools-${t.id}`, role: "assistant", toolCalls: [] }));
177
+ group.toolCalls.push({ id: t.id, type: "function", function: { name: t.name, arguments: JSON.stringify({ summary: t.summary, status: t.status }) } });
178
+ }
179
+ else {
180
+ const a = live.activities.find((x) => x.id === p.id);
181
+ group = null;
182
+ out.push({ id: a.id, role: "activity", activityType: a.activityType, content: a.content });
183
+ }
184
+ }
185
+ return out;
186
+ }
187
+ /**
188
+ * The tool calls of a message, or of a run's tools: `{name, summary, status}` from `toolCalls[].function.arguments`
189
+ * (agent-paseo's snapshot shape: JSON `{summary, status}`).
190
+ */
191
+ export function toolViews(m) {
192
+ if (m.role !== "assistant" || !m.toolCalls)
193
+ return [];
194
+ return m.toolCalls.map((c) => {
195
+ let v = {};
196
+ try {
197
+ v = JSON.parse(c.function.arguments) ?? {};
198
+ }
199
+ catch { }
200
+ return { id: c.id, name: c.function.name, summary: str(v.summary), status: str(v.status) };
201
+ });
202
+ }
203
+ /** One line for a run of tool calls: the count and the last call (`3 steps · Read notes.md`). */
204
+ export function toolLine(tools) {
205
+ const last = tools.at(-1);
206
+ if (!last)
207
+ return "";
208
+ const what = last.summary ? `${last.name} ${last.summary}` : last.name;
209
+ return tools.length > 1 ? `${tools.length} steps · ${what}` : what;
210
+ }
211
+ const str = (v) => (typeof v === "string" ? v : null);
@@ -0,0 +1,13 @@
1
+ import type { BaseEvent } from "@ag-ui/core";
2
+ /** What `readSse` needs from a response: a byte stream (the WHATWG `Response` has it; so do expo/fetch and undici). */
3
+ export interface SseSource {
4
+ body: ReadableStream<Uint8Array> | null;
5
+ }
6
+ /**
7
+ * Reads a `text/event-stream` body as AG-UI events: each SSE event's `data` (lines joined with `\n`) is parsed as JSON
8
+ * and yielded when it has a string `type`. The SSE `event:` name is ignored (hosts name events by type, or `CUSTOM` by
9
+ * its name, for their own logs); comments (`: ping`), `id:` and `retry:` are skipped, and so is data that is not JSON.
10
+ * An event cut off by the end of the stream is dropped, as the SSE spec says, so a connection that breaks in the
11
+ * middle of an event never yields half of it. Stops reading when the iterator is closed (`break`, `return`).
12
+ */
13
+ export declare function readSse(res: SseSource): AsyncGenerator<BaseEvent, void, undefined>;
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Reads a `text/event-stream` body as AG-UI events: each SSE event's `data` (lines joined with `\n`) is parsed as JSON
3
+ * and yielded when it has a string `type`. The SSE `event:` name is ignored (hosts name events by type, or `CUSTOM` by
4
+ * its name, for their own logs); comments (`: ping`), `id:` and `retry:` are skipped, and so is data that is not JSON.
5
+ * An event cut off by the end of the stream is dropped, as the SSE spec says, so a connection that breaks in the
6
+ * middle of an event never yields half of it. Stops reading when the iterator is closed (`break`, `return`).
7
+ */
8
+ export async function* readSse(res) {
9
+ if (!res.body)
10
+ throw new Error("readSse: the response has no body");
11
+ const reader = res.body.getReader();
12
+ const decoder = new TextDecoder();
13
+ let buf = "";
14
+ let data = [];
15
+ let finished = false;
16
+ try {
17
+ for (;;) {
18
+ const { value, done } = await reader.read();
19
+ if (done)
20
+ finished = true;
21
+ else
22
+ buf += decoder.decode(value, { stream: true });
23
+ // Complete lines only: a trailing `\r` may be the first half of `\r\n`, so it waits for the next chunk (or the end).
24
+ let start = 0;
25
+ for (let i = 0; i < buf.length; i++) {
26
+ const c = buf.charCodeAt(i);
27
+ if (c !== 10 && c !== 13)
28
+ continue;
29
+ if (c === 13 && i === buf.length - 1 && !done)
30
+ break;
31
+ const line = buf.slice(start, i);
32
+ if (c === 13 && buf.charCodeAt(i + 1) === 10)
33
+ i++;
34
+ start = i + 1;
35
+ if (line === "") {
36
+ const e = parse(data);
37
+ data = [];
38
+ if (e)
39
+ yield e;
40
+ continue;
41
+ }
42
+ if (line.charCodeAt(0) === 58)
43
+ continue; // ":" comment
44
+ const colon = line.indexOf(":");
45
+ const field = colon < 0 ? line : line.slice(0, colon);
46
+ if (field !== "data")
47
+ continue;
48
+ let v = colon < 0 ? "" : line.slice(colon + 1);
49
+ if (v.charCodeAt(0) === 32)
50
+ v = v.slice(1);
51
+ data.push(v);
52
+ }
53
+ buf = buf.slice(start);
54
+ if (done)
55
+ return;
56
+ }
57
+ }
58
+ finally {
59
+ if (!finished)
60
+ await reader.cancel().catch(() => { });
61
+ reader.releaseLock();
62
+ }
63
+ }
64
+ function parse(data) {
65
+ if (!data.length)
66
+ return null;
67
+ try {
68
+ const e = JSON.parse(data.join("\n"));
69
+ return e && typeof e === "object" && typeof e.type === "string" ? e : null;
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@lightblues/jig/agent-pi`: the server runtime for in-app pi agents (vibeU, erudite, lemma): router models with
3
+ * tiers, sessions and run rows in the host's own tables, and one `AgentSession` run that emits `@ag-ui/core` events.
4
+ * The host keeps auth, tool binding, prompts, tools, budgets and rendering. See `.ea/docs/agent-pi.md`.
5
+ */
6
+ export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.ts";
7
+ export type { ModelPrice, ModelStream, PiModel, PiModels, PiModelsOptions, PurposeModel, Thinking } from "./models.ts";
8
+ export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.ts";
9
+ export type { Card, PiRunEvent, RunAgentOptions, RunLimits, RunResult, RunTool, Turn } from "./run.ts";
10
+ export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.ts";
11
+ export type { PgSessionStoreOptions, Query, RunStart, RunStatus, RunUsage, SessionStore } from "./store.ts";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@lightblues/jig/agent-pi`: the server runtime for in-app pi agents (vibeU, erudite, lemma): router models with
3
+ * tiers, sessions and run rows in the host's own tables, and one `AgentSession` run that emits `@ag-ui/core` events.
4
+ * The host keeps auth, tool binding, prompts, tools, budgets and rendering. See `.ea/docs/agent-pi.md`.
5
+ */
6
+ export { costOf, modelCost, parsePrices, piModels, routerModel, singleModel } from "./models.js";
7
+ export { appendToThread, cutText, DEFAULT_LIMITS, estimateTokens, runAgent, windowEntries, withoutEmptyImages, withoutImages } from "./run.js";
8
+ export { memorySessionStore, newRunId, pgSessionStore, PI_SESSION_DDL } from "./store.js";
@@ -0,0 +1,91 @@
1
+ import type { StreamFn } from "@earendil-works/pi-agent-core";
2
+ import { type Model, type Usage } from "@earendil-works/pi-ai";
3
+ /** A model stream that returns at once, the form pi takes for a registered provider. */
4
+ export type ModelStream = (...args: Parameters<StreamFn>) => Awaited<ReturnType<StreamFn>>;
5
+ /** pi's thinking levels a purpose may ask for; a model without reasoning always runs `off`. */
6
+ export type Thinking = "off" | "minimal" | "low" | "medium" | "high";
7
+ /** One model and how to stream from it. Tests build one from pi-ai's faux provider (`fauxModel`). */
8
+ export interface PiModel {
9
+ id: string;
10
+ model: Model<any>;
11
+ streamFn: ModelStream;
12
+ }
13
+ /** Which tier and how much thinking a kind of run gets. */
14
+ export interface PurposeModel {
15
+ tier: string;
16
+ thinking: Thinking;
17
+ }
18
+ /** US dollars per million tokens; a missing `cacheWrite` is 0. */
19
+ export interface ModelPrice {
20
+ input: number;
21
+ output: number;
22
+ cacheRead: number;
23
+ cacheWrite?: number;
24
+ }
25
+ /** What `runAgent` asks of the models: the model, tier name and thinking level of a purpose. */
26
+ export interface PiModels {
27
+ pick(purpose: string): {
28
+ model: PiModel;
29
+ tier: string;
30
+ thinking: Thinking;
31
+ };
32
+ }
33
+ export interface PiModelsOptions<TTier extends string, TPurpose extends string> {
34
+ /** The OpenAI-compatible router (`…/v1`). */
35
+ baseUrl: string;
36
+ /** The router key. It only lives in `streamFn`; pi's runtime is registered with a dummy key. */
37
+ apiKey: string;
38
+ /** The model id behind each tier (`{ haiku: 'cbi/deepseek-v4.1-flash', … }`). */
39
+ tiers: Record<TTier, string>;
40
+ /** The tier and thinking of each purpose. An unknown purpose throws in `pick`. */
41
+ purposes: Record<TPurpose, {
42
+ tier: TTier;
43
+ thinking: Thinking;
44
+ }>;
45
+ /** Prices by model id; an unpriced model costs 0 (`warn` says so once). */
46
+ prices?: Record<string, ModelPrice>;
47
+ /** The provider name pi registers the models under (the host's name: `erudite`, `vibeu`, `lemma`). Default `jig`. */
48
+ provider?: string;
49
+ /** What the models take. Default `['text', 'image']`. */
50
+ input?: ("text" | "image")[];
51
+ /** Default 128 000. */
52
+ contextWindow?: number;
53
+ /** pi's default output cap; `runAgent` sets its own from `limits`. Default 4 000. */
54
+ maxTokens?: number;
55
+ /** Default `console.warn`. */
56
+ warn?: (message: string) => void;
57
+ }
58
+ /** A model's rates as pi takes them; an unpriced model costs 0. */
59
+ export declare const modelCost: (price: ModelPrice | undefined) => Model<any>["cost"];
60
+ /**
61
+ * `base` with the prices in `json` (an env value, JSON keyed by model id) over them. Malformed JSON keeps `base`;
62
+ * a malformed entry is skipped. `warn` says which.
63
+ */
64
+ export declare function parsePrices(json: string | undefined, base?: Record<string, ModelPrice>, warn?: (message: string) => void): Record<string, ModelPrice>;
65
+ /**
66
+ * One router model. DeepSeek takes `thinking: {type}` and wants its reasoning sent back on later turns; pi detects
67
+ * that only for its own provider, so the compat flags are set here by id.
68
+ */
69
+ export declare function routerModel(id: string, o: {
70
+ baseUrl: string;
71
+ apiKey: string;
72
+ provider?: string;
73
+ price?: ModelPrice;
74
+ input?: ("text" | "image")[];
75
+ contextWindow?: number;
76
+ maxTokens?: number;
77
+ }): PiModel;
78
+ /**
79
+ * The tiers behind an OpenAI-compatible router, and which tier and thinking each purpose gets. The key is injected
80
+ * in each model's `streamFn`, never registered with pi.
81
+ */
82
+ export declare function piModels<TTier extends string, TPurpose extends string>(o: PiModelsOptions<TTier, TPurpose>): PiModels & {
83
+ tier(name: TTier): PiModel;
84
+ };
85
+ /**
86
+ * One model for every purpose, with the purposes' tier names and thinking (tests: a faux model). A purpose not in
87
+ * `purposes` runs as tier `default` without thinking.
88
+ */
89
+ export declare function singleModel(model: PiModel, purposes?: Record<string, PurposeModel>): PiModels;
90
+ /** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
91
+ export declare function costOf(model: PiModel, usage: Usage): number;
@@ -0,0 +1,107 @@
1
+ import { calculateCost } from "@earendil-works/pi-ai";
2
+ import { streamSimple } from "@earendil-works/pi-ai/api/openai-completions";
3
+ /** A model's rates as pi takes them; an unpriced model costs 0. */
4
+ export const modelCost = (price) => price ? { input: price.input, output: price.output, cacheRead: price.cacheRead, cacheWrite: price.cacheWrite ?? 0 } : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
5
+ const isPrice = (value) => {
6
+ const p = value;
7
+ return (!!p &&
8
+ typeof p === "object" &&
9
+ ["input", "output", "cacheRead"].every((k) => typeof p[k] === "number" && p[k] >= 0) &&
10
+ (p.cacheWrite === undefined || (typeof p.cacheWrite === "number" && p.cacheWrite >= 0)));
11
+ };
12
+ /**
13
+ * `base` with the prices in `json` (an env value, JSON keyed by model id) over them. Malformed JSON keeps `base`;
14
+ * a malformed entry is skipped. `warn` says which.
15
+ */
16
+ export function parsePrices(json, base = {}, warn = console.warn) {
17
+ const prices = { ...base };
18
+ if (!json)
19
+ return prices;
20
+ let given;
21
+ try {
22
+ given = JSON.parse(json);
23
+ }
24
+ catch {
25
+ warn("model prices are not JSON; using the built-in prices");
26
+ return prices;
27
+ }
28
+ for (const [id, price] of Object.entries((given && typeof given === "object" ? given : {}))) {
29
+ if (isPrice(price))
30
+ prices[id] = price;
31
+ else
32
+ warn(`model price skipped: ${id}`);
33
+ }
34
+ return prices;
35
+ }
36
+ /**
37
+ * One router model. DeepSeek takes `thinking: {type}` and wants its reasoning sent back on later turns; pi detects
38
+ * that only for its own provider, so the compat flags are set here by id.
39
+ */
40
+ export function routerModel(id, o) {
41
+ const deepseek = /deepseek/i.test(id);
42
+ const model = {
43
+ id,
44
+ name: id,
45
+ api: "openai-completions",
46
+ provider: o.provider ?? "jig",
47
+ baseUrl: o.baseUrl,
48
+ reasoning: true,
49
+ input: o.input ?? ["text", "image"],
50
+ cost: modelCost(o.price),
51
+ contextWindow: o.contextWindow ?? 128_000,
52
+ maxTokens: o.maxTokens ?? 4_000,
53
+ compat: {
54
+ supportsStore: false,
55
+ supportsDeveloperRole: false,
56
+ maxTokensField: "max_tokens",
57
+ ...(deepseek ? { thinkingFormat: "deepseek", requiresReasoningContentOnAssistantMessages: true, supportsReasoningEffort: false } : {}),
58
+ },
59
+ };
60
+ const apiKey = o.apiKey;
61
+ return { id, model, streamFn: (m, context, options) => streamSimple(m, context, { ...options, apiKey }) };
62
+ }
63
+ /**
64
+ * The tiers behind an OpenAI-compatible router, and which tier and thinking each purpose gets. The key is injected
65
+ * in each model's `streamFn`, never registered with pi.
66
+ */
67
+ export function piModels(o) {
68
+ const warn = o.warn ?? console.warn;
69
+ const byTier = new Map();
70
+ for (const [tier, id] of Object.entries(o.tiers)) {
71
+ const price = o.prices?.[id];
72
+ if (o.prices && !price)
73
+ warn(`model ${id} has no price; its runs cost 0`);
74
+ byTier.set(tier, routerModel(id, { ...o, price }));
75
+ }
76
+ for (const [purpose, pick] of Object.entries(o.purposes)) {
77
+ if (!byTier.has(pick.tier))
78
+ throw new Error(`purpose ${purpose} names tier ${pick.tier}, which has no model`);
79
+ }
80
+ return {
81
+ tier: (name) => {
82
+ const model = byTier.get(name);
83
+ if (!model)
84
+ throw new Error(`no model for tier ${name}`);
85
+ return model;
86
+ },
87
+ pick: (purpose) => {
88
+ const pick = o.purposes[purpose];
89
+ if (!pick)
90
+ throw new Error(`unknown purpose ${purpose}`);
91
+ return { model: byTier.get(pick.tier), tier: pick.tier, thinking: pick.thinking };
92
+ },
93
+ };
94
+ }
95
+ /**
96
+ * One model for every purpose, with the purposes' tier names and thinking (tests: a faux model). A purpose not in
97
+ * `purposes` runs as tier `default` without thinking.
98
+ */
99
+ export function singleModel(model, purposes = {}) {
100
+ return { pick: (purpose) => ({ model, tier: purposes[purpose]?.tier ?? "default", thinking: purposes[purpose]?.thinking ?? "off" }) };
101
+ }
102
+ /** A reply's cost: what the provider worked out, else the model's rates over its usage (a faux stream prices nothing). */
103
+ export function costOf(model, usage) {
104
+ if (usage.cost?.total)
105
+ return usage.cost.total;
106
+ return calculateCost(model.model, { ...usage, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }).total;
107
+ }