@cslug/ai 0.4.1 → 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,215 @@
1
+ import { type Application, Clock, ConflictError, CslugError, currentContext, NotFoundError } from '@cslug/core'
2
+ import type { Agent, AgentOutput } from './agent'
3
+ import { Ai, type AiResult, type RunRecord } from './ai'
4
+ import { AiStream } from './ai-stream'
5
+ import type { Message } from './model'
6
+
7
+ type AgentClass<A extends Agent> = abstract new (...args: never[]) => A
8
+
9
+ /** Who a conversation belongs to: a user row (`{ id }`), or another kind of owner with `ownerType`. */
10
+ export type OwnerRef = { id: string | number }
11
+
12
+ export type ConversationRow = {
13
+ id: string
14
+ agent: string
15
+ ownerType: string | null
16
+ ownerId: string | null
17
+ title: string | null
18
+ metadata: Record<string, unknown>
19
+ messageCount: number
20
+ createdAt: Date
21
+ updatedAt: Date
22
+ }
23
+
24
+ /** Where conversations, messages and runs are kept (`cslug_ai_*` tables, set by `AiProvider` with @cslug/database). */
25
+ export interface ConversationStore {
26
+ create(
27
+ row: Pick<ConversationRow, 'id' | 'agent' | 'ownerType' | 'ownerId' | 'title' | 'metadata' | 'createdAt'>,
28
+ ): Promise<void>
29
+ find(id: string): Promise<ConversationRow | null>
30
+ list(where: {
31
+ ownerType: string | null
32
+ ownerId: string | null
33
+ agent?: string
34
+ limit: number
35
+ }): Promise<ConversationRow[]>
36
+ messages(id: string): Promise<Message[]>
37
+ /** Append after exactly `after` messages; false when another turn was stored first. */
38
+ append(id: string, after: number, messages: Message[], runId: string): Promise<boolean>
39
+ update(id: string, changes: { title?: string | null; metadata?: Record<string, unknown> }): Promise<void>
40
+ delete(id: string): Promise<void>
41
+ recordRun(run: RunRecord): Promise<void>
42
+ }
43
+
44
+ export type StartOptions = {
45
+ /** The owner: the signed-in user by default; `null` for none (anyone with the id can continue it). */
46
+ owner?: OwnerRef | null
47
+ /** The kind of owner (default `user`; only `user` owners are matched with the signed-in user). */
48
+ ownerType?: string
49
+ title?: string
50
+ metadata?: Record<string, unknown>
51
+ }
52
+
53
+ export type FindOptions = {
54
+ /** Check against this owner instead of the signed-in user (a job, another kind of owner). */
55
+ owner?: OwnerRef
56
+ ownerType?: string
57
+ }
58
+
59
+ /** A stored conversation with one agent: each `send` continues it and stores the new messages. */
60
+ export class Conversation<A extends Agent = Agent> {
61
+ constructor(
62
+ private row: ConversationRow,
63
+ readonly agent: A,
64
+ private readonly store: ConversationStore,
65
+ private readonly ai: Ai,
66
+ ) {}
67
+
68
+ get id(): string {
69
+ return this.row.id
70
+ }
71
+ get title(): string | null {
72
+ return this.row.title
73
+ }
74
+ get metadata(): Record<string, unknown> {
75
+ return this.row.metadata
76
+ }
77
+ get owner(): { type: string; id: string } | null {
78
+ return this.row.ownerType && this.row.ownerId ? { type: this.row.ownerType, id: this.row.ownerId } : null
79
+ }
80
+ get createdAt(): Date {
81
+ return this.row.createdAt
82
+ }
83
+
84
+ /** Every stored message, oldest first (provider blocks included; send them back unchanged). */
85
+ messages(): Promise<Message[]> {
86
+ return this.store.messages(this.id)
87
+ }
88
+
89
+ /** Continue the conversation; the new messages are stored with the run's id. */
90
+ async send(input: string, options: { context?: Record<string, unknown> } = {}): Promise<AiResult<AgentOutput<A>>> {
91
+ const history = await this.messages()
92
+ const result = await this.ai.result(this.agent, { input, history, ...options }, this.meta())
93
+ await this.storeTurn(history.length, result)
94
+ return result as AiResult<AgentOutput<A>>
95
+ }
96
+
97
+ /** `send` as a stream: the text as it arrives; the messages are stored once it has been read. */
98
+ stream(input: string, options: { context?: Record<string, unknown> } = {}): AiStream<AgentOutput<A>> {
99
+ const self = this
100
+ return new AiStream(
101
+ (async function* () {
102
+ const history = await self.messages()
103
+ const inner = self.ai.stream(self.agent, { input, history, ...options }, self.meta())
104
+ for await (const text of inner) yield { type: 'text' as const, text }
105
+ const result = await inner.result
106
+ await self.storeTurn(history.length, result)
107
+ yield { type: 'result' as const, result }
108
+ })(),
109
+ )
110
+ }
111
+
112
+ /** Change the title or replace the metadata. */
113
+ async update(changes: { title?: string | null; metadata?: Record<string, unknown> }): Promise<void> {
114
+ await this.store.update(this.id, changes)
115
+ this.row = { ...this.row, ...changes } as ConversationRow
116
+ }
117
+
118
+ /** Delete the conversation and its messages (its run records stay, without the link). */
119
+ delete(): Promise<void> {
120
+ return this.store.delete(this.id)
121
+ }
122
+
123
+ private meta() {
124
+ return { conversationId: this.id, compact: true }
125
+ }
126
+
127
+ private async storeTurn(after: number, result: AiResult): Promise<void> {
128
+ const stored = await this.store.append(this.id, after, result.messages.slice(after), result.runId)
129
+ if (!stored)
130
+ throw new ConflictError(
131
+ 'ai.conversation_changed',
132
+ { id: this.id },
133
+ 'Another message was added to this conversation during the run; reload it and send again',
134
+ )
135
+ this.row = { ...this.row, messageCount: result.messages.length }
136
+ }
137
+ }
138
+
139
+ const ownerKey = (owner: OwnerRef | null | undefined, type = 'user') =>
140
+ owner ? { ownerType: type, ownerId: String(owner.id) } : { ownerType: null, ownerId: null }
141
+
142
+ const signedIn = (): OwnerRef | undefined => {
143
+ const id = currentContext()?.userId
144
+ return id === undefined || id === null ? undefined : { id: String(id) }
145
+ }
146
+
147
+ /**
148
+ * Stored conversations (`@inject(Conversations)`), with @cslug/database: `start(Agent, { owner })`, `find(Agent, id)`
149
+ * (owner checked), `list()`.
150
+ */
151
+ export class Conversations {
152
+ /** Set by `AiProvider` when @cslug/database is installed. */
153
+ store?: ConversationStore
154
+
155
+ constructor(private readonly app: Application) {}
156
+
157
+ private get db(): ConversationStore {
158
+ if (!this.store)
159
+ throw new CslugError(
160
+ 'ai.no_database',
161
+ 'Stored conversations need @cslug/database (cslug add database); without it, pass `history` to run()',
162
+ )
163
+ return this.store
164
+ }
165
+
166
+ private open<A extends Agent>(row: ConversationRow, agent: AgentClass<A>): Conversation<A> {
167
+ return new Conversation(row, this.app.resolve(agent as never) as A, this.db, this.app.resolve(Ai))
168
+ }
169
+
170
+ /** A new conversation with `agent`, owned by the signed-in user unless `owner` says otherwise. */
171
+ async start<A extends Agent>(agent: AgentClass<A>, options: StartOptions = {}): Promise<Conversation<A>> {
172
+ const owner = options.owner === undefined ? signedIn() : options.owner
173
+ const row = {
174
+ id: Bun.randomUUIDv7(),
175
+ agent: agent.name,
176
+ ...ownerKey(owner, options.ownerType),
177
+ title: options.title ?? null,
178
+ metadata: options.metadata ?? {},
179
+ createdAt: this.app.resolve(Clock).now(),
180
+ }
181
+ await this.db.create(row)
182
+ return this.open({ ...row, messageCount: 0, updatedAt: row.createdAt }, agent)
183
+ }
184
+
185
+ /**
186
+ * A conversation with `agent`, if its owner is the signed-in user (or `options.owner`); a conversation without an
187
+ * owner is open to anyone with its id. Anything else is a `NotFoundError`, so ids are not confirmed to strangers.
188
+ */
189
+ async find<A extends Agent>(agent: AgentClass<A>, id: string, options: FindOptions = {}): Promise<Conversation<A>> {
190
+ const row = UUID.test(id) ? await this.db.find(id) : null
191
+ if (!row || row.agent !== agent.name || !this.allowed(row, options)) throw new NotFoundError('conversation', id)
192
+ return this.open(row, agent)
193
+ }
194
+
195
+ /** The owner's conversations, most recent first (default: the signed-in user's). */
196
+ async list<A extends Agent>(
197
+ options: FindOptions & { agent?: AgentClass<A>; limit?: number } = {},
198
+ ): Promise<ConversationRow[]> {
199
+ const owner = options.owner ?? signedIn()
200
+ if (!owner) return []
201
+ return this.db.list({
202
+ ...ownerKey(owner, options.ownerType),
203
+ ...(options.agent ? { agent: options.agent.name } : {}),
204
+ limit: options.limit ?? 50,
205
+ })
206
+ }
207
+
208
+ private allowed(row: ConversationRow, { owner, ownerType = 'user' }: FindOptions): boolean {
209
+ if (row.ownerId === null) return true
210
+ const expected = owner ?? (row.ownerType === 'user' ? signedIn() : undefined)
211
+ return !!expected && row.ownerType === (owner ? ownerType : 'user') && row.ownerId === String(expected.id)
212
+ }
213
+ }
214
+
215
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
package/src/drivers.ts ADDED
@@ -0,0 +1,249 @@
1
+ import { CslugError } from '@cslug/core'
2
+ import {
3
+ AiRefusalError,
4
+ type Block,
5
+ type ModelRequest,
6
+ type ModelResponse,
7
+ type Provider,
8
+ postJson,
9
+ type StreamEvent,
10
+ sseEvents,
11
+ } from './model'
12
+
13
+ type Json = Record<string, unknown>
14
+
15
+ export type AnthropicConfig = {
16
+ driver: 'anthropic'
17
+ /** Default: `ANTHROPIC_API_KEY`. */
18
+ apiKey?: string
19
+ baseUrl?: string
20
+ /**
21
+ * Prompt caching, on by default: a breakpoint on the system prompt, and automatic caching (top-level
22
+ * `cache_control`) once there is more than one message, so each turn or tool round reads the earlier ones.
23
+ */
24
+ promptCaching?: boolean
25
+ /** Server-side refusal fallbacks (`fallbacks: "default"`) on the models that have them; on by default. */
26
+ fallbacks?: boolean
27
+ }
28
+
29
+ const API_VERSION = '2026-10-21'
30
+ const FALLBACK_BETA = 'server-side-fallback-2026-07-01'
31
+ const WITH_FALLBACKS = ['claude-fable-5-2', 'claude-fable-5-1', 'claude-opus-5-5', 'claude-opus-5', 'claude-sonnet-5-5']
32
+ const COMPACTION_BETA = 'compact-2026-01-12'
33
+ /** Models with server-side compaction (`context_management` edit `compact_20260112`). */
34
+ const WITH_COMPACTION = [
35
+ 'claude-fable-5-2',
36
+ 'claude-fable-5-1',
37
+ 'claude-fable-5',
38
+ 'claude-opus-5-5',
39
+ 'claude-opus-5',
40
+ 'claude-opus-4-8',
41
+ 'claude-opus-4-7',
42
+ 'claude-opus-4-6',
43
+ 'claude-sonnet-5-5',
44
+ 'claude-sonnet-5',
45
+ 'claude-sonnet-4-6',
46
+ 'claude-haiku-5-5',
47
+ ]
48
+
49
+ const toAnthropic = (b: Block): unknown =>
50
+ b.type === 'raw'
51
+ ? b.value
52
+ : b.type === 'tool_result'
53
+ ? { type: 'tool_result', tool_use_id: b.toolUseId, content: b.content, ...(b.isError ? { is_error: true } : {}) }
54
+ : b
55
+ const fromAnthropic = (b: Json): Block =>
56
+ b.type === 'text'
57
+ ? { type: 'text', text: String(b.text) }
58
+ : b.type === 'tool_use'
59
+ ? { type: 'tool_use', id: String(b.id), name: String(b.name), input: b.input }
60
+ : { type: 'raw', value: b } // thinking, fallback…: sent back unchanged
61
+
62
+ /** The Claude Messages API over `fetch` (no SDK: cslug has no third-party runtime dependencies). */
63
+ export class AnthropicProvider implements Provider {
64
+ constructor(private readonly config: AnthropicConfig) {}
65
+
66
+ private request(r: ModelRequest, stream: boolean): [string, Record<string, string>, Json] {
67
+ const key = this.config.apiKey ?? process.env.ANTHROPIC_API_KEY
68
+ if (!key) throw new CslugError('ai.no_key', 'Set ANTHROPIC_API_KEY (or providers.<name>.apiKey in config/ai.ts)')
69
+ const fallbacks = this.config.fallbacks !== false && WITH_FALLBACKS.includes(r.model)
70
+ const compact = !!r.compact && WITH_COMPACTION.includes(r.model)
71
+ const betas = [...(fallbacks ? [FALLBACK_BETA] : []), ...(compact ? [COMPACTION_BETA] : [])]
72
+ const format = r.output ? { format: { type: 'json_schema', schema: r.output } } : {}
73
+ const caching = this.config.promptCaching !== false
74
+ const body: Json = {
75
+ model: r.model,
76
+ max_tokens: r.maxTokens ?? (stream ? 64_000 : 16_000),
77
+ messages: r.messages.map((m) => ({ role: m.role, content: m.content.map(toAnthropic) })),
78
+ ...(r.system
79
+ ? {
80
+ system: [
81
+ {
82
+ type: 'text',
83
+ text: r.system,
84
+ ...(caching ? { cache_control: { type: 'ephemeral' } } : {}),
85
+ },
86
+ ],
87
+ }
88
+ : {}),
89
+ ...(r.tools.length
90
+ ? { tools: r.tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.inputSchema })) }
91
+ : {}),
92
+ ...(r.output || r.effort ? { output_config: { ...format, ...(r.effort ? { effort: r.effort } : {}) } } : {}),
93
+ ...(caching && r.messages.length > 1 ? { cache_control: { type: 'ephemeral' } } : {}),
94
+ ...(compact ? { context_management: { edits: [{ type: 'compact_20260112' }] } } : {}),
95
+ ...(fallbacks ? { fallbacks: 'default' } : {}),
96
+ ...(stream ? { stream: true } : {}),
97
+ }
98
+ const headers = {
99
+ 'x-api-key': key,
100
+ 'anthropic-version': API_VERSION,
101
+ ...(betas.length ? { 'anthropic-beta': betas.join(',') } : {}),
102
+ }
103
+ return [`${this.config.baseUrl ?? 'https://api.anthropic.com'}/v1/messages`, headers, body]
104
+ }
105
+
106
+ private response(message: Json): ModelResponse {
107
+ if (message.stop_reason === 'refusal')
108
+ throw new AiRefusalError((message.stop_details as Json | null)?.category as string | undefined)
109
+ const usage = (message.usage ?? {}) as Json
110
+ return {
111
+ content: ((message.content ?? []) as Json[]).map(fromAnthropic),
112
+ stopReason: String(message.stop_reason),
113
+ usage: {
114
+ inputTokens: Number(usage.input_tokens ?? 0),
115
+ outputTokens: Number(usage.output_tokens ?? 0),
116
+ cacheReadTokens: Number(usage.cache_read_input_tokens ?? 0),
117
+ cacheWriteTokens: Number(usage.cache_creation_input_tokens ?? 0),
118
+ },
119
+ }
120
+ }
121
+
122
+ async complete(r: ModelRequest): Promise<ModelResponse> {
123
+ return this.response((await (await postJson(...this.request(r, false))).json()) as Json)
124
+ }
125
+
126
+ /** Text deltas as they arrive; blocks are rebuilt from their deltas (tool inputs from `partial_json`). */
127
+ async *stream(r: ModelRequest): AsyncIterable<StreamEvent> {
128
+ const res = await postJson(...this.request(r, true))
129
+ const message: Json = { content: [] }
130
+ const blocks = message.content as Json[]
131
+ const partial: string[] = []
132
+ for await (const { data } of sseEvents(res.body as ReadableStream<Uint8Array>)) {
133
+ const e = JSON.parse(data) as Json
134
+ if (e.type === 'message_start') Object.assign(message, e.message, { content: blocks })
135
+ else if (e.type === 'content_block_start') blocks[Number(e.index)] = { ...(e.content_block as Json) }
136
+ else if (e.type === 'content_block_delta') {
137
+ const block = blocks[Number(e.index)] as Json
138
+ const delta = e.delta as Json
139
+ if (delta.type === 'input_json_delta')
140
+ partial[Number(e.index)] = (partial[Number(e.index)] ?? '') + delta.partial_json
141
+ else
142
+ for (const [k, v] of Object.entries(delta))
143
+ if (k !== 'type') block[k] = typeof v === 'string' && typeof block[k] === 'string' ? block[k] + v : v
144
+ if (delta.type === 'text_delta') yield { type: 'text', text: String(delta.text) }
145
+ } else if (e.type === 'content_block_stop' && partial[Number(e.index)] !== undefined)
146
+ (blocks[Number(e.index)] as Json).input = JSON.parse(partial[Number(e.index)] || '{}')
147
+ else if (e.type === 'message_delta') {
148
+ Object.assign(message, e.delta)
149
+ message.usage = { ...(message.usage as Json), ...(e.usage as Json) }
150
+ } else if (e.type === 'error') throw new CslugError('ai.provider', JSON.stringify(e.error))
151
+ }
152
+ yield { type: 'done', response: this.response(message) }
153
+ }
154
+ }
155
+
156
+ export type OpenAiCompatibleConfig = { driver: 'openai-compatible'; baseUrl: string; apiKey?: string }
157
+
158
+ /** Any OpenAI-compatible chat completions endpoint (Ollama, vLLM, LM Studio…). */
159
+ export class OpenAiCompatibleProvider implements Provider {
160
+ constructor(private readonly config: OpenAiCompatibleConfig) {}
161
+
162
+ private request(r: ModelRequest, stream: boolean): [string, Record<string, string>, Json] {
163
+ const messages: Json[] = r.system ? [{ role: 'system', content: r.system }] : []
164
+ for (const m of r.messages) {
165
+ const text = m.content.flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('')
166
+ const calls = m.content.flatMap((b) =>
167
+ b.type === 'tool_use'
168
+ ? [{ id: b.id, type: 'function', function: { name: b.name, arguments: JSON.stringify(b.input) } }]
169
+ : [],
170
+ )
171
+ for (const b of m.content)
172
+ if (b.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: b.toolUseId, content: b.content })
173
+ if (text || calls.length)
174
+ messages.push({ role: m.role, content: text, ...(calls.length ? { tool_calls: calls } : {}) })
175
+ }
176
+ const body: Json = {
177
+ model: r.model,
178
+ messages,
179
+ ...(r.maxTokens ? { max_tokens: r.maxTokens } : {}),
180
+ ...(r.tools.length
181
+ ? {
182
+ tools: r.tools.map((t) => ({
183
+ type: 'function',
184
+ function: { name: t.name, description: t.description, parameters: t.inputSchema },
185
+ })),
186
+ }
187
+ : {}),
188
+ ...(r.output
189
+ ? { response_format: { type: 'json_schema', json_schema: { name: 'output', schema: r.output, strict: true } } }
190
+ : {}),
191
+ ...(stream ? { stream: true } : {}),
192
+ }
193
+ const headers: Record<string, string> = this.config.apiKey ? { authorization: `Bearer ${this.config.apiKey}` } : {}
194
+ return [`${this.config.baseUrl.replace(/\/$/, '')}/chat/completions`, headers, body]
195
+ }
196
+
197
+ private response(
198
+ text: string,
199
+ calls: { id: string; name: string; arguments: string }[],
200
+ finish: unknown,
201
+ usage?: Json,
202
+ ) {
203
+ const content: Block[] = text ? [{ type: 'text', text }] : []
204
+ for (const c of calls)
205
+ content.push({ type: 'tool_use', id: c.id, name: c.name, input: JSON.parse(c.arguments || '{}') })
206
+ return {
207
+ content,
208
+ stopReason: calls.length ? 'tool_use' : finish === 'length' ? 'max_tokens' : 'end_turn',
209
+ usage: { inputTokens: Number(usage?.prompt_tokens ?? 0), outputTokens: Number(usage?.completion_tokens ?? 0) },
210
+ }
211
+ }
212
+
213
+ async complete(r: ModelRequest): Promise<ModelResponse> {
214
+ const json = (await (await postJson(...this.request(r, false))).json()) as Json
215
+ const choice = ((json.choices ?? []) as Json[])[0] ?? {}
216
+ const message = (choice.message ?? {}) as Json
217
+ const calls = ((message.tool_calls ?? []) as Json[]).map((c) => {
218
+ const fn = c.function as Json
219
+ return { id: String(c.id), name: String(fn.name), arguments: String(fn.arguments ?? '') }
220
+ })
221
+ return this.response(String(message.content ?? ''), calls, choice.finish_reason, json.usage as Json)
222
+ }
223
+
224
+ async *stream(r: ModelRequest): AsyncIterable<StreamEvent> {
225
+ const res = await postJson(...this.request(r, true))
226
+ let text = ''
227
+ let finish: unknown
228
+ const calls: { id: string; name: string; arguments: string }[] = []
229
+ for await (const { data } of sseEvents(res.body as ReadableStream<Uint8Array>)) {
230
+ if (data === '[DONE]') break
231
+ const choice = (((JSON.parse(data) as Json).choices ?? []) as Json[])[0] ?? {}
232
+ const delta = (choice.delta ?? {}) as Json
233
+ if (typeof delta.content === 'string' && delta.content) {
234
+ text += delta.content
235
+ yield { type: 'text', text: delta.content }
236
+ }
237
+ for (const c of (delta.tool_calls ?? []) as Json[]) {
238
+ const fn = (c.function ?? {}) as Json
239
+ const call = calls[Number(c.index)] ?? { id: '', name: '', arguments: '' }
240
+ calls[Number(c.index)] = call
241
+ call.id ||= String(c.id ?? '')
242
+ call.name ||= String(fn.name ?? '')
243
+ call.arguments += String(fn.arguments ?? '')
244
+ }
245
+ finish = choice.finish_reason ?? finish
246
+ }
247
+ yield { type: 'done', response: this.response(text, calls, finish) }
248
+ }
249
+ }
package/src/fake.ts ADDED
@@ -0,0 +1,156 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { type Application, CslugError, Logger } from '@cslug/core'
4
+ import type { Agent, AgentSettings, RunOptions } from './agent'
5
+ import { Ai, type AiConfig, type AiResult, type RunMeta } from './ai'
6
+ import { AiStream } from './ai-stream'
7
+ import type { Message } from './model'
8
+
9
+ type AgentClass<A extends Agent = Agent> = abstract new (...args: never[]) => A
10
+ /** A recorded run: the agent, its input and context. */
11
+ export type AiRun = { agent: AgentSettings } & Required<RunOptions>
12
+
13
+ /** `tests/fixtures/ai/<name>.json`: a real run, written by `cslug ai:record`, replayed by `t.ai.fixture()`. */
14
+ export type AiFixture = {
15
+ agent: string
16
+ input: string
17
+ context: Record<string, unknown>
18
+ /** The conversation before this run, when it continued one. */
19
+ history?: Message[]
20
+ /** The model's answer before validation (parsed JSON, or the text). */
21
+ output: unknown
22
+ model: string
23
+ recordedAt: string
24
+ }
25
+
26
+ /** The folder fixtures live in, under the app root. */
27
+ export const FIXTURES_DIR = 'tests/fixtures/ai'
28
+
29
+ const textOf = (raw: unknown) => (typeof raw === 'string' ? raw : JSON.stringify(raw))
30
+
31
+ export const readFixture = (path: string): AiFixture => JSON.parse(readFileSync(path, 'utf8')) as AiFixture
32
+
33
+ /**
34
+ * AI in tests (`testApp({ fakes: ['ai'] })` → `t.ai`): no provider is called. `respond(Agent, output)` gives an agent
35
+ * its answer (checked against its `output` schema, so fixtures stay valid); every run is recorded.
36
+ */
37
+ export class AiFake extends Ai {
38
+ readonly runs: AiRun[] = []
39
+ private readonly answers = new Map<AgentClass, (run: AiRun) => unknown>()
40
+ private real?: Ai
41
+
42
+ constructor(app: Application) {
43
+ super(app, {}, Logger.null())
44
+ }
45
+
46
+ /** An agent's answer: a value, or a function of the run (its input, context, history). */
47
+ respond<A extends Agent>(agent: AgentClass<A>, answer: (run: AiRun) => unknown): this
48
+ respond<A extends Agent>(agent: AgentClass<A>, output: unknown): this
49
+ respond<A extends Agent>(agent: AgentClass<A>, output: unknown): this {
50
+ this.answers.set(agent, typeof output === 'function' ? (output as (run: AiRun) => unknown) : () => output)
51
+ return this
52
+ }
53
+
54
+ /**
55
+ * Answer an agent with a recorded fixture, `tests/fixtures/ai/<name>.json`. `cslug ai:record` runs the test against
56
+ * the real provider and writes the fixtures that are missing (`--all`: every one).
57
+ */
58
+ fixture<A extends Agent>(agent: AgentClass<A>, name: string): this {
59
+ const path = join(this.app.rootDir, FIXTURES_DIR, `${name}.json`)
60
+ return this.respond(agent, async (run: AiRun) => {
61
+ const mode = process.env.CSLUG_AI_RECORD
62
+ if (mode === 'all' || (mode && !existsSync(path))) return this.record(run, path)
63
+ if (!existsSync(path))
64
+ throw new CslugError(
65
+ 'ai.no_fixture',
66
+ `No AI fixture ${FIXTURES_DIR}/${name}.json: record it with \`cslug ai:record <this test file>\``,
67
+ )
68
+ return readFixture(path).output
69
+ })
70
+ }
71
+
72
+ /** Run against the real provider (config `ai`) and write the fixture. */
73
+ private async record(run: AiRun, path: string): Promise<unknown> {
74
+ this.real ??= new Ai(this.app, this.app.config<AiConfig | undefined>('ai') ?? {}, Logger.null())
75
+ const result = await this.real.result(run.agent, run)
76
+ const fixture: AiFixture = {
77
+ agent: run.agent.constructor.name,
78
+ input: run.input,
79
+ context: run.context,
80
+ ...(run.history.length ? { history: run.history } : {}),
81
+ output: result.raw,
82
+ model: result.model,
83
+ recordedAt: new Date().toISOString(),
84
+ }
85
+ mkdirSync(dirname(path), { recursive: true })
86
+ writeFileSync(path, `${JSON.stringify(fixture, null, 2)}\n`)
87
+ process.stderr.write(`recorded ${path} (${result.model}, $${(result.costUsd ?? 0).toFixed(4)})\n`)
88
+ return result.raw
89
+ }
90
+
91
+ /** The fake's answer as a run result: no provider call, no cost; `messages` continue the `history`. */
92
+ override async result(
93
+ agent: AgentSettings,
94
+ { input, context = {}, history = [] }: RunOptions,
95
+ _meta?: RunMeta,
96
+ ): Promise<AiResult> {
97
+ const run: AiRun = { agent, input, context, history }
98
+ this.runs.push(run)
99
+ const answer = [...this.answers].find(([cls]) => agent instanceof cls)?.[1]
100
+ if (!answer)
101
+ throw new Error(`No fake answer for ${agent.constructor.name}: t.ai.respond(${agent.constructor.name}, …)`)
102
+ const raw = await answer(run)
103
+ const value = agent.output ? this.validate(agent, raw) : String(raw)
104
+ return {
105
+ runId: Bun.randomUUIDv7(),
106
+ value,
107
+ raw,
108
+ model: 'fake',
109
+ steps: 1,
110
+ usage: { inputTokens: 0, outputTokens: 0 },
111
+ costUsd: 0,
112
+ messages: [
113
+ ...history,
114
+ { role: 'user', content: [{ type: 'text', text: input }] },
115
+ { role: 'assistant', content: [{ type: 'text', text: textOf(raw) }] },
116
+ ],
117
+ }
118
+ }
119
+
120
+ /** The whole answer as one piece of text, then the result. */
121
+ override stream(agent: AgentSettings, options: RunOptions, _meta?: RunMeta): AiStream {
122
+ const result = this.result(agent, options)
123
+ return new AiStream(
124
+ (async function* () {
125
+ const done = await result
126
+ yield { type: 'text' as const, text: textOf(done.raw) }
127
+ yield { type: 'result' as const, result: done }
128
+ })(),
129
+ )
130
+ }
131
+
132
+ override async close(): Promise<void> {
133
+ await this.real?.close()
134
+ }
135
+
136
+ ran<A extends Agent>(agent: AgentClass<A>): AiRun[] {
137
+ return this.runs.filter((r) => r.agent instanceof agent)
138
+ }
139
+
140
+ assertRan<A extends Agent>(agent: AgentClass<A>, where?: (run: AiRun) => boolean): void {
141
+ if (!this.ran(agent).some((r) => !where || where(r)))
142
+ throw new Error(
143
+ `Expected ${agent.name} to run${where ? ' (matching)' : ''}; ran: ${this.runs.map((r) => r.agent.constructor.name).join(', ') || 'none'}`,
144
+ )
145
+ }
146
+
147
+ assertNotRan<A extends Agent>(agent: AgentClass<A>): void {
148
+ if (this.ran(agent).length) throw new Error(`Expected ${agent.name} not to run`)
149
+ }
150
+ }
151
+
152
+ export function installAiFake(app: Application): AiFake {
153
+ const fake = new AiFake(app)
154
+ app.swap(Ai, fake)
155
+ return fake
156
+ }
package/src/index.ts CHANGED
@@ -1,6 +1,70 @@
1
1
  /**
2
- * @cslug/ai: Agents, tools, structured output and MCP.
3
- *
4
- * Not implemented yet. See docs/packages.md and docs/implementation-plan.md.
2
+ * @cslug/ai: agents and tools as `@inject()` classes, structured output validated by `v` schemas, prompts as
3
+ * Markdown files, streaming to the browser, Anthropic and OpenAI-compatible providers over `fetch`, a test fake.
5
4
  */
6
- export {}
5
+ export {
6
+ Agent,
7
+ type AgentOutput,
8
+ type AgentSettings,
9
+ Prompt,
10
+ prompt,
11
+ type RunnableTool,
12
+ type RunOptions,
13
+ Tool,
14
+ type ToolClass,
15
+ } from './agent'
16
+ export { Ai, type AiConfig, AiOutputError, type AiResult, type RunMeta, type RunRecord } from './ai'
17
+ export { AiEvalCommand, jsonDiff } from './ai-eval-command'
18
+ export { AiPromptsCommand, AiProvider, AiRecordCommand, McpServeCommand } from './ai-provider'
19
+ export { AiStream } from './ai-stream'
20
+ export {
21
+ AiBudgetAlert,
22
+ AiBudgetError,
23
+ Budget,
24
+ type BudgetConfig,
25
+ costOf,
26
+ MODEL_PRICES,
27
+ type ModelPrice,
28
+ } from './budget'
29
+ export { AI_MIGRATIONS } from './conversation-store'
30
+ export {
31
+ Conversation,
32
+ type ConversationRow,
33
+ type ConversationStore,
34
+ Conversations,
35
+ type FindOptions,
36
+ type OwnerRef,
37
+ type StartOptions,
38
+ } from './conversations'
39
+ export {
40
+ type AnthropicConfig,
41
+ AnthropicProvider,
42
+ type OpenAiCompatibleConfig,
43
+ OpenAiCompatibleProvider,
44
+ } from './drivers'
45
+ export { AiFake, type AiFixture, type AiRun, FIXTURES_DIR, installAiFake } from './fake'
46
+ export {
47
+ asMcpTools,
48
+ discoverTools,
49
+ handleMcp,
50
+ MCP_VERSIONS,
51
+ type McpCaller,
52
+ type McpOptions,
53
+ type McpReply,
54
+ mcpTools,
55
+ } from './mcp'
56
+ export { McpConnection, type McpServerConfig, McpTools, mcp } from './mcp-client'
57
+ export {
58
+ AiRefusalError,
59
+ type Block,
60
+ type Effort,
61
+ type Message,
62
+ type ModelRequest,
63
+ type ModelResponse,
64
+ modelSchema,
65
+ type Provider,
66
+ type StreamEvent,
67
+ type ToolSpec,
68
+ type Usage,
69
+ } from './model'
70
+ export { sse } from './sse'