@cslug/ai 0.4.1 → 0.6.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.
@@ -0,0 +1,187 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { arg, Command, flag, Logger, resolve, ServiceProvider, serveMcpStdio, type Token } from '@cslug/core'
4
+ import type { HttpContext } from '@cslug/http'
5
+ import { PROMPT_VARIABLE } from './agent'
6
+ import { Ai, type AiConfig } from './ai'
7
+ import { AiEvalCommand } from './ai-eval-command'
8
+ import { databaseStore } from './conversation-store'
9
+ import { Conversations } from './conversations'
10
+ import { embedderFor, type TextEmbedder } from './embedders'
11
+ import { setFakeEmbedder } from './fake'
12
+ import { asMcpTools, discoverTools, handleMcp, type McpCaller, type McpReply, mcpTools } from './mcp'
13
+ import type { SearchableIndex } from './search-tools'
14
+
15
+ /** What this package uses of @cslug/search (an optional peer, imported only when installed). */
16
+ type SearchModule = {
17
+ Embedder: Token<TextEmbedder>
18
+ FakeEmbedder: new () => TextEmbedder
19
+ SearchIndex: new (name: string, options: { semantic?: boolean }) => SearchableIndex
20
+ }
21
+
22
+ /**
23
+ * `cslug mcp:serve`: the `@mcp()` tools over stdio, for a local client (every exposed tool: the caller is whoever
24
+ * runs the command). Logs go to stderr; stdout carries only MCP messages.
25
+ */
26
+ export class McpServeCommand extends Command {
27
+ static signature = 'mcp:serve'
28
+ static description = 'Serve the @mcp() tools over stdio (HTTP: POST /mcp on the web server)'
29
+
30
+ async handle() {
31
+ this.app.swap(Logger, new Logger({ write: (line) => process.stderr.write(`${line}\n`) }))
32
+ const info = { name: String(this.app.config('app.name') ?? 'cslug'), version: '1' }
33
+ await serveMcpStdio(() => asMcpTools((cls) => resolve(cls), 'local'), info)
34
+ return 0
35
+ }
36
+ }
37
+
38
+ /** `cslug ai:prompts`: the prompt files and the variables each one needs. */
39
+ export class AiPromptsCommand extends Command {
40
+ static signature = 'ai:prompts'
41
+ static description = 'List resources/prompts/*.md and their {{ variables }}'
42
+ static boot = false
43
+ static args = { json: flag.boolean() }
44
+
45
+ handle({ json }: Command.Args<typeof AiPromptsCommand>) {
46
+ const dir = join(this.app.rootDir, 'resources/prompts')
47
+ const rows = existsSync(dir)
48
+ ? (readdirSync(dir, { recursive: true }) as string[])
49
+ .filter((f) => f.endsWith('.md'))
50
+ .sort()
51
+ .map((f) => ({
52
+ prompt: f.replace(/\.md$/, ''),
53
+ variables: [
54
+ ...new Set(
55
+ [...readFileSync(join(dir, f), 'utf8').matchAll(PROMPT_VARIABLE)].map((m) =>
56
+ m[2] === undefined ? m[1] : `${m[1]}?`,
57
+ ),
58
+ ),
59
+ ].join(', '),
60
+ }))
61
+ : []
62
+ if (json) this.line(JSON.stringify(rows))
63
+ else if (rows.length) this.table(rows)
64
+ else this.info('No prompts in resources/prompts')
65
+ }
66
+ }
67
+
68
+ /**
69
+ * `cslug ai:record [path]`: `bun test` with `t.ai.fixture()` answered by the real provider; missing fixtures are
70
+ * written (`--all`: every one, re-recorded). Each recorded call costs what the model charges.
71
+ */
72
+ export class AiRecordCommand extends Command {
73
+ static signature = 'ai:record'
74
+ static description = 'Run tests against the real AI provider and write their missing fixtures (calls the API)'
75
+ static boot = false
76
+ static args = {
77
+ path: arg.string().optional().describe('A test file or folder (bun test filter)'),
78
+ all: flag.boolean().describe('Re-record every fixture the tests use'),
79
+ }
80
+
81
+ async handle({ path, all }: Command.Args<typeof AiRecordCommand>) {
82
+ this.warn(`Recording AI fixtures (${all ? 'all' : 'missing'}): the real provider is called`)
83
+ const child = Bun.spawn(['bun', 'test', ...(path ? [path] : [])], {
84
+ cwd: this.app.rootDir,
85
+ env: { ...process.env, CSLUG_AI_RECORD: all ? 'all' : 'missing' },
86
+ stdio: ['inherit', 'inherit', 'inherit'],
87
+ })
88
+ return await child.exited
89
+ }
90
+ }
91
+
92
+ /**
93
+ * Binds `Ai` from `config/ai.ts` (`default`, `providers`, `models`, `mcp`, `budget`, `prices`, `runs`,
94
+ * `embeddings`: @cslug/search's `Embedder` when it is installed) and
95
+ * `Conversations`; contributes `ai:prompts`, `ai:record`, `ai:eval` and `mcp:serve`. With @cslug/database: the
96
+ * `cslug_ai_*` tables, stored conversations and a record per run.
97
+ * With `@mcp()` tools in `app/tools/` and @cslug/http installed: `POST /mcp` (streamable HTTP, in the api group's
98
+ * middleware, so API tokens authenticate callers).
99
+ */
100
+ export class AiProvider extends ServiceProvider {
101
+ register() {
102
+ this.commands([AiPromptsCommand, AiRecordCommand, AiEvalCommand, McpServeCommand])
103
+ this.app.singleton(
104
+ Ai,
105
+ (c) => new Ai(this.app, this.app.config<AiConfig | undefined>('ai') ?? {}, c.resolve(Logger)),
106
+ )
107
+ this.app.singleton(Conversations, () => new Conversations(this.app))
108
+ }
109
+
110
+ async boot() {
111
+ await this.bindEmbedder()
112
+ await this.recallIndex()
113
+ const store = await databaseStore(this.app)
114
+ if (store) {
115
+ this.app.resolve(Conversations).store = store
116
+ if (this.app.config<boolean | undefined>('ai.runs') !== false) this.app.resolve(Ai).recorder = store.recordRun
117
+ }
118
+ await discoverTools(this.app)
119
+ if (!mcpTools().length) return
120
+ const http = await import('@cslug/http').catch(() => undefined)
121
+ if (!http || !this.app.has(http.Router)) return
122
+ const info = { name: String(this.app.config('app.name') ?? 'cslug'), version: '1' }
123
+ this.app.resolve(http.Router).load(
124
+ (r) => {
125
+ r.post('/mcp', (ctx) => this.mcpHttp(ctx, info)).name('mcp')
126
+ r.get('/mcp', () => new Response(null, { status: 405, headers: { allow: 'POST' } }))
127
+ },
128
+ { middleware: this.app.tagged(http.API_MIDDLEWARE) },
129
+ )
130
+ }
131
+
132
+ /** With `ai.embeddings` and @cslug/search installed: its `Embedder`, from the configured driver. */
133
+ private async bindEmbedder() {
134
+ const config = this.app.config<AiConfig | undefined>('ai')?.embeddings
135
+ if (!config) return
136
+ // a variable specifier: apps without @cslug/search still type-check (TypeScript does not resolve it)
137
+ const specifier = '@cslug/search'
138
+ const search = (await import(specifier).catch(() => undefined)) as SearchModule | undefined
139
+ if (!search) {
140
+ this.app.resolve(Logger).warn('ai.embeddings_unused', { reason: '@cslug/search is not installed' })
141
+ return
142
+ }
143
+ const embedder = embedderFor(config, () => this.app.resolve(Ai).budget)
144
+ this.app.instance(search.Embedder, embedder)
145
+ // tests (`fakes: ['ai']`) swap it for a FakeEmbedder: no paid call from a test
146
+ setFakeEmbedder(search.Embedder, () => new search.FakeEmbedder())
147
+ }
148
+
149
+ /** With `ai.recall`: the index conversations' turns are kept in (semantic when an embedder is bound). */
150
+ private async recallIndex() {
151
+ const recall = this.app.config<AiConfig | undefined>('ai')?.recall
152
+ if (!recall) return
153
+ const specifier = '@cslug/search'
154
+ const search = (await import(specifier).catch(() => undefined)) as SearchModule | undefined
155
+ if (!search) {
156
+ this.app.resolve(Logger).warn('ai.recall_unused', { reason: '@cslug/search is not installed' })
157
+ return
158
+ }
159
+ const name = (typeof recall === 'object' && recall.index) || 'ai-conversations'
160
+ this.app.resolve(Ai).recallIndex = new search.SearchIndex(name, { semantic: this.app.has(search.Embedder) })
161
+ }
162
+
163
+ /** One MCP message over HTTP: Origin checked (DNS rebinding), notifications 202, JSON responses. */
164
+ private async mcpHttp(ctx: HttpContext, info: { name: string; version: string }): Promise<Response> {
165
+ const origin = ctx.request.header('origin')
166
+ const appUrl = this.app.config<string | undefined>('app.url')
167
+ if (origin && (!appUrl || new URL(origin).origin !== new URL(appUrl).origin))
168
+ return Response.json(
169
+ { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Origin not allowed' } },
170
+ { status: 403 },
171
+ )
172
+ const caller: McpCaller = Reflect.get(ctx, 'auth')
173
+ const reply = await handleMcp(await ctx.request.body(), (cls) => resolve(cls), caller, info).catch(
174
+ (): McpReply => ({
175
+ jsonrpc: '2.0',
176
+ id: null,
177
+ error: { code: -32700, message: 'Parse error' },
178
+ }),
179
+ )
180
+ if (!reply) return new Response(null, { status: 202 })
181
+ return Response.json(reply, { status: reply.error?.code === -32601 ? 404 : 200 })
182
+ }
183
+
184
+ async shutdown() {
185
+ await this.app.resolve(Ai).close()
186
+ }
187
+ }
@@ -0,0 +1,31 @@
1
+ import type { AiResult } from './ai'
2
+
3
+ type StreamStep = { type: 'text'; text: string } | { type: 'result'; result: AiResult }
4
+
5
+ /**
6
+ * What `stream()` returns: the text as it arrives (`for await`, or `sse(stream)`), and `result`, the finished run
7
+ * with its `messages` to store for the next turn. `result` settles once the text has been read to the end (it
8
+ * rejects with the run's error).
9
+ */
10
+ export class AiStream<V = unknown> implements AsyncIterable<string> {
11
+ readonly result: Promise<AiResult<V>>
12
+ private settle!: { resolve(result: AiResult<V>): void; reject(error: unknown): void }
13
+
14
+ constructor(private readonly steps: AsyncIterable<StreamStep>) {
15
+ this.result = new Promise((resolve, reject) => {
16
+ this.settle = { resolve, reject }
17
+ })
18
+ this.result.catch(() => {}) // the error also reaches the reader of the text; not unhandled when nobody awaits
19
+ }
20
+
21
+ async *[Symbol.asyncIterator](): AsyncIterator<string> {
22
+ try {
23
+ for await (const step of this.steps)
24
+ if (step.type === 'text') yield step.text
25
+ else this.settle.resolve(step.result as AiResult<V>)
26
+ } catch (error) {
27
+ this.settle.reject(error)
28
+ throw error
29
+ }
30
+ }
31
+ }
package/src/ai.ts ADDED
@@ -0,0 +1,329 @@
1
+ import { type Application, Cache, Clock, CslugError, currentContext, type Logger, resolve } from '@cslug/core'
2
+ import { type AgentSettings, type RunnableTool, type RunOptions, renderInstructions } from './agent'
3
+ import { AiStream } from './ai-stream'
4
+ import { Budget, type BudgetConfig, costOf, type ModelPrice } from './budget'
5
+ import {
6
+ type AnthropicConfig,
7
+ AnthropicProvider,
8
+ type OpenAiCompatibleConfig,
9
+ OpenAiCompatibleProvider,
10
+ } from './drivers'
11
+ import type { EmbeddingsConfig } from './embedders'
12
+ import { McpConnection, type McpServerConfig, McpTools } from './mcp-client'
13
+ import {
14
+ type Block,
15
+ type Message,
16
+ type ModelRequest,
17
+ type ModelResponse,
18
+ modelSchema,
19
+ type Provider,
20
+ type Usage,
21
+ } from './model'
22
+ import type { SearchableIndex } from './search-tools'
23
+
24
+ /** `config/ai.ts`. */
25
+ export type AiConfig = {
26
+ default?: string
27
+ providers?: Record<string, AnthropicConfig | OpenAiCompatibleConfig>
28
+ /** Roles code refers to (`fast`, `smart`) → model IDs. */
29
+ models?: Record<string, string>
30
+ /** MCP servers whose tools agents use: `mcp('maps').tools([...])`. */
31
+ mcp?: Record<string, McpServerConfig>
32
+ /** A daily spending limit: `{ perDay: { usd: 20 }, alertAt: 0.8 }` (`AiBudgetError` once spent). */
33
+ budget?: BudgetConfig
34
+ /** USD per million tokens for models the built-in table lacks (or to override it). */
35
+ prices?: Record<string, ModelPrice>
36
+ /** With @cslug/database, a row per run in `cslug_ai_runs` (default true). */
37
+ runs?: boolean
38
+ /** The embedding model `@cslug/search` uses for semantic indexes (bound as its `Embedder`). */
39
+ embeddings?: EmbeddingsConfig
40
+ /**
41
+ * Keep stored conversations' text in a search index (`ai-conversations` by default; semantic when an embedder is
42
+ * bound), so `recallTool()` can search an owner's earlier conversations. Needs @cslug/search and @cslug/database.
43
+ */
44
+ recall?: boolean | { index?: string }
45
+ }
46
+
47
+ /** A finished or failed run, as `cslug_ai_runs` stores it. */
48
+ export type RunRecord = {
49
+ id: string
50
+ agent: string
51
+ model: string
52
+ conversationId?: string
53
+ /** The signed-in user (ambient context), if any. */
54
+ userId?: string
55
+ status: 'completed' | 'failed'
56
+ steps: number
57
+ usage: Required<Usage>
58
+ costUsd: number | undefined
59
+ error?: string
60
+ startedAt: Date
61
+ finishedAt: Date
62
+ }
63
+
64
+ /** How a run is called besides its options (set by `Conversation`). */
65
+ export type RunMeta = {
66
+ conversationId?: string
67
+ /** Ask the provider to compact a long history server-side (Anthropic: `compact_20260112`). */
68
+ compact?: boolean
69
+ }
70
+
71
+ /** A finished run in detail: the value `run()` returns, the model's raw answer (JSON or text), what it cost. */
72
+ export type AiResult<V = unknown> = {
73
+ /** UUIDv7, the `cslug_ai_runs` row when runs are recorded. */
74
+ runId: string
75
+ value: V
76
+ /** The answer before validation: parsed JSON with an `output` schema, else the text. Fixtures store this. */
77
+ raw: unknown
78
+ model: string
79
+ steps: number
80
+ usage: Usage
81
+ /** Estimated from the model's price; `undefined` when it has none. */
82
+ costUsd: number | undefined
83
+ /** The whole conversation: the `history`, this input, the tool rounds and the answer. Pass it as `history` next. */
84
+ messages: Message[]
85
+ }
86
+
87
+ /** The model's final answer did not match the agent's `output` schema (or was not JSON). */
88
+ export class AiOutputError extends CslugError {
89
+ constructor(
90
+ readonly text: string,
91
+ readonly issues: unknown,
92
+ ) {
93
+ super('ai.output', `The model's answer does not match the output schema: ${JSON.stringify(issues).slice(0, 300)}`)
94
+ }
95
+ }
96
+
97
+ const NO_USAGE: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
98
+ const textOf = (blocks: Block[]) => blocks.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('')
99
+
100
+ /** Runs agents: renders instructions, calls the provider, runs tools until the model answers, validates the output. */
101
+ export class Ai {
102
+ private readonly providers = new Map<string, Provider>()
103
+ private readonly connections = new Map<string, McpConnection>()
104
+ private budgetTracker?: Budget
105
+ /** Stores each run (set by `AiProvider` with @cslug/database). */
106
+ recorder?: (record: RunRecord) => Promise<void>
107
+ /** Where stored conversations' turns are kept for `recallTool()` (set by `AiProvider` with `ai.recall`). */
108
+ recallIndex?: SearchableIndex
109
+
110
+ constructor(
111
+ protected readonly app: Application,
112
+ protected readonly config: AiConfig,
113
+ protected readonly log: Logger,
114
+ ) {}
115
+
116
+ /** Register a provider by name (tests, custom APIs). */
117
+ extend(name: string, provider: Provider): this {
118
+ this.providers.set(name, provider)
119
+ return this
120
+ }
121
+
122
+ provider(name = this.config.default ?? 'anthropic'): Provider {
123
+ const known = this.providers.get(name)
124
+ if (known) return known
125
+ const config =
126
+ this.config.providers?.[name] ?? (name === 'anthropic' ? { driver: 'anthropic' as const } : undefined)
127
+ if (!config) throw new CslugError('ai.unknown_provider', `No AI provider "${name}" (config ai.providers)`)
128
+ const provider =
129
+ config.driver === 'anthropic' ? new AnthropicProvider(config) : new OpenAiCompatibleProvider(config)
130
+ this.providers.set(name, provider)
131
+ return provider
132
+ }
133
+
134
+ /** The daily budget (`ai.budget`), or `undefined` without one. */
135
+ get budget(): Budget | undefined {
136
+ if (!this.config.budget) return undefined
137
+ this.budgetTracker ??= new Budget(
138
+ this.config.budget,
139
+ this.config.prices ?? {},
140
+ this.app.resolve(Cache),
141
+ this.app.resolve(Clock),
142
+ this.log,
143
+ )
144
+ return this.budgetTracker
145
+ }
146
+
147
+ /** An MCP server's tools as a run calls them (its result: `structuredContent`, else the text). */
148
+ private async remote({ server, only }: McpTools): Promise<RunnableTool[]> {
149
+ const config = this.config.mcp?.[server]
150
+ if (!config) throw new CslugError('ai.unknown_mcp', `No MCP server "${server}" (config ai.mcp)`)
151
+ const connection = this.connections.get(server) ?? new McpConnection(server, config)
152
+ this.connections.set(server, connection)
153
+ const listed = (await connection.request('tools/list')).tools as {
154
+ name: string
155
+ description?: string
156
+ inputSchema: Record<string, unknown>
157
+ }[]
158
+ return listed
159
+ .filter((t) => !only || only.includes(t.name))
160
+ .map((t) => ({
161
+ name: t.name,
162
+ description: t.description ?? '',
163
+ input: { toJSONSchema: () => t.inputSchema, safeParse: (data: unknown) => ({ success: true as const, data }) },
164
+ handle: async (args: unknown) => {
165
+ const result = await connection.request('tools/call', { name: t.name, arguments: args })
166
+ const text = ((result.content ?? []) as { text?: string }[]).map((c) => c.text ?? '').join('')
167
+ if (result.isError) throw new Error(text)
168
+ return result.structuredContent ?? text
169
+ },
170
+ }))
171
+ }
172
+
173
+ /** Close the MCP connections (stdio servers are stopped). */
174
+ async close(): Promise<void> {
175
+ await Promise.all([...this.connections.values()].map((c) => c.close()))
176
+ this.connections.clear()
177
+ }
178
+
179
+ async run(agent: AgentSettings, options: RunOptions): Promise<unknown> {
180
+ return (await this.result(agent, options)).value
181
+ }
182
+
183
+ /** Like `run()`, with the raw answer, the model, the token usage and the estimated cost (`ai:record`, `ai:eval`). */
184
+ async result(agent: AgentSettings, options: RunOptions, meta: RunMeta = {}): Promise<AiResult> {
185
+ for await (const event of this.recorded(agent, options, false, meta))
186
+ if (event.type === 'result') return event.result
187
+ throw new CslugError('ai.no_result', 'The agent finished without a result')
188
+ }
189
+
190
+ /** The text as it arrives; `.result` settles with the finished run once the text has been read. */
191
+ stream(agent: AgentSettings, options: RunOptions, meta: RunMeta = {}): AiStream {
192
+ return new AiStream(this.recorded(agent, options, true, meta))
193
+ }
194
+
195
+ /** The steps, with the run recorded at the end (completed or failed); a recording failure is only logged. */
196
+ private async *recorded(agent: AgentSettings, options: RunOptions, streaming: boolean, meta: RunMeta) {
197
+ const id = Bun.randomUUIDv7()
198
+ const clock = this.app.resolve(Clock)
199
+ const startedAt = clock.now()
200
+ const record = async (rest: Pick<RunRecord, 'status' | 'steps' | 'usage' | 'costUsd' | 'error'>) => {
201
+ if (!this.recorder) return
202
+ const userId = currentContext()?.userId
203
+ await this.recorder({
204
+ id,
205
+ agent: agent.constructor.name,
206
+ model: this.config.models?.[agent.model] ?? agent.model,
207
+ ...(meta.conversationId ? { conversationId: meta.conversationId } : {}),
208
+ ...(userId !== undefined ? { userId: String(userId) } : {}),
209
+ startedAt,
210
+ finishedAt: clock.now(),
211
+ ...rest,
212
+ }).catch((error) => this.log.warn('ai.run_not_recorded', { id, error }))
213
+ }
214
+ try {
215
+ for await (const event of this.steps(agent, options, streaming, meta, id)) {
216
+ if (event.type === 'result') {
217
+ const { steps, usage, costUsd } = event.result
218
+ await record({ status: 'completed', steps, usage: { ...NO_USAGE, ...usage }, costUsd })
219
+ }
220
+ yield event
221
+ }
222
+ } catch (error) {
223
+ const message = error instanceof Error ? error.message : String(error)
224
+ await record({ status: 'failed', steps: 0, usage: NO_USAGE, costUsd: undefined, error: message })
225
+ throw error
226
+ }
227
+ }
228
+
229
+ private async *steps(
230
+ agent: AgentSettings,
231
+ { input, context = {}, history = [] }: RunOptions,
232
+ streaming: boolean,
233
+ meta: RunMeta,
234
+ runId: string,
235
+ ) {
236
+ const { maxSteps = 8 } = agent
237
+ const tools: RunnableTool[] = []
238
+ for (const t of agent.tools ?? [])
239
+ tools.push(...(t instanceof McpTools ? await this.remote(t) : typeof t === 'function' ? [resolve(t)] : [t]))
240
+ const request: ModelRequest = {
241
+ model: this.config.models?.[agent.model] ?? agent.model,
242
+ system: await renderInstructions(agent.instructions, context),
243
+ messages: [...history, { role: 'user', content: [{ type: 'text', text: input }] }],
244
+ tools: tools.map((t) => ({
245
+ name: t.name,
246
+ description: t.description,
247
+ inputSchema: modelSchema(t.input.toJSONSchema()),
248
+ })),
249
+ ...(agent.output ? { output: modelSchema(agent.output.toJSONSchema()) } : {}),
250
+ ...(agent.effort ? { effort: agent.effort } : {}),
251
+ ...(agent.maxTokens ? { maxTokens: agent.maxTokens } : {}),
252
+ ...((agent.compact ?? meta.compact) ? { compact: true } : {}),
253
+ }
254
+ const provider = this.provider(agent.provider)
255
+ const usage: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
256
+ const budget = this.budget
257
+ for (let step = 1; step <= maxSteps; step++) {
258
+ await budget?.check()
259
+ let response: ModelResponse | undefined
260
+ if (streaming)
261
+ for await (const event of provider.stream(request)) {
262
+ if (event.type === 'text') yield event
263
+ else response = event.response
264
+ }
265
+ else response = await provider.complete(request)
266
+ if (!response) throw new CslugError('ai.provider', 'The stream ended without a response')
267
+ for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] += response.usage[k] ?? 0
268
+ await budget?.charge(request.model, response.usage)
269
+ request.messages.push({ role: 'assistant', content: response.content })
270
+ const calls = response.content.filter((b) => b.type === 'tool_use')
271
+ if (!calls.length) {
272
+ const costUsd = costOf(request.model, usage, this.config.prices)
273
+ this.log.info('ai.run', { agent: agent.constructor.name, model: request.model, steps: step, ...usage, costUsd })
274
+ const text = textOf(response.content)
275
+ const raw = agent.output ? this.json(text) : text
276
+ const result: AiResult = {
277
+ runId,
278
+ raw,
279
+ value: this.validate(agent, raw, text),
280
+ model: request.model,
281
+ steps: step,
282
+ usage,
283
+ costUsd,
284
+ messages: [...request.messages],
285
+ }
286
+ yield { type: 'result' as const, result }
287
+ return
288
+ }
289
+ // every result of one turn goes back in one message
290
+ request.messages.push({ role: 'user', content: await Promise.all(calls.map((call) => this.call(tools, call))) })
291
+ }
292
+ throw new CslugError('ai.max_steps', `${agent.constructor.name} did not finish in ${maxSteps} steps`)
293
+ }
294
+
295
+ private async call(tools: RunnableTool[], call: Extract<Block, { type: 'tool_use' }>): Promise<Block> {
296
+ const result = (content: string, isError = false): Block => ({
297
+ type: 'tool_result',
298
+ toolUseId: call.id,
299
+ content,
300
+ isError,
301
+ })
302
+ const tool = tools.find((t) => t.name === call.name)
303
+ if (!tool) return result(`Unknown tool ${call.name}`, true)
304
+ const input = tool.input.safeParse(call.input)
305
+ if (!input.success) return result(`Invalid input: ${JSON.stringify(input.error.issues)}`, true)
306
+ try {
307
+ const value = await tool.handle(input.data as never)
308
+ return result(typeof value === 'string' ? value : JSON.stringify(value ?? null))
309
+ } catch (error) {
310
+ this.log.warn('ai.tool_failed', { tool: call.name, error })
311
+ return result(error instanceof Error ? error.message : String(error), true)
312
+ }
313
+ }
314
+
315
+ private json(text: string): unknown {
316
+ try {
317
+ return JSON.parse(text)
318
+ } catch {
319
+ throw new AiOutputError(text, 'not JSON')
320
+ }
321
+ }
322
+
323
+ /** The value through the agent's `output` schema (coercions applied), or `AiOutputError`. */
324
+ protected validate(agent: AgentSettings, value: unknown, text = ''): unknown {
325
+ const parsed = agent.output?.safeParse(value)
326
+ if (parsed && !parsed.success) throw new AiOutputError(text, parsed.error.issues)
327
+ return parsed ? parsed.data : value
328
+ }
329
+ }
package/src/budget.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { type Cache, type Clock, CslugError, Event, type Logger } from '@cslug/core'
2
+ import type { Usage } from './model'
3
+
4
+ /** USD per million tokens. Cache reads cost 0.1× input and cache writes 1.25× input (5-minute cache). */
5
+ export type ModelPrice = { input: number; output: number }
6
+
7
+ /** Anthropic first-party prices (2026-11); `ai.prices` overrides or adds models. */
8
+ export const MODEL_PRICES: Record<string, ModelPrice> = {
9
+ 'claude-fable-5-2': { input: 8, output: 40 },
10
+ 'claude-fable-5-1': { input: 10, output: 50 },
11
+ 'claude-fable-5': { input: 10, output: 50 },
12
+ 'claude-opus-5-5': { input: 4, output: 20 },
13
+ 'claude-opus-5': { input: 5, output: 25 },
14
+ 'claude-opus-4-8': { input: 5, output: 25 },
15
+ 'claude-opus-4-7': { input: 5, output: 25 },
16
+ 'claude-opus-4-6': { input: 5, output: 25 },
17
+ 'claude-sonnet-5-5': { input: 2, output: 10 },
18
+ 'claude-sonnet-5': { input: 2, output: 10 },
19
+ 'claude-sonnet-4-6': { input: 3, output: 15 },
20
+ 'claude-haiku-5-5': { input: 0.1, output: 0.5 },
21
+ 'claude-haiku-4-5': { input: 1, output: 5 },
22
+ }
23
+
24
+ /** `config/ai.ts` → `budget`: a daily spending limit for the whole app (every process sharing the cache). */
25
+ export type BudgetConfig = {
26
+ perDay: { usd: number }
27
+ /** Share of the limit at which `AiBudgetAlert` is emitted once a day (default 0.8). */
28
+ alertAt?: number
29
+ }
30
+
31
+ /** The estimated cost of one call in USD, or `undefined` when the model has no price. */
32
+ export function costOf(model: string, usage: Usage, prices: Record<string, ModelPrice> = {}): number | undefined {
33
+ const price = prices[model] ?? MODEL_PRICES[model]
34
+ if (!price) return undefined
35
+ const input = usage.inputTokens + 0.1 * (usage.cacheReadTokens ?? 0) + 1.25 * (usage.cacheWriteTokens ?? 0)
36
+ return (input * price.input + usage.outputTokens * price.output) / 1e6
37
+ }
38
+
39
+ /** Today's AI spend reached the daily limit: no model is called until tomorrow (app time zone). */
40
+ export class AiBudgetError extends CslugError {
41
+ constructor(
42
+ readonly spentUsd: number,
43
+ readonly limitUsd: number,
44
+ ) {
45
+ super(
46
+ 'ai.budget',
47
+ `The daily AI budget is spent ($${spentUsd.toFixed(2)} of $${limitUsd}); raise ai.budget.perDay or wait until tomorrow`,
48
+ )
49
+ }
50
+ }
51
+
52
+ /** Emitted once a day when the spend crosses `ai.budget.alertAt` of the limit (listen to warn someone). */
53
+ export class AiBudgetAlert extends Event<{ day: string; spentUsd: number; limitUsd: number }>('ai.budget_alert') {}
54
+
55
+ const MICROS = 1e6 // spend is counted in micro-dollars: cache counters are integers
56
+
57
+ /**
58
+ * The daily budget: checked before each model call, charged after it. Spend lives in the app's `Cache` (Redis when
59
+ * @cslug/redis is installed, so every process shares it) under `ai:spend:<day>`.
60
+ */
61
+ export class Budget {
62
+ private readonly unpriced = new Set<string>()
63
+
64
+ constructor(
65
+ private readonly config: BudgetConfig,
66
+ private readonly prices: Record<string, ModelPrice>,
67
+ private readonly cache: Cache,
68
+ private readonly clock: Clock,
69
+ private readonly log: Logger,
70
+ ) {}
71
+
72
+ private key = () => `ai:spend:${this.clock.today()}`
73
+
74
+ /** Spent today, in USD. */
75
+ async spent(): Promise<number> {
76
+ return ((await this.cache.get<number>(this.key())) ?? 0) / MICROS
77
+ }
78
+
79
+ /** `AiBudgetError` when today's limit is reached. */
80
+ async check(): Promise<void> {
81
+ const spent = await this.spent()
82
+ if (spent >= this.config.perDay.usd) throw new AiBudgetError(spent, this.config.perDay.usd)
83
+ }
84
+
85
+ async charge(model: string, usage: Usage): Promise<void> {
86
+ const cost = costOf(model, usage, this.prices)
87
+ if (cost === undefined) {
88
+ if (!this.unpriced.has(model)) this.log.warn('ai.budget_unpriced', { model, fix: `add ai.prices['${model}']` })
89
+ this.unpriced.add(model)
90
+ return
91
+ }
92
+ const micros = Math.round(cost * MICROS)
93
+ if (!micros) return
94
+ const total = await this.cache.increment(this.key(), micros, '2d')
95
+ const limit = this.config.perDay.usd
96
+ const threshold = (this.config.alertAt ?? 0.8) * limit * MICROS
97
+ if (total - micros < threshold && total >= threshold) {
98
+ const payload = { day: this.clock.today(), spentUsd: total / MICROS, limitUsd: limit }
99
+ this.log.warn('ai.budget_alert', payload)
100
+ await AiBudgetAlert.emit(payload)
101
+ }
102
+ }
103
+ }