@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.
package/README.md CHANGED
@@ -1,5 +1,8 @@
1
1
  # @cslug/ai
2
2
 
3
- Agents, tools, structured output and MCP.
3
+ Agents and tools as `@inject()` classes, structured output validated by `v` schemas, prompts as Markdown files,
4
+ streaming to the browser with `sse()`, Anthropic and OpenAI-compatible providers over `fetch`, and a test fake.
5
+ `cslug add ai` installs it and adds `AiProvider`.
4
6
 
5
- > Not implemented yet. Part of [cslug](https://github.com/cslugts/cslug).
7
+ Part of [cslug](https://github.com/cslugts/cslug). Docs: [docs/README.md](docs/README.md), [docs/api.md](docs/api.md),
8
+ [guide 18](../../guides/18-ai.md).
package/docs/README.md CHANGED
@@ -1,6 +1,131 @@
1
1
  # @cslug/ai
2
2
 
3
- Agents, tools, structured output and MCP.
3
+ List `AiProvider` in `bootstrap/providers.ts` (`cslug add ai` does it and writes `config/ai.ts`). The guide is
4
+ [guide 18](../../../guides/18-ai.md).
4
5
 
5
- > **Not implemented yet.** This version is an empty placeholder kept for the lockstep release; the package is
6
- > planned for a later release.
6
+ ## Agents
7
+
8
+ An agent is an `@inject()` class with a `model` (a model ID, or a role from `ai.models`) and, optionally,
9
+ `instructions` (a string or `prompt('name')`), `output` (a `v` schema), `tools`, `maxSteps` (8), `provider`,
10
+ `effort` and `maxTokens`. These settings are not declared on `Agent`, as for jobs, so apps compiled with
11
+ `noImplicitOverride` don't write `override`.
12
+
13
+ `run({ input, context })`:
14
+
15
+ 1. renders the instructions (`{{ variables }}` from `context`),
16
+ 2. calls the provider with the tools and, with `output`, the schema as structured output (the JSON Schema without
17
+ the constraints the API rejects: numeric and length limits, patterns, array sizes),
18
+ 3. while the model calls tools: validates each input with the tool's schema, runs the calls of the turn together and
19
+ sends every result back in one message (an invalid input or a thrown error as an error result),
20
+ 4. parses and validates the final answer with the full schema → typed result, or `AiOutputError`.
21
+
22
+ `stream({ input, context })` yields the text as it arrives (tools run between turns). `sse(stream)` makes it a
23
+ `text/event-stream` response, keeping the request's context. The stream's `result` promise settles with the finished
24
+ run once the text has been read (and rejects with the run's error).
25
+
26
+ **Conversations.** `history` takes a previous result's `messages` and continues them: the request is the history,
27
+ then the new input. `result()` (on the agent or on `Ai`) and `stream().result` return `messages`: the history plus
28
+ this run's input, tool rounds and answer, to pass as `history` next turn. Provider blocks (thinking, fallbacks) are
29
+ kept, so send the messages back unchanged; they are JSON. The history passed in is not modified. With the Anthropic
30
+ driver and `promptCaching` on, a request with more than one message also sets automatic caching (top-level
31
+ `cache_control`), after the system prompt's breakpoint, so each turn and tool round reads the earlier ones from the
32
+ cache.
33
+
34
+ ## Stored conversations and run records (with @cslug/database)
35
+
36
+ `AiProvider` registers the `cslug_ai` migration when `Database` is bound:
37
+
38
+ | Table | Holds |
39
+ |---|---|
40
+ | `cslug_ai_conversations` | `id` (UUIDv7), `agent` (class name), `owner_type` + `owner_id`, `title`, `metadata` (jsonb), `message_count`, timestamps |
41
+ | `cslug_ai_messages` | `conversation_id` + `position` (key), `role`, `content` (the blocks, jsonb), `run_id` |
42
+ | `cslug_ai_runs` | one row per run: agent, model, `conversation_id`, `user_id` (the signed-in user), status (`completed` / `failed`), steps, token counts, `cost_usd` (estimate), error, `started_at` / `finished_at` |
43
+
44
+ `Conversations` (injectable):
45
+
46
+ - `start(Agent, { owner?, ownerType?, title?, metadata? })`: the owner is the signed-in user (the ambient context's
47
+ `userId`, set by @cslug/auth) unless given; `owner: null` for none; `ownerType` defaults to `user`.
48
+ - `find(Agent, id, { owner?, ownerType? })`: the conversation if it was started with that agent and its owner is the
49
+ signed-in user (or the owner given); an unowned one is open to anyone. Anything else, a malformed id included,
50
+ is `NotFoundError`.
51
+ - `list({ owner?, ownerType?, agent?, limit = 50 })`: rows, most recent first (`updatedAt`); empty without an owner.
52
+
53
+ `Conversation`: `id`, `agent`, `title`, `metadata`, `owner`, `createdAt`; `send(input, { context })` →
54
+ `AiResult` (the stored history, then the input; the new messages are appended with the run's id); `stream(input)` →
55
+ `AiStream` (stored once read); `messages()`; `update({ title, metadata })`; `delete()` (messages too; run records
56
+ keep their row, unlinked). A turn is stored only if no other was stored since it read the history, else
57
+ `ConflictError` (`ai.conversation_changed`). Turns in a conversation ask for server-side compaction
58
+ (`compact_20260112`, Anthropic models that support it); `compact = false` on the agent turns it off, `compact = true`
59
+ turns it on for plain runs. Timestamps come from `Clock`.
60
+
61
+ `Ai` records every run (`ai.result`, `run`, `stream`; in a conversation or not) through `ai.recorder`;
62
+ `ai.runs: false` turns it off, and a failure to record is logged (`ai.run_not_recorded`), never thrown. Without
63
+ @cslug/database nothing is recorded, and `Conversations` throws `ai.no_database`.
64
+
65
+ ## Providers
66
+
67
+ | Driver | Config | |
68
+ |---|---|---|
69
+ | `anthropic` | `apiKey` (default `ANTHROPIC_API_KEY`), `baseUrl`, `promptCaching` (true), `fallbacks` (true) | The Messages API (`anthropic-version: 2026-10-21`) with `fetch`: the system prompt cached with `cache_control`, structured output through `output_config.format`, `effort` in `output_config`, `max_tokens` 16000 (64000 when streaming). On the models that have server-side refusal fallbacks (Claude Fable 5.2 / 5.1, Opus 5.5 / 5, Sonnet 5.5) requests carry `fallbacks: "default"`. Thinking and other blocks are sent back unchanged in a tool loop. A refusal is `AiRefusalError` (`category`) |
70
+ | `openai-compatible` | `baseUrl`, `apiKey` | Chat completions (Ollama, vLLM, LM Studio…): function tools, `response_format` JSON Schema, streaming |
71
+
72
+ Without `config/ai.ts`, the default provider is `anthropic`. `ai.extend(name, provider)` adds one (any object with
73
+ `complete` and `stream`).
74
+
75
+ `ai.result(agent, { input, context })` is `run()` in detail: `{ value, raw, model, steps, usage, costUsd }` (`raw` is
76
+ the answer before validation: the parsed JSON, or the text).
77
+
78
+ ## Daily budget
79
+
80
+ ```ts
81
+ budget: { perDay: { usd: 10 }, alertAt: 0.8 }, // config/ai.ts
82
+ prices: { 'llama3.3': { input: 0, output: 0 } }, // USD per million tokens, for models the built-in table lacks
83
+ ```
84
+
85
+ Each model call is charged after it answers, at the model's price (`MODEL_PRICES`: Anthropic's first-party prices;
86
+ cache reads at 0.1× and cache writes at 1.25× the input price). Before each call, a spend at or above the limit is
87
+ `AiBudgetError`: nothing is called until the next day in the app's time zone. When the spend crosses `alertAt` (0.8)
88
+ of the limit, `AiBudgetAlert` (`ai.budget_alert`: `{ day, spentUsd, limitUsd }`) is emitted once and logged. The spend
89
+ is kept in the app's `Cache` (`ai:spend:<day>`), so with @cslug/redis every process shares it; with the in-memory
90
+ cache each process counts its own. A model without a price costs nothing and is logged once (`ai.budget_unpriced`).
91
+ The figures are estimates from the token counts, not the provider's bill.
92
+
93
+ ## Tests
94
+
95
+ `testApp({ fakes: ['ai'] })` → `t.ai`: no provider is called. `respond(Agent, output | (run) => output)` gives an
96
+ agent its answer (checked against its `output` schema); `assertRan(Agent, where?)`, `assertNotRan(Agent)`,
97
+ `ran(Agent)`, `runs`.
98
+
99
+ **Recorded fixtures.** `t.ai.fixture(Agent, 'proposals/isalo')` answers with `tests/fixtures/ai/proposals/isalo.json`
100
+ (validated like `respond`). A missing file is an error that names the command to run:
101
+
102
+ - `cslug ai:record [path]` runs `bun test [path]` with `CSLUG_AI_RECORD=missing`: a `fixture()` whose file is
103
+ missing calls the real provider (config `ai`) and writes `{ agent, input, context, output, model, recordedAt }`,
104
+ `output` being the raw answer. `--all` re-records every fixture the tests reach. Commit the files.
105
+ - `cslug ai:eval [folder]` runs every fixture under `tests/fixtures/ai/[folder]` through the real model, with the
106
+ agent class found by name in `app/agents/`: `same`, `diff` (the changed paths), `schema` (an `AiOutputError`) or
107
+ `error`, plus the estimated cost. Schema failures and errors exit 1; diffs only with `--strict`. `--json` prints
108
+ the rows.
109
+
110
+ Both call the provider and cost money (and count against the daily budget).
111
+
112
+ ## MCP
113
+
114
+ **Serving.** `@mcp(options)` on a `Tool` class in `app/tools/` (imported at boot) exposes it:
115
+
116
+ - `POST /mcp` (when @cslug/http is installed and a tool is exposed): streamable HTTP with JSON responses, `202` for
117
+ notifications, `404` for an unknown method, `405` for GET, `403` when `Origin` is not `app.url`'s. It runs the api
118
+ group's middleware, so `ctx.auth` (from @cslug/auth) is the caller. Options: none → any authenticated caller;
119
+ `public: true` → anyone; `guard: 'token'` → that guard; `ability: 'mcp:x'` → a token with that ability (session
120
+ users pass). A tool the caller may not use is not listed and is "unknown" when called.
121
+ - `cslug mcp:serve`: stdio (newline-delimited JSON-RPC on stdout, logs on stderr); every exposed tool.
122
+
123
+ Protocol: `server/discover` and per-request versions (2026-07-28), and `initialize` for 2025-11-25, 2025-06-18 and
124
+ 2025-03-26 (the client's version if supported, else 2025-11-25). `tools/list`, `tools/call` (input validated; a
125
+ plain-object result is also `structuredContent`; an error is `isError: true`), `ping`. An unsupported
126
+ `_meta["io.modelcontextprotocol/protocolVersion"]` is error `-32022`.
127
+
128
+ **Using a server.** `config/ai.ts` → `mcp.<name>`: `{ url, headers? }` or `{ command, env? }` (stdio, started on first
129
+ use, stopped at shutdown). In an agent: `tools = [...mcp('maps').tools(['route_duration'])]` (all tools without a
130
+ list). The client tries `server/discover` (2026-07-28), else `initialize` (2025-11-25), keeps `Mcp-Session-Id` for
131
+ older HTTP servers, reads JSON or SSE responses. A tool error comes back to the model as an error result.
package/docs/api.md ADDED
@@ -0,0 +1,36 @@
1
+ # @cslug/ai: API
2
+
3
+ | | |
4
+ |---|---|
5
+ | `Agent` | Abstract `model`; settings `AgentSettings` (`instructions`, `output`, `tools`, `maxSteps`, `provider`, `effort`, `maxTokens`); `run(options)` → `AgentOutput<this>`; `result(options)` → `AiResult<AgentOutput<this>>`; `stream(options)` → `AiStream` |
6
+ | `RunOptions` | `{ input, context?, history? }`: `history` is a previous result's `messages` |
7
+ | `AiStream` | Async iterable of text; `result: Promise<AiResult>`, settled once the text is read |
8
+ | `Tool` | Abstract `name`, `description`, `input` (a `v` schema), `handle(input)` |
9
+ | `prompt(name)` / `Prompt` | `resources/prompts/<name>.md`; `render(vars)`, `ai.prompt_variables` when one is missing |
10
+ | `Ai` | Injectable runtime: `run(agent, options)`, `result(agent, options, meta?)` → `AiResult`, `stream(agent, options, meta?)`, `provider(name?)`, `extend(name, provider)`, `budget`, `recorder` |
11
+ | `AiResult` | `{ runId, value, raw, model, steps, usage, costUsd, messages }` |
12
+ | `Conversations` | `start(Agent, options)`, `find(Agent, id, options)`, `list(options)`; `store` (set with @cslug/database) |
13
+ | `Conversation` | `id`, `agent`, `title`, `metadata`, `owner`, `createdAt`; `send(input)`, `stream(input)`, `messages()`, `update(changes)`, `delete()` |
14
+ | `ConversationStore`, `ConversationRow`, `OwnerRef`, `StartOptions`, `FindOptions` | The store contract and shapes |
15
+ | `RunRecord`, `RunMeta` | A `cslug_ai_runs` row; `ai.result(agent, options, meta)`'s third argument (`conversationId`, `compact`) |
16
+ | `AI_MIGRATIONS` | The migrations folder (registered at boot with @cslug/database) |
17
+ | `AiProvider` | Config `ai`: `default`, `providers.<name>`, `models`, `mcp`, `budget`, `prices`, `runs`; binds `Conversations`; commands `ai:prompts`, `ai:record`, `ai:eval`, `mcp:serve` |
18
+ | `AiRecordCommand` | `cslug ai:record [path] [--all]`: `bun test` with `CSLUG_AI_RECORD` set, writing missing (all) fixtures |
19
+ | `AiEvalCommand` | `cslug ai:eval [folder] [--strict] [--json]`: fixtures through the real model; `jsonDiff(a, b)` |
20
+ | `Budget` | The daily budget: `spent()`, `check()`, `charge(model, usage)`; `BudgetConfig` `{ perDay: { usd }, alertAt? }` |
21
+ | `costOf(model, usage, prices?)`, `MODEL_PRICES`, `ModelPrice` | Estimated USD cost of a call (`undefined` without a price) |
22
+ | `AiBudgetError` | The day's budget is spent (`spentUsd`, `limitUsd`) |
23
+ | `AiBudgetAlert` | Event `ai.budget_alert` `{ day, spentUsd, limitUsd }`, once a day at `alertAt` |
24
+ | `AnthropicProvider`, `OpenAiCompatibleProvider` | The drivers; `Provider` is `{ complete(request), stream(request) }` |
25
+ | `ModelRequest`, `ModelResponse`, `Block`, `Message`, `StreamEvent`, `Usage` | The neutral request and response shapes (`Usage`: input, output, cache read and cache write tokens) |
26
+ | `modelSchema(jsonSchema)` | A JSON Schema as structured output accepts it |
27
+ | `sse(textStream)` | A `Responsable` streaming server-sent events |
28
+ | `AiOutputError` | The answer is not JSON or breaks the `output` schema (`text`, `issues`) |
29
+ | `AiRefusalError` | The model declined (`category`) |
30
+ | `mcp(options?)` | Decorator: expose a `Tool` over MCP (`public`, `guard`, `ability`) |
31
+ | `mcp(server).tools(names?)` | An MCP server's tools for an agent's `tools` |
32
+ | `McpConnection(name, config)` | A client: `request(method, params)`, `close()` |
33
+ | `handleMcp(message, tools, caller)` | One MCP message → its reply, over the `@mcp()` tools `caller` may use (core's `handleMcpMessage`); `asMcpTools(tools, caller)`, `MCP_VERSIONS`, `discoverTools(app)`, `mcpTools()` |
34
+ | `McpServeCommand` | `cslug mcp:serve` (stdio) |
35
+ | `AiFake`, `installAiFake(app)` | `fakes: ['ai']`: `respond`, `fixture(Agent, name)`, `assertRan`, `assertNotRan`, `ran`, `runs` |
36
+ | `AiFixture`, `FIXTURES_DIR` | A fixture file's shape (`history` when the run continued one); `tests/fixtures/ai` |
@@ -0,0 +1,48 @@
1
+ -- up
2
+ create table cslug_ai_conversations (
3
+ id uuid primary key,
4
+ agent text not null,
5
+ owner_type text,
6
+ owner_id text,
7
+ title text,
8
+ metadata jsonb not null default '{}',
9
+ message_count integer not null default 0,
10
+ created_at timestamptz not null default now(),
11
+ updated_at timestamptz not null default now()
12
+ );
13
+ create index cslug_ai_conversations_owner_idx on cslug_ai_conversations (owner_type, owner_id, updated_at desc);
14
+
15
+ create table cslug_ai_messages (
16
+ conversation_id uuid not null references cslug_ai_conversations (id) on delete cascade,
17
+ position integer not null,
18
+ role text not null,
19
+ content jsonb not null,
20
+ run_id uuid,
21
+ created_at timestamptz not null default now(),
22
+ primary key (conversation_id, position)
23
+ );
24
+
25
+ create table cslug_ai_runs (
26
+ id uuid primary key,
27
+ agent text not null,
28
+ model text not null,
29
+ conversation_id uuid references cslug_ai_conversations (id) on delete set null,
30
+ user_id text,
31
+ status text not null,
32
+ steps integer not null default 0,
33
+ input_tokens integer not null default 0,
34
+ output_tokens integer not null default 0,
35
+ cache_read_tokens integer not null default 0,
36
+ cache_write_tokens integer not null default 0,
37
+ cost_usd numeric(12, 6),
38
+ error text,
39
+ started_at timestamptz not null,
40
+ finished_at timestamptz not null
41
+ );
42
+ create index cslug_ai_runs_started_idx on cslug_ai_runs (started_at desc);
43
+ create index cslug_ai_runs_user_idx on cslug_ai_runs (user_id, started_at desc);
44
+
45
+ -- down
46
+ drop table cslug_ai_runs;
47
+ drop table cslug_ai_messages;
48
+ drop table cslug_ai_conversations;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cslug/ai",
3
- "version": "0.4.1",
4
- "description": "Agents, tools, structured output and MCP.",
3
+ "version": "0.5.0",
4
+ "description": "Agents and tools, structured output, prompts, streaming; Anthropic and OpenAI-compatible providers.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "repository": {
@@ -20,6 +20,7 @@
20
20
  },
21
21
  "files": [
22
22
  "src",
23
+ "migrations",
23
24
  "docs",
24
25
  "stubs",
25
26
  "README.md"
@@ -28,13 +29,26 @@
28
29
  "bun": ">=1.3.14"
29
30
  },
30
31
  "peerDependencies": {
31
- "@cslug/core": "0.4.1",
32
- "@cslug/validation": "0.4.1",
33
- "@cslug/queue": "0.4.1"
32
+ "@cslug/core": "0.5.0",
33
+ "@cslug/validation": "0.5.0",
34
+ "@cslug/queue": "0.5.0",
35
+ "@cslug/http": "0.5.0",
36
+ "@cslug/database": "0.5.0"
34
37
  },
35
38
  "peerDependenciesMeta": {
36
39
  "@cslug/queue": {
37
40
  "optional": true
41
+ },
42
+ "@cslug/http": {
43
+ "optional": true
44
+ },
45
+ "@cslug/database": {
46
+ "optional": true
38
47
  }
48
+ },
49
+ "devDependencies": {
50
+ "@cslug/testing": "workspace:*",
51
+ "@cslug/http": "workspace:*",
52
+ "@cslug/database": "workspace:*"
39
53
  }
40
54
  }
package/src/agent.ts ADDED
@@ -0,0 +1,115 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { type Class, CslugError, currentApp, resolve } from '@cslug/core'
4
+ import type { Schema } from '@cslug/validation'
5
+ import type { AiResult } from './ai'
6
+ import { Ai } from './ai'
7
+ import type { AiStream } from './ai-stream'
8
+ import type { McpTools } from './mcp-client'
9
+ import type { Effort, Message } from './model'
10
+
11
+ /** A prompt file, `resources/prompts/<name>.md`, with `{{ variables }}` filled from the run's `context`. */
12
+ export class Prompt {
13
+ constructor(readonly name: string) {}
14
+
15
+ get path(): string {
16
+ return join(currentApp().rootDir, 'resources/prompts', `${this.name}.md`)
17
+ }
18
+
19
+ render(vars: Record<string, unknown> = {}): string {
20
+ if (!existsSync(this.path)) throw new CslugError('ai.no_prompt', `No prompt file resources/prompts/${this.name}.md`)
21
+ const missing = new Set<string>()
22
+ const text = readFileSync(this.path, 'utf8').replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_m, key: string) => {
23
+ if (!(key in vars)) missing.add(key)
24
+ return String(vars[key] ?? '')
25
+ })
26
+ if (missing.size)
27
+ throw new CslugError('ai.prompt_variables', `Prompt ${this.name} needs ${[...missing].join(', ')} in context`)
28
+ return text
29
+ }
30
+ }
31
+
32
+ /** `instructions = prompt('proposals/extract-offer')` → `resources/prompts/proposals/extract-offer.md`. */
33
+ export const prompt = (name: string) => new Prompt(name)
34
+
35
+ /**
36
+ * Something an agent can call: an `@inject()` class with a name, a description, an input schema and `handle(input)`.
37
+ * The input is validated before `handle` runs; a validation failure or a thrown error goes back to the model as an
38
+ * error result, so it can correct itself.
39
+ */
40
+ export abstract class Tool {
41
+ abstract name: string
42
+ abstract description: string
43
+ abstract input: Schema<unknown>
44
+ abstract handle(input: never): unknown
45
+ }
46
+
47
+ /** What a run calls: a `Tool`, or an MCP server's tool (its input is checked by that server). */
48
+ export type RunnableTool = {
49
+ name: string
50
+ description: string
51
+ input: Pick<Schema<unknown>, 'toJSONSchema' | 'safeParse'>
52
+ handle(input: never): unknown
53
+ }
54
+ export type ToolClass = Class<Tool>
55
+
56
+ export type RunOptions = {
57
+ input: string
58
+ context?: Record<string, unknown>
59
+ /**
60
+ * The conversation so far: a previous result's `messages`, unchanged. The run continues it (append-only, so the
61
+ * provider's prompt cache keeps the earlier turns).
62
+ */
63
+ history?: Message[]
64
+ }
65
+
66
+ /**
67
+ * What an agent may declare besides `model`. These are deliberately not declared on `Agent` (as for jobs), so apps
68
+ * compiled with `noImplicitOverride` write `instructions = …` without `override`.
69
+ */
70
+ export type AgentSettings = {
71
+ /** A model ID (`claude-opus-5-5`), or a role from config `ai.models` (`fast`, `smart`). */
72
+ model: string
73
+ instructions?: string | Prompt
74
+ /** Structured output: the answer is parsed and validated (`AiOutputError` otherwise). */
75
+ output?: Schema<unknown>
76
+ /** Tool classes, and MCP servers' tools: `tools = [FindOperatorsTool, ...mcp('maps').tools(['route_duration'])]`. */
77
+ tools?: (ToolClass | McpTools)[]
78
+ /** Model calls before giving up (each tool round is one); default 8. */
79
+ maxSteps?: number
80
+ /** A provider from config `ai.providers` (default: `ai.default`). */
81
+ provider?: string
82
+ effort?: Effort
83
+ maxTokens?: number
84
+ /**
85
+ * Let the provider summarise a long history server-side (Anthropic compaction, at about 150K input tokens, on the
86
+ * models that support it). On by default in a `Conversation`; `false` turns it off there.
87
+ */
88
+ compact?: boolean
89
+ }
90
+
91
+ /** What `run()` returns: the `output` schema's type, or the text. */
92
+ export type AgentOutput<A> = A extends { output: Schema<infer O> } ? O : string
93
+
94
+ /**
95
+ * An AI task as a class: a model, instructions, optional tools and an optional `output` schema
96
+ * ({@link AgentSettings}). `run()` returns the result; `stream()` yields the text as it arrives. Pass a previous
97
+ * result's `messages` as `history` to continue a conversation.
98
+ */
99
+ export abstract class Agent {
100
+ abstract model: string
101
+
102
+ run(options: RunOptions): Promise<AgentOutput<this>> {
103
+ return resolve(Ai).run(this, options) as Promise<AgentOutput<this>>
104
+ }
105
+
106
+ /** The run in detail: the value, the raw answer, `messages` (the conversation to pass as `history` next turn), usage, cost. */
107
+ result(options: RunOptions): Promise<AiResult<AgentOutput<this>>> {
108
+ return resolve(Ai).result(this, options) as Promise<AiResult<AgentOutput<this>>>
109
+ }
110
+
111
+ /** The text as it arrives; `.result` gives the finished run once it has been read. */
112
+ stream(options: RunOptions): AiStream<AgentOutput<this>> {
113
+ return resolve(Ai).stream(this, options) as AiStream<AgentOutput<this>>
114
+ }
115
+ }
@@ -0,0 +1,100 @@
1
+ import { existsSync, readdirSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { arg, Command, flag } from '@cslug/core'
4
+ import { Agent } from './agent'
5
+ import { Ai, AiOutputError } from './ai'
6
+ import { FIXTURES_DIR, readFixture } from './fake'
7
+
8
+ /** Where two JSON values differ, as `path: before → after` lines. */
9
+ export function jsonDiff(before: unknown, after: unknown, path = ''): string[] {
10
+ const show = (x: unknown) => (x === undefined ? '(none)' : JSON.stringify(x))
11
+ if (Object.is(before, after)) return []
12
+ const objects = before && after && typeof before === 'object' && typeof after === 'object'
13
+ if (!objects || Array.isArray(before) !== Array.isArray(after))
14
+ return [`${path || '(answer)'}: ${show(before)} → ${show(after)}`]
15
+ const a = before as Record<string, unknown>
16
+ const b = after as Record<string, unknown>
17
+ const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])]
18
+ return keys.flatMap((k) => jsonDiff(a[k], b[k], Array.isArray(before) ? `${path}[${k}]` : path ? `${path}.${k}` : k))
19
+ }
20
+
21
+ /** The agent classes exported by the modules under `app/agents/`, by class name. */
22
+ async function agentClasses(rootDir: string): Promise<Map<string, new () => Agent>> {
23
+ const dir = join(rootDir, 'app/agents')
24
+ const found = new Map<string, new () => Agent>()
25
+ if (!existsSync(dir)) return found
26
+ for (const file of (readdirSync(dir, { recursive: true }) as string[]).filter((f) => /(?<!\.test)\.ts$/.test(f)))
27
+ for (const value of Object.values(await import(join(dir, file))))
28
+ if (typeof value === 'function' && value.prototype instanceof Agent)
29
+ found.set(value.name, value as new () => Agent)
30
+ return found
31
+ }
32
+
33
+ /**
34
+ * `cslug ai:eval [folder]`: every fixture under `tests/fixtures/ai/<folder>` through the real model. A schema failure or
35
+ * an error fails the command; a different answer is reported as a diff (failing only with `--strict`).
36
+ */
37
+ export class AiEvalCommand extends Command {
38
+ static signature = 'ai:eval'
39
+ static description = 'Run recorded AI fixtures through the real model: schema failures and diffs (calls the API)'
40
+ static args = {
41
+ folder: arg.string().optional().describe(`A folder under ${FIXTURES_DIR}, e.g. proposals`),
42
+ strict: flag.boolean().describe('Fail when an answer differs from its fixture'),
43
+ json: flag.boolean(),
44
+ }
45
+
46
+ async handle({ folder, strict, json }: Command.Args<typeof AiEvalCommand>) {
47
+ const dir = join(this.app.rootDir, FIXTURES_DIR, folder ?? '')
48
+ const files = existsSync(dir)
49
+ ? (readdirSync(dir, { recursive: true }) as string[]).filter((f) => f.endsWith('.json')).sort()
50
+ : []
51
+ if (!files.length) {
52
+ this.warn(`No fixtures in ${join(FIXTURES_DIR, folder ?? '')} (record them with cslug ai:record)`)
53
+ return 1
54
+ }
55
+ const agents = await agentClasses(this.app.rootDir)
56
+ const ai = this.app.resolve(Ai)
57
+ const rows: { fixture: string; result: string; details: string; costUsd?: number }[] = []
58
+ for (const file of files) {
59
+ const fixture = readFixture(join(dir, file))
60
+ const name = join(folder ?? '', file.replace(/\.json$/, ''))
61
+ const cls = agents.get(fixture.agent)
62
+ if (!cls) {
63
+ rows.push({ fixture: name, result: 'error', details: `No agent ${fixture.agent} in app/agents` })
64
+ continue
65
+ }
66
+ try {
67
+ const result = await ai.result(this.app.resolve(cls), {
68
+ input: fixture.input,
69
+ context: fixture.context,
70
+ history: fixture.history,
71
+ })
72
+ const diff = jsonDiff(fixture.output, result.raw)
73
+ rows.push({
74
+ fixture: name,
75
+ result: diff.length ? 'diff' : 'same',
76
+ details: diff.join('\n'),
77
+ costUsd: result.costUsd,
78
+ })
79
+ } catch (error) {
80
+ const schema = error instanceof AiOutputError
81
+ rows.push({
82
+ fixture: name,
83
+ result: schema ? 'schema' : 'error',
84
+ details: error instanceof Error ? error.message : String(error),
85
+ })
86
+ }
87
+ }
88
+ const failed = rows.filter((r) => r.result === 'schema' || r.result === 'error' || (strict && r.result === 'diff'))
89
+ const cost = rows.reduce((sum, r) => sum + (r.costUsd ?? 0), 0)
90
+ if (json) this.line(JSON.stringify(rows))
91
+ else {
92
+ this.table(rows.map(({ costUsd: _, ...row }) => row))
93
+ const count = (result: string) => rows.filter((r) => r.result === result).length
94
+ const summary = `${count('same')} same, ${count('diff')} diff, ${count('schema')} schema failures, ${count('error')} errors (~$${cost.toFixed(4)})`
95
+ if (failed.length) this.error(summary)
96
+ else this.success(summary)
97
+ }
98
+ return failed.length ? 1 : 0
99
+ }
100
+ }
@@ -0,0 +1,138 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { arg, Command, flag, Logger, resolve, ServiceProvider, serveMcpStdio } from '@cslug/core'
4
+ import type { HttpContext } from '@cslug/http'
5
+ import { Ai, type AiConfig } from './ai'
6
+ import { AiEvalCommand } from './ai-eval-command'
7
+ import { databaseStore } from './conversation-store'
8
+ import { Conversations } from './conversations'
9
+ import { asMcpTools, discoverTools, handleMcp, type McpCaller, type McpReply, mcpTools } from './mcp'
10
+
11
+ /**
12
+ * `cslug mcp:serve`: the `@mcp()` tools over stdio, for a local client (every exposed tool: the caller is whoever
13
+ * runs the command). Logs go to stderr; stdout carries only MCP messages.
14
+ */
15
+ export class McpServeCommand extends Command {
16
+ static signature = 'mcp:serve'
17
+ static description = 'Serve the @mcp() tools over stdio (HTTP: POST /mcp on the web server)'
18
+
19
+ async handle() {
20
+ this.app.swap(Logger, new Logger({ write: (line) => process.stderr.write(`${line}\n`) }))
21
+ const info = { name: String(this.app.config('app.name') ?? 'cslug'), version: '1' }
22
+ await serveMcpStdio(() => asMcpTools((cls) => resolve(cls), 'local'), info)
23
+ return 0
24
+ }
25
+ }
26
+
27
+ /** `cslug ai:prompts`: the prompt files and the variables each one needs. */
28
+ export class AiPromptsCommand extends Command {
29
+ static signature = 'ai:prompts'
30
+ static description = 'List resources/prompts/*.md and their {{ variables }}'
31
+ static boot = false
32
+ static args = { json: flag.boolean() }
33
+
34
+ handle({ json }: Command.Args<typeof AiPromptsCommand>) {
35
+ const dir = join(this.app.rootDir, 'resources/prompts')
36
+ const rows = existsSync(dir)
37
+ ? (readdirSync(dir, { recursive: true }) as string[])
38
+ .filter((f) => f.endsWith('.md'))
39
+ .sort()
40
+ .map((f) => ({
41
+ prompt: f.replace(/\.md$/, ''),
42
+ variables: [
43
+ ...new Set([...readFileSync(join(dir, f), 'utf8').matchAll(/\{\{\s*([\w.]+)\s*\}\}/g)].map((m) => m[1])),
44
+ ].join(', '),
45
+ }))
46
+ : []
47
+ if (json) this.line(JSON.stringify(rows))
48
+ else if (rows.length) this.table(rows)
49
+ else this.info('No prompts in resources/prompts')
50
+ }
51
+ }
52
+
53
+ /**
54
+ * `cslug ai:record [path]`: `bun test` with `t.ai.fixture()` answered by the real provider; missing fixtures are
55
+ * written (`--all`: every one, re-recorded). Each recorded call costs what the model charges.
56
+ */
57
+ export class AiRecordCommand extends Command {
58
+ static signature = 'ai:record'
59
+ static description = 'Run tests against the real AI provider and write their missing fixtures (calls the API)'
60
+ static boot = false
61
+ static args = {
62
+ path: arg.string().optional().describe('A test file or folder (bun test filter)'),
63
+ all: flag.boolean().describe('Re-record every fixture the tests use'),
64
+ }
65
+
66
+ async handle({ path, all }: Command.Args<typeof AiRecordCommand>) {
67
+ this.warn(`Recording AI fixtures (${all ? 'all' : 'missing'}): the real provider is called`)
68
+ const child = Bun.spawn(['bun', 'test', ...(path ? [path] : [])], {
69
+ cwd: this.app.rootDir,
70
+ env: { ...process.env, CSLUG_AI_RECORD: all ? 'all' : 'missing' },
71
+ stdio: ['inherit', 'inherit', 'inherit'],
72
+ })
73
+ return await child.exited
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Binds `Ai` from `config/ai.ts` (`default`, `providers`, `models`, `mcp`, `budget`, `prices`, `runs`) and
79
+ * `Conversations`; contributes `ai:prompts`, `ai:record`, `ai:eval` and `mcp:serve`. With @cslug/database: the
80
+ * `cslug_ai_*` tables, stored conversations and a record per run.
81
+ * With `@mcp()` tools in `app/tools/` and @cslug/http installed: `POST /mcp` (streamable HTTP, in the api group's
82
+ * middleware, so API tokens authenticate callers).
83
+ */
84
+ export class AiProvider extends ServiceProvider {
85
+ register() {
86
+ this.commands([AiPromptsCommand, AiRecordCommand, AiEvalCommand, McpServeCommand])
87
+ this.app.singleton(
88
+ Ai,
89
+ (c) => new Ai(this.app, this.app.config<AiConfig | undefined>('ai') ?? {}, c.resolve(Logger)),
90
+ )
91
+ this.app.singleton(Conversations, () => new Conversations(this.app))
92
+ }
93
+
94
+ async boot() {
95
+ const store = await databaseStore(this.app)
96
+ if (store) {
97
+ this.app.resolve(Conversations).store = store
98
+ if (this.app.config<boolean | undefined>('ai.runs') !== false) this.app.resolve(Ai).recorder = store.recordRun
99
+ }
100
+ await discoverTools(this.app)
101
+ if (!mcpTools().length) return
102
+ const http = await import('@cslug/http').catch(() => undefined)
103
+ if (!http || !this.app.has(http.Router)) return
104
+ const info = { name: String(this.app.config('app.name') ?? 'cslug'), version: '1' }
105
+ this.app.resolve(http.Router).load(
106
+ (r) => {
107
+ r.post('/mcp', (ctx) => this.mcpHttp(ctx, info)).name('mcp')
108
+ r.get('/mcp', () => new Response(null, { status: 405, headers: { allow: 'POST' } }))
109
+ },
110
+ { middleware: this.app.tagged(http.API_MIDDLEWARE) },
111
+ )
112
+ }
113
+
114
+ /** One MCP message over HTTP: Origin checked (DNS rebinding), notifications 202, JSON responses. */
115
+ private async mcpHttp(ctx: HttpContext, info: { name: string; version: string }): Promise<Response> {
116
+ const origin = ctx.request.header('origin')
117
+ const appUrl = this.app.config<string | undefined>('app.url')
118
+ if (origin && (!appUrl || new URL(origin).origin !== new URL(appUrl).origin))
119
+ return Response.json(
120
+ { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Origin not allowed' } },
121
+ { status: 403 },
122
+ )
123
+ const caller: McpCaller = Reflect.get(ctx, 'auth')
124
+ const reply = await handleMcp(await ctx.request.body(), (cls) => resolve(cls), caller, info).catch(
125
+ (): McpReply => ({
126
+ jsonrpc: '2.0',
127
+ id: null,
128
+ error: { code: -32700, message: 'Parse error' },
129
+ }),
130
+ )
131
+ if (!reply) return new Response(null, { status: 202 })
132
+ return Response.json(reply, { status: reply.error?.code === -32601 ? 404 : 200 })
133
+ }
134
+
135
+ async shutdown() {
136
+ await this.app.resolve(Ai).close()
137
+ }
138
+ }