@cslug/ai 0.4.0 → 0.5.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,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,317 @@
1
+ import { type Application, Cache, Clock, CslugError, currentContext, type Logger, resolve } from '@cslug/core'
2
+ import type { AgentSettings, RunnableTool, RunOptions } 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 { McpConnection, type McpServerConfig, McpTools } from './mcp-client'
12
+ import {
13
+ type Block,
14
+ type Message,
15
+ type ModelRequest,
16
+ type ModelResponse,
17
+ modelSchema,
18
+ type Provider,
19
+ type Usage,
20
+ } from './model'
21
+
22
+ /** `config/ai.ts`. */
23
+ export type AiConfig = {
24
+ default?: string
25
+ providers?: Record<string, AnthropicConfig | OpenAiCompatibleConfig>
26
+ /** Roles code refers to (`fast`, `smart`) → model IDs. */
27
+ models?: Record<string, string>
28
+ /** MCP servers whose tools agents use: `mcp('maps').tools([...])`. */
29
+ mcp?: Record<string, McpServerConfig>
30
+ /** A daily spending limit: `{ perDay: { usd: 20 }, alertAt: 0.8 }` (`AiBudgetError` once spent). */
31
+ budget?: BudgetConfig
32
+ /** USD per million tokens for models the built-in table lacks (or to override it). */
33
+ prices?: Record<string, ModelPrice>
34
+ /** With @cslug/database, a row per run in `cslug_ai_runs` (default true). */
35
+ runs?: boolean
36
+ }
37
+
38
+ /** A finished or failed run, as `cslug_ai_runs` stores it. */
39
+ export type RunRecord = {
40
+ id: string
41
+ agent: string
42
+ model: string
43
+ conversationId?: string
44
+ /** The signed-in user (ambient context), if any. */
45
+ userId?: string
46
+ status: 'completed' | 'failed'
47
+ steps: number
48
+ usage: Required<Usage>
49
+ costUsd: number | undefined
50
+ error?: string
51
+ startedAt: Date
52
+ finishedAt: Date
53
+ }
54
+
55
+ /** How a run is called besides its options (set by `Conversation`). */
56
+ export type RunMeta = {
57
+ conversationId?: string
58
+ /** Ask the provider to compact a long history server-side (Anthropic: `compact_20260112`). */
59
+ compact?: boolean
60
+ }
61
+
62
+ /** A finished run in detail: the value `run()` returns, the model's raw answer (JSON or text), what it cost. */
63
+ export type AiResult<V = unknown> = {
64
+ /** UUIDv7, the `cslug_ai_runs` row when runs are recorded. */
65
+ runId: string
66
+ value: V
67
+ /** The answer before validation: parsed JSON with an `output` schema, else the text. Fixtures store this. */
68
+ raw: unknown
69
+ model: string
70
+ steps: number
71
+ usage: Usage
72
+ /** Estimated from the model's price; `undefined` when it has none. */
73
+ costUsd: number | undefined
74
+ /** The whole conversation: the `history`, this input, the tool rounds and the answer. Pass it as `history` next. */
75
+ messages: Message[]
76
+ }
77
+
78
+ /** The model's final answer did not match the agent's `output` schema (or was not JSON). */
79
+ export class AiOutputError extends CslugError {
80
+ constructor(
81
+ readonly text: string,
82
+ readonly issues: unknown,
83
+ ) {
84
+ super('ai.output', `The model's answer does not match the output schema: ${JSON.stringify(issues).slice(0, 300)}`)
85
+ }
86
+ }
87
+
88
+ const NO_USAGE: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
89
+ const textOf = (blocks: Block[]) => blocks.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('')
90
+
91
+ /** Runs agents: renders instructions, calls the provider, runs tools until the model answers, validates the output. */
92
+ export class Ai {
93
+ private readonly providers = new Map<string, Provider>()
94
+ private readonly connections = new Map<string, McpConnection>()
95
+ private budgetTracker?: Budget
96
+ /** Stores each run (set by `AiProvider` with @cslug/database). */
97
+ recorder?: (record: RunRecord) => Promise<void>
98
+
99
+ constructor(
100
+ protected readonly app: Application,
101
+ protected readonly config: AiConfig,
102
+ protected readonly log: Logger,
103
+ ) {}
104
+
105
+ /** Register a provider by name (tests, custom APIs). */
106
+ extend(name: string, provider: Provider): this {
107
+ this.providers.set(name, provider)
108
+ return this
109
+ }
110
+
111
+ provider(name = this.config.default ?? 'anthropic'): Provider {
112
+ const known = this.providers.get(name)
113
+ if (known) return known
114
+ const config =
115
+ this.config.providers?.[name] ?? (name === 'anthropic' ? { driver: 'anthropic' as const } : undefined)
116
+ if (!config) throw new CslugError('ai.unknown_provider', `No AI provider "${name}" (config ai.providers)`)
117
+ const provider =
118
+ config.driver === 'anthropic' ? new AnthropicProvider(config) : new OpenAiCompatibleProvider(config)
119
+ this.providers.set(name, provider)
120
+ return provider
121
+ }
122
+
123
+ /** The daily budget (`ai.budget`), or `undefined` without one. */
124
+ get budget(): Budget | undefined {
125
+ if (!this.config.budget) return undefined
126
+ this.budgetTracker ??= new Budget(
127
+ this.config.budget,
128
+ this.config.prices ?? {},
129
+ this.app.resolve(Cache),
130
+ this.app.resolve(Clock),
131
+ this.log,
132
+ )
133
+ return this.budgetTracker
134
+ }
135
+
136
+ /** An MCP server's tools as a run calls them (its result: `structuredContent`, else the text). */
137
+ private async remote({ server, only }: McpTools): Promise<RunnableTool[]> {
138
+ const config = this.config.mcp?.[server]
139
+ if (!config) throw new CslugError('ai.unknown_mcp', `No MCP server "${server}" (config ai.mcp)`)
140
+ const connection = this.connections.get(server) ?? new McpConnection(server, config)
141
+ this.connections.set(server, connection)
142
+ const listed = (await connection.request('tools/list')).tools as {
143
+ name: string
144
+ description?: string
145
+ inputSchema: Record<string, unknown>
146
+ }[]
147
+ return listed
148
+ .filter((t) => !only || only.includes(t.name))
149
+ .map((t) => ({
150
+ name: t.name,
151
+ description: t.description ?? '',
152
+ input: { toJSONSchema: () => t.inputSchema, safeParse: (data: unknown) => ({ success: true as const, data }) },
153
+ handle: async (args: unknown) => {
154
+ const result = await connection.request('tools/call', { name: t.name, arguments: args })
155
+ const text = ((result.content ?? []) as { text?: string }[]).map((c) => c.text ?? '').join('')
156
+ if (result.isError) throw new Error(text)
157
+ return result.structuredContent ?? text
158
+ },
159
+ }))
160
+ }
161
+
162
+ /** Close the MCP connections (stdio servers are stopped). */
163
+ async close(): Promise<void> {
164
+ await Promise.all([...this.connections.values()].map((c) => c.close()))
165
+ this.connections.clear()
166
+ }
167
+
168
+ async run(agent: AgentSettings, options: RunOptions): Promise<unknown> {
169
+ return (await this.result(agent, options)).value
170
+ }
171
+
172
+ /** Like `run()`, with the raw answer, the model, the token usage and the estimated cost (`ai:record`, `ai:eval`). */
173
+ async result(agent: AgentSettings, options: RunOptions, meta: RunMeta = {}): Promise<AiResult> {
174
+ for await (const event of this.recorded(agent, options, false, meta))
175
+ if (event.type === 'result') return event.result
176
+ throw new CslugError('ai.no_result', 'The agent finished without a result')
177
+ }
178
+
179
+ /** The text as it arrives; `.result` settles with the finished run once the text has been read. */
180
+ stream(agent: AgentSettings, options: RunOptions, meta: RunMeta = {}): AiStream {
181
+ return new AiStream(this.recorded(agent, options, true, meta))
182
+ }
183
+
184
+ /** The steps, with the run recorded at the end (completed or failed); a recording failure is only logged. */
185
+ private async *recorded(agent: AgentSettings, options: RunOptions, streaming: boolean, meta: RunMeta) {
186
+ const id = Bun.randomUUIDv7()
187
+ const clock = this.app.resolve(Clock)
188
+ const startedAt = clock.now()
189
+ const record = async (rest: Pick<RunRecord, 'status' | 'steps' | 'usage' | 'costUsd' | 'error'>) => {
190
+ if (!this.recorder) return
191
+ const userId = currentContext()?.userId
192
+ await this.recorder({
193
+ id,
194
+ agent: agent.constructor.name,
195
+ model: this.config.models?.[agent.model] ?? agent.model,
196
+ ...(meta.conversationId ? { conversationId: meta.conversationId } : {}),
197
+ ...(userId !== undefined ? { userId: String(userId) } : {}),
198
+ startedAt,
199
+ finishedAt: clock.now(),
200
+ ...rest,
201
+ }).catch((error) => this.log.warn('ai.run_not_recorded', { id, error }))
202
+ }
203
+ try {
204
+ for await (const event of this.steps(agent, options, streaming, meta, id)) {
205
+ if (event.type === 'result') {
206
+ const { steps, usage, costUsd } = event.result
207
+ await record({ status: 'completed', steps, usage: { ...NO_USAGE, ...usage }, costUsd })
208
+ }
209
+ yield event
210
+ }
211
+ } catch (error) {
212
+ const message = error instanceof Error ? error.message : String(error)
213
+ await record({ status: 'failed', steps: 0, usage: NO_USAGE, costUsd: undefined, error: message })
214
+ throw error
215
+ }
216
+ }
217
+
218
+ private async *steps(
219
+ agent: AgentSettings,
220
+ { input, context = {}, history = [] }: RunOptions,
221
+ streaming: boolean,
222
+ meta: RunMeta,
223
+ runId: string,
224
+ ) {
225
+ const { instructions = '', maxSteps = 8 } = agent
226
+ const tools: RunnableTool[] = []
227
+ for (const t of agent.tools ?? []) tools.push(...(t instanceof McpTools ? await this.remote(t) : [resolve(t)]))
228
+ const request: ModelRequest = {
229
+ model: this.config.models?.[agent.model] ?? agent.model,
230
+ system: typeof instructions === 'string' ? instructions : instructions.render(context),
231
+ messages: [...history, { role: 'user', content: [{ type: 'text', text: input }] }],
232
+ tools: tools.map((t) => ({
233
+ name: t.name,
234
+ description: t.description,
235
+ inputSchema: modelSchema(t.input.toJSONSchema()),
236
+ })),
237
+ ...(agent.output ? { output: modelSchema(agent.output.toJSONSchema()) } : {}),
238
+ ...(agent.effort ? { effort: agent.effort } : {}),
239
+ ...(agent.maxTokens ? { maxTokens: agent.maxTokens } : {}),
240
+ ...((agent.compact ?? meta.compact) ? { compact: true } : {}),
241
+ }
242
+ const provider = this.provider(agent.provider)
243
+ const usage: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
244
+ const budget = this.budget
245
+ for (let step = 1; step <= maxSteps; step++) {
246
+ await budget?.check()
247
+ let response: ModelResponse | undefined
248
+ if (streaming)
249
+ for await (const event of provider.stream(request)) {
250
+ if (event.type === 'text') yield event
251
+ else response = event.response
252
+ }
253
+ else response = await provider.complete(request)
254
+ if (!response) throw new CslugError('ai.provider', 'The stream ended without a response')
255
+ for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] += response.usage[k] ?? 0
256
+ await budget?.charge(request.model, response.usage)
257
+ request.messages.push({ role: 'assistant', content: response.content })
258
+ const calls = response.content.filter((b) => b.type === 'tool_use')
259
+ if (!calls.length) {
260
+ const costUsd = costOf(request.model, usage, this.config.prices)
261
+ this.log.info('ai.run', { agent: agent.constructor.name, model: request.model, steps: step, ...usage, costUsd })
262
+ const text = textOf(response.content)
263
+ const raw = agent.output ? this.json(text) : text
264
+ const result: AiResult = {
265
+ runId,
266
+ raw,
267
+ value: this.validate(agent, raw, text),
268
+ model: request.model,
269
+ steps: step,
270
+ usage,
271
+ costUsd,
272
+ messages: [...request.messages],
273
+ }
274
+ yield { type: 'result' as const, result }
275
+ return
276
+ }
277
+ // every result of one turn goes back in one message
278
+ request.messages.push({ role: 'user', content: await Promise.all(calls.map((call) => this.call(tools, call))) })
279
+ }
280
+ throw new CslugError('ai.max_steps', `${agent.constructor.name} did not finish in ${maxSteps} steps`)
281
+ }
282
+
283
+ private async call(tools: RunnableTool[], call: Extract<Block, { type: 'tool_use' }>): Promise<Block> {
284
+ const result = (content: string, isError = false): Block => ({
285
+ type: 'tool_result',
286
+ toolUseId: call.id,
287
+ content,
288
+ isError,
289
+ })
290
+ const tool = tools.find((t) => t.name === call.name)
291
+ if (!tool) return result(`Unknown tool ${call.name}`, true)
292
+ const input = tool.input.safeParse(call.input)
293
+ if (!input.success) return result(`Invalid input: ${JSON.stringify(input.error.issues)}`, true)
294
+ try {
295
+ const value = await tool.handle(input.data as never)
296
+ return result(typeof value === 'string' ? value : JSON.stringify(value ?? null))
297
+ } catch (error) {
298
+ this.log.warn('ai.tool_failed', { tool: call.name, error })
299
+ return result(error instanceof Error ? error.message : String(error), true)
300
+ }
301
+ }
302
+
303
+ private json(text: string): unknown {
304
+ try {
305
+ return JSON.parse(text)
306
+ } catch {
307
+ throw new AiOutputError(text, 'not JSON')
308
+ }
309
+ }
310
+
311
+ /** The value through the agent's `output` schema (coercions applied), or `AiOutputError`. */
312
+ protected validate(agent: AgentSettings, value: unknown, text = ''): unknown {
313
+ const parsed = agent.output?.safeParse(value)
314
+ if (parsed && !parsed.success) throw new AiOutputError(text, parsed.error.issues)
315
+ return parsed ? parsed.data : value
316
+ }
317
+ }
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
+ }
@@ -0,0 +1,79 @@
1
+ import { join } from 'node:path'
2
+ import { type Application, Clock } from '@cslug/core'
3
+ import type { ConversationRow, ConversationStore } from './conversations'
4
+ import type { Message } from './model'
5
+
6
+ /** The `cslug_ai_conversations`, `cslug_ai_messages` and `cslug_ai_runs` migration (registered with @cslug/database). */
7
+ export const AI_MIGRATIONS = join(import.meta.dir, '../migrations')
8
+
9
+ /** The tables through @cslug/database (ambient transaction when there is one), or undefined without it. */
10
+ export async function databaseStore(app: Application): Promise<ConversationStore | undefined> {
11
+ const db = await import('@cslug/database').catch(() => undefined)
12
+ if (!db || !app.has(db.Database)) return undefined
13
+ db.addMigrations(AI_MIGRATIONS)
14
+ const { sql } = db
15
+ const database = () => app.resolve(db.Database)
16
+ const now = () => app.resolve(Clock).now()
17
+ const row = (r: ConversationRow) => ({ ...r, metadata: r.metadata ?? {} })
18
+ return {
19
+ async create(c) {
20
+ await database().exec(sql`insert into cslug_ai_conversations
21
+ (id, agent, owner_type, owner_id, title, metadata, created_at, updated_at)
22
+ values (${c.id}, ${c.agent}, ${c.ownerType}, ${c.ownerId}, ${c.title}, ${sql.json(c.metadata)}, ${c.createdAt},
23
+ ${c.createdAt})`)
24
+ },
25
+ async find(id) {
26
+ const found = await database().maybeOne<ConversationRow>(
27
+ sql`select * from cslug_ai_conversations where id = ${id}`,
28
+ )
29
+ return found && row(found)
30
+ },
31
+ async list({ ownerType, ownerId, agent, limit }) {
32
+ const rows = await database().many<ConversationRow>(sql`select * from cslug_ai_conversations
33
+ where owner_type is not distinct from ${ownerType} and owner_id is not distinct from ${ownerId}
34
+ ${agent ? sql`and agent = ${agent}` : sql.empty}
35
+ order by updated_at desc, id desc limit ${limit}`)
36
+ return rows.map(row)
37
+ },
38
+ async messages(id) {
39
+ const rows = await database().many<{ role: Message['role']; content: Message['content'] }>(
40
+ sql`select role, content from cslug_ai_messages where conversation_id = ${id} order by position`,
41
+ )
42
+ return rows.map(({ role, content }) => ({ role, content }))
43
+ },
44
+ async append(id, after, messages, runId) {
45
+ if (!messages.length) return true
46
+ return database().transaction(async (tx) => {
47
+ // the count moves only if no other turn was stored since this one read the history
48
+ const moved = await tx.exec(sql`update cslug_ai_conversations
49
+ set message_count = message_count + ${messages.length}, updated_at = ${now()}
50
+ where id = ${id} and message_count = ${after}`)
51
+ if (!moved) return false
52
+ const at = now()
53
+ const values = messages.map(
54
+ (m, i) => sql`(${id}, ${after + i}, ${m.role}, ${sql.json(m.content)}, ${runId}, ${at})`,
55
+ )
56
+ await tx.exec(sql`insert into cslug_ai_messages (conversation_id, position, role, content, run_id, created_at)
57
+ values ${sql.join(values)}`)
58
+ return true
59
+ })
60
+ },
61
+ async update(id, { title, metadata }) {
62
+ await database().exec(sql`update cslug_ai_conversations set
63
+ title = ${title === undefined ? sql`title` : title},
64
+ metadata = ${metadata === undefined ? sql`metadata` : sql.json(metadata)},
65
+ updated_at = ${now()}
66
+ where id = ${id}`)
67
+ },
68
+ async delete(id) {
69
+ await database().exec(sql`delete from cslug_ai_conversations where id = ${id}`)
70
+ },
71
+ async recordRun(r) {
72
+ await database().exec(sql`insert into cslug_ai_runs (id, agent, model, conversation_id, user_id, status, steps,
73
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, cost_usd, error, started_at, finished_at)
74
+ values (${r.id}, ${r.agent}, ${r.model}, ${r.conversationId ?? null}, ${r.userId ?? null}, ${r.status},
75
+ ${r.steps}, ${r.usage.inputTokens}, ${r.usage.outputTokens}, ${r.usage.cacheReadTokens},
76
+ ${r.usage.cacheWriteTokens}, ${r.costUsd ?? null}, ${r.error ?? null}, ${r.startedAt}, ${r.finishedAt})`)
77
+ },
78
+ }
79
+ }