@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.
- package/README.md +5 -2
- package/docs/README.md +182 -3
- package/docs/api.md +44 -0
- package/migrations/00000000_000500_cslug_ai.sql +48 -0
- package/package.json +24 -5
- package/src/agent.ts +168 -0
- package/src/ai-eval-command.ts +100 -0
- package/src/ai-provider.ts +187 -0
- package/src/ai-stream.ts +31 -0
- package/src/ai.ts +329 -0
- package/src/budget.ts +103 -0
- package/src/conversation-store.ts +79 -0
- package/src/conversations.ts +251 -0
- package/src/drivers.ts +249 -0
- package/src/embedders.ts +133 -0
- package/src/fake.ts +165 -0
- package/src/index.ts +88 -4
- package/src/mcp-client.ts +154 -0
- package/src/mcp.ts +75 -0
- package/src/model.ts +111 -0
- package/src/search-tools.ts +163 -0
- package/src/sse.ts +35 -0
package/README.md
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
# @cslug/ai
|
|
2
2
|
|
|
3
|
-
Agents
|
|
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
|
-
|
|
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,185 @@
|
|
|
1
1
|
# @cslug/ai
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
6
|
-
|
|
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, `prompt('name')`, or a function of the context), `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: a function is called with `context` (and awaited); a prompt file is filled from it,
|
|
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
|
+
## Prompts
|
|
66
|
+
|
|
67
|
+
`prompt('trips/brief')` reads `resources/prompts/trips/brief.md` on every run and fills it with `fillPrompt`:
|
|
68
|
+
|
|
69
|
+
| In the file | Gives |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `{{ name }}` | `context.name`: a string as is, a number or boolean as text, a `Date` as ISO, an object or a list as indented JSON (bigint as text) |
|
|
72
|
+
| `{{ trip.circuit.name }}` | A nested value (each step must be an object) |
|
|
73
|
+
| `{{ language \| English }}` | The value, or `English` when it is missing or null (`{{ note \| }}`: empty) |
|
|
74
|
+
|
|
75
|
+
A missing value without a default throws `ai.prompt_variables` listing every one; a present `null` without a
|
|
76
|
+
default renders empty. `cslug ai:prompts` lists each file and its variables, with `?` after those that have a
|
|
77
|
+
default. `PROMPT_VARIABLE` is the pattern (path, default); `renderInstructions(instructions, context)` gives the
|
|
78
|
+
system prompt for any `Instructions`.
|
|
79
|
+
|
|
80
|
+
## Providers
|
|
81
|
+
|
|
82
|
+
| Driver | Config | |
|
|
83
|
+
|---|---|---|
|
|
84
|
+
| `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`) |
|
|
85
|
+
| `openai-compatible` | `baseUrl`, `apiKey` | Chat completions (Ollama, vLLM, LM Studio…): function tools, `response_format` JSON Schema, streaming |
|
|
86
|
+
|
|
87
|
+
Without `config/ai.ts`, the default provider is `anthropic`. `ai.extend(name, provider)` adds one (any object with
|
|
88
|
+
`complete` and `stream`).
|
|
89
|
+
|
|
90
|
+
`ai.result(agent, { input, context })` is `run()` in detail: `{ value, raw, model, steps, usage, costUsd }` (`raw` is
|
|
91
|
+
the answer before validation: the parsed JSON, or the text).
|
|
92
|
+
|
|
93
|
+
## Search tools (with @cslug/search)
|
|
94
|
+
|
|
95
|
+
`tools` accepts tool objects besides classes and MCP tools.
|
|
96
|
+
|
|
97
|
+
- `searchTool(index, { name = 'search_<index>', description, perPage = 5, filter, words = 40 })`: input
|
|
98
|
+
`{ query, page? }`; result `{ results: [{ key, title, snippet, metadata }], total, page, lastPage }`, snippets as
|
|
99
|
+
plain text (marks removed, entities decoded). `index` is any `searchIndex()` (typed structurally as
|
|
100
|
+
`SearchableIndex`).
|
|
101
|
+
- `ai.recall: true` (or `{ index }`): each stored turn's text messages (user and assistant, not tool rounds) are
|
|
102
|
+
upserted into a search index, `ai-conversations` by default, semantic when an `Embedder` is bound, keyed
|
|
103
|
+
`<conversation>:<position>` with `{ ownerType, ownerId, conversationId, role }` metadata. Unowned conversations
|
|
104
|
+
are not kept. A failure to index is logged (`ai.recall_failed`), never thrown into the turn. `chat.delete()`
|
|
105
|
+
removes its entries.
|
|
106
|
+
- `recallTool({ perPage = 5 })`: `{ query }` → `{ results: [{ conversationId, role, text }] }`, searched within the
|
|
107
|
+
current conversation's owner (from the ambient context `Conversation.send` / `stream` set: `currentConversation()`),
|
|
108
|
+
the current conversation left out. Outside a stored conversation it answers that there is nothing to search.
|
|
109
|
+
|
|
110
|
+
## Embeddings (for @cslug/search)
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
embeddings: { driver: 'voyage', model: 'voyage-3.5' }, // VOYAGE_API_KEY
|
|
114
|
+
embeddings: { driver: 'openai-compatible', baseUrl: 'https://api.openai.com/v1', apiKey: env.OPENAI_API_KEY,
|
|
115
|
+
model: 'text-embedding-3-small', dimensions: 512 },
|
|
116
|
+
embeddings: { driver: 'openai-compatible', baseUrl: 'http://localhost:11434/v1', model: 'nomic-embed-text' }, // Ollama
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
With `ai.embeddings` and `@cslug/search` installed, `AiProvider` binds search's `Embedder` (semantic indexes use it).
|
|
120
|
+
Anthropic has no embeddings API; Voyage is the provider it recommends.
|
|
121
|
+
|
|
122
|
+
- `voyage`: `POST {baseUrl}/embeddings` with `input_type` (`document` for indexed texts, `query` for searches) and
|
|
123
|
+
`output_dimension` from `dimensions`.
|
|
124
|
+
- `openai-compatible`: `POST {baseUrl}/embeddings` `{ model, input, dimensions? }`.
|
|
125
|
+
- The vectors' `model` includes the dimensions (`voyage-3.5@512`), so changing either re-embeds documents.
|
|
126
|
+
- Calls are checked against and charged to the daily budget, as input tokens of `model`. There are no built-in
|
|
127
|
+
prices for embedding models: add yours to `ai.prices` (`{ 'voyage-3.5': { input: <USD per million>, output: 0 } }`),
|
|
128
|
+
otherwise the calls are logged once as unpriced and cost nothing in the budget.
|
|
129
|
+
- `testApp({ fakes: ['ai'] })` also swaps the bound `Embedder` for a `FakeEmbedder`, so a test never calls the
|
|
130
|
+
provider.
|
|
131
|
+
|
|
132
|
+
## Daily budget
|
|
133
|
+
|
|
134
|
+
```ts
|
|
135
|
+
budget: { perDay: { usd: 10 }, alertAt: 0.8 }, // config/ai.ts
|
|
136
|
+
prices: { 'llama3.3': { input: 0, output: 0 } }, // USD per million tokens, for models the built-in table lacks
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Each model call is charged after it answers, at the model's price (`MODEL_PRICES`: Anthropic's first-party prices;
|
|
140
|
+
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
|
|
141
|
+
`AiBudgetError`: nothing is called until the next day in the app's time zone. When the spend crosses `alertAt` (0.8)
|
|
142
|
+
of the limit, `AiBudgetAlert` (`ai.budget_alert`: `{ day, spentUsd, limitUsd }`) is emitted once and logged. The spend
|
|
143
|
+
is kept in the app's `Cache` (`ai:spend:<day>`), so with @cslug/redis every process shares it; with the in-memory
|
|
144
|
+
cache each process counts its own. A model without a price costs nothing and is logged once (`ai.budget_unpriced`).
|
|
145
|
+
The figures are estimates from the token counts, not the provider's bill.
|
|
146
|
+
|
|
147
|
+
## Tests
|
|
148
|
+
|
|
149
|
+
`testApp({ fakes: ['ai'] })` → `t.ai`: no provider is called. `respond(Agent, output | (run) => output)` gives an
|
|
150
|
+
agent its answer (checked against its `output` schema); `assertRan(Agent, where?)`, `assertNotRan(Agent)`,
|
|
151
|
+
`ran(Agent)`, `runs`.
|
|
152
|
+
|
|
153
|
+
**Recorded fixtures.** `t.ai.fixture(Agent, 'proposals/isalo')` answers with `tests/fixtures/ai/proposals/isalo.json`
|
|
154
|
+
(validated like `respond`). A missing file is an error that names the command to run:
|
|
155
|
+
|
|
156
|
+
- `cslug ai:record [path]` runs `bun test [path]` with `CSLUG_AI_RECORD=missing`: a `fixture()` whose file is
|
|
157
|
+
missing calls the real provider (config `ai`) and writes `{ agent, input, context, output, model, recordedAt }`,
|
|
158
|
+
`output` being the raw answer. `--all` re-records every fixture the tests reach. Commit the files.
|
|
159
|
+
- `cslug ai:eval [folder]` runs every fixture under `tests/fixtures/ai/[folder]` through the real model, with the
|
|
160
|
+
agent class found by name in `app/agents/`: `same`, `diff` (the changed paths), `schema` (an `AiOutputError`) or
|
|
161
|
+
`error`, plus the estimated cost. Schema failures and errors exit 1; diffs only with `--strict`. `--json` prints
|
|
162
|
+
the rows.
|
|
163
|
+
|
|
164
|
+
Both call the provider and cost money (and count against the daily budget).
|
|
165
|
+
|
|
166
|
+
## MCP
|
|
167
|
+
|
|
168
|
+
**Serving.** `@mcp(options)` on a `Tool` class in `app/tools/` (imported at boot) exposes it:
|
|
169
|
+
|
|
170
|
+
- `POST /mcp` (when @cslug/http is installed and a tool is exposed): streamable HTTP with JSON responses, `202` for
|
|
171
|
+
notifications, `404` for an unknown method, `405` for GET, `403` when `Origin` is not `app.url`'s. It runs the api
|
|
172
|
+
group's middleware, so `ctx.auth` (from @cslug/auth) is the caller. Options: none → any authenticated caller;
|
|
173
|
+
`public: true` → anyone; `guard: 'token'` → that guard; `ability: 'mcp:x'` → a token with that ability (session
|
|
174
|
+
users pass). A tool the caller may not use is not listed and is "unknown" when called.
|
|
175
|
+
- `cslug mcp:serve`: stdio (newline-delimited JSON-RPC on stdout, logs on stderr); every exposed tool.
|
|
176
|
+
|
|
177
|
+
Protocol: `server/discover` and per-request versions (2026-07-28), and `initialize` for 2025-11-25, 2025-06-18 and
|
|
178
|
+
2025-03-26 (the client's version if supported, else 2025-11-25). `tools/list`, `tools/call` (input validated; a
|
|
179
|
+
plain-object result is also `structuredContent`; an error is `isError: true`), `ping`. An unsupported
|
|
180
|
+
`_meta["io.modelcontextprotocol/protocolVersion"]` is error `-32022`.
|
|
181
|
+
|
|
182
|
+
**Using a server.** `config/ai.ts` → `mcp.<name>`: `{ url, headers? }` or `{ command, env? }` (stdio, started on first
|
|
183
|
+
use, stopped at shutdown). In an agent: `tools = [...mcp('maps').tools(['route_duration'])]` (all tools without a
|
|
184
|
+
list). The client tries `server/discover` (2026-07-28), else `initialize` (2025-11-25), keeps `Mcp-Session-Id` for
|
|
185
|
+
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,44 @@
|
|
|
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
|
+
| `fillPrompt(template, vars, name?)` | `{{ path }}` (nested, objects as JSON), `{{ path \| default }}`; `PROMPT_VARIABLE` |
|
|
11
|
+
| `Instructions`, `renderInstructions(instructions, context)` | `string \| Prompt \| (context) => string \| Prompt` (or a promise of one); the system prompt for a run |
|
|
12
|
+
| `Ai` | Injectable runtime: `run(agent, options)`, `result(agent, options, meta?)` → `AiResult`, `stream(agent, options, meta?)`, `provider(name?)`, `extend(name, provider)`, `budget`, `recorder` |
|
|
13
|
+
| `AiResult` | `{ runId, value, raw, model, steps, usage, costUsd, messages }` |
|
|
14
|
+
| `Conversations` | `start(Agent, options)`, `find(Agent, id, options)`, `list(options)`; `store` (set with @cslug/database) |
|
|
15
|
+
| `Conversation` | `id`, `agent`, `title`, `metadata`, `owner`, `createdAt`; `send(input)`, `stream(input)`, `messages()`, `update(changes)`, `delete()` |
|
|
16
|
+
| `ConversationStore`, `ConversationRow`, `OwnerRef`, `StartOptions`, `FindOptions` | The store contract and shapes |
|
|
17
|
+
| `RunRecord`, `RunMeta` | A `cslug_ai_runs` row; `ai.result(agent, options, meta)`'s third argument (`conversationId`, `compact`) |
|
|
18
|
+
| `AI_MIGRATIONS` | The migrations folder (registered at boot with @cslug/database) |
|
|
19
|
+
| `AiProvider` | Config `ai`: `default`, `providers.<name>`, `models`, `mcp`, `budget`, `prices`, `runs`; binds `Conversations`; commands `ai:prompts`, `ai:record`, `ai:eval`, `mcp:serve` |
|
|
20
|
+
| `AiRecordCommand` | `cslug ai:record [path] [--all]`: `bun test` with `CSLUG_AI_RECORD` set, writing missing (all) fixtures |
|
|
21
|
+
| `AiEvalCommand` | `cslug ai:eval [folder] [--strict] [--json]`: fixtures through the real model; `jsonDiff(a, b)` |
|
|
22
|
+
| `Budget` | The daily budget: `spent()`, `check()`, `charge(model, usage)`; `BudgetConfig` `{ perDay: { usd }, alertAt? }` |
|
|
23
|
+
| `costOf(model, usage, prices?)`, `MODEL_PRICES`, `ModelPrice` | Estimated USD cost of a call (`undefined` without a price) |
|
|
24
|
+
| `AiBudgetError` | The day's budget is spent (`spentUsd`, `limitUsd`) |
|
|
25
|
+
| `AiBudgetAlert` | Event `ai.budget_alert` `{ day, spentUsd, limitUsd }`, once a day at `alertAt` |
|
|
26
|
+
| `AnthropicProvider`, `OpenAiCompatibleProvider` | The drivers; `Provider` is `{ complete(request), stream(request) }` |
|
|
27
|
+
| `ModelRequest`, `ModelResponse`, `Block`, `Message`, `StreamEvent`, `Usage` | The neutral request and response shapes (`Usage`: input, output, cache read and cache write tokens) |
|
|
28
|
+
| `modelSchema(jsonSchema)` | A JSON Schema as structured output accepts it |
|
|
29
|
+
| `sse(textStream)` | A `Responsable` streaming server-sent events |
|
|
30
|
+
| `AiOutputError` | The answer is not JSON or breaks the `output` schema (`text`, `issues`) |
|
|
31
|
+
| `AiRefusalError` | The model declined (`category`) |
|
|
32
|
+
| `mcp(options?)` | Decorator: expose a `Tool` over MCP (`public`, `guard`, `ability`) |
|
|
33
|
+
| `mcp(server).tools(names?)` | An MCP server's tools for an agent's `tools` |
|
|
34
|
+
| `McpConnection(name, config)` | A client: `request(method, params)`, `close()` |
|
|
35
|
+
| `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()` |
|
|
36
|
+
| `McpServeCommand` | `cslug mcp:serve` (stdio) |
|
|
37
|
+
| `AiFake`, `installAiFake(app)` | `fakes: ['ai']`: `respond`, `fixture(Agent, name)`, `assertRan`, `assertNotRan`, `ran`, `runs` |
|
|
38
|
+
| `searchTool(index, options?)`, `SearchToolOptions`, `SearchableIndex` | A tool object searching a `@cslug/search` index |
|
|
39
|
+
| `recallTool(options?)` | Search the current conversation owner's earlier conversations (`ai.recall`) |
|
|
40
|
+
| `currentConversation()`, `CONVERSATION_KEY`, `ConversationScope` | The conversation a run belongs to (`{ id, owner }`), in the ambient context |
|
|
41
|
+
| `EmbeddingsConfig`, `embedderFor(config, budget?)` | `config/ai.ts` → `embeddings`: `{ driver: 'voyage' \| 'openai-compatible', model, dimensions?, apiKey?, baseUrl? }`; the embedder for it |
|
|
42
|
+
| `VoyageEmbedder`, `OpenAiCompatibleEmbedder`, `TextEmbedder` | The drivers (`model`, `embed(texts, purpose)`), charged to the budget |
|
|
43
|
+
| `setFakeEmbedder(token, create)` | Set by `AiProvider`: what `installAiFake` swaps the bound `Embedder` for |
|
|
44
|
+
| `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
|
-
"description": "Agents
|
|
3
|
+
"version": "0.6.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,31 @@
|
|
|
28
29
|
"bun": ">=1.3.14"
|
|
29
30
|
},
|
|
30
31
|
"peerDependencies": {
|
|
31
|
-
"@cslug/core": "0.
|
|
32
|
-
"@cslug/validation": "0.
|
|
33
|
-
"@cslug/queue": "0.
|
|
32
|
+
"@cslug/core": "0.6.0",
|
|
33
|
+
"@cslug/validation": "0.6.0",
|
|
34
|
+
"@cslug/queue": "0.6.0",
|
|
35
|
+
"@cslug/http": "0.6.0",
|
|
36
|
+
"@cslug/database": "0.6.0",
|
|
37
|
+
"@cslug/search": "0.6.0"
|
|
34
38
|
},
|
|
35
39
|
"peerDependenciesMeta": {
|
|
36
40
|
"@cslug/queue": {
|
|
37
41
|
"optional": true
|
|
42
|
+
},
|
|
43
|
+
"@cslug/http": {
|
|
44
|
+
"optional": true
|
|
45
|
+
},
|
|
46
|
+
"@cslug/database": {
|
|
47
|
+
"optional": true
|
|
48
|
+
},
|
|
49
|
+
"@cslug/search": {
|
|
50
|
+
"optional": true
|
|
38
51
|
}
|
|
52
|
+
},
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@cslug/testing": "workspace:*",
|
|
55
|
+
"@cslug/http": "workspace:*",
|
|
56
|
+
"@cslug/database": "workspace:*",
|
|
57
|
+
"@cslug/search": "workspace:*"
|
|
39
58
|
}
|
|
40
59
|
}
|
package/src/agent.ts
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
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
|
+
/** `{{ path }}` or `{{ path | default }}`: a dotted path into the context, and an optional fallback text. */
|
|
12
|
+
export const PROMPT_VARIABLE = /\{\{\s*([\w]+(?:\.[\w]+)*)\s*(?:\|\s*([^}]*?)\s*)?\}\}/g
|
|
13
|
+
|
|
14
|
+
const lookup = (vars: Record<string, unknown>, path: string): { found: boolean; value: unknown } => {
|
|
15
|
+
let value: unknown = vars
|
|
16
|
+
for (const key of path.split('.')) {
|
|
17
|
+
if (value === null || typeof value !== 'object' || !(key in value)) return { found: false, value: undefined }
|
|
18
|
+
value = (value as Record<string, unknown>)[key]
|
|
19
|
+
}
|
|
20
|
+
return { found: true, value }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const asText = (value: unknown): string =>
|
|
24
|
+
typeof value === 'string'
|
|
25
|
+
? value
|
|
26
|
+
: value !== null && typeof value === 'object' && !(value instanceof Date)
|
|
27
|
+
? JSON.stringify(value, (_k, x) => (typeof x === 'bigint' ? x.toString() : x), 2)
|
|
28
|
+
: String(value instanceof Date ? value.toISOString() : value)
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Fill a prompt template: `{{ trip.circuit }}` reads a nested value, an object or a list is written as JSON,
|
|
32
|
+
* `{{ language | English }}` falls back when the value is missing or null. A missing value without a default is
|
|
33
|
+
* an `ai.prompt_variables` error naming every one.
|
|
34
|
+
*/
|
|
35
|
+
export function fillPrompt(template: string, vars: Record<string, unknown>, name = 'prompt'): string {
|
|
36
|
+
const missing = new Set<string>()
|
|
37
|
+
const text = template.replace(PROMPT_VARIABLE, (_m, path: string, fallback: string | undefined) => {
|
|
38
|
+
const { found, value } = lookup(vars, path)
|
|
39
|
+
if (found && value !== null && value !== undefined) return asText(value)
|
|
40
|
+
if (fallback !== undefined) return fallback
|
|
41
|
+
if (!found) missing.add(path)
|
|
42
|
+
return ''
|
|
43
|
+
})
|
|
44
|
+
if (missing.size)
|
|
45
|
+
throw new CslugError('ai.prompt_variables', `Prompt ${name} needs ${[...missing].join(', ')} in context`)
|
|
46
|
+
return text
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A prompt file, `resources/prompts/<name>.md`, with `{{ variables }}` filled from the run's `context`. */
|
|
50
|
+
export class Prompt {
|
|
51
|
+
constructor(readonly name: string) {}
|
|
52
|
+
|
|
53
|
+
get path(): string {
|
|
54
|
+
return join(currentApp().rootDir, 'resources/prompts', `${this.name}.md`)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
render(vars: Record<string, unknown> = {}): string {
|
|
58
|
+
if (!existsSync(this.path)) throw new CslugError('ai.no_prompt', `No prompt file resources/prompts/${this.name}.md`)
|
|
59
|
+
return fillPrompt(readFileSync(this.path, 'utf8'), vars, this.name)
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What an agent's `instructions` may be. */
|
|
64
|
+
export type Instructions =
|
|
65
|
+
| string
|
|
66
|
+
| Prompt
|
|
67
|
+
| ((context: Record<string, unknown>) => string | Prompt | Promise<string | Prompt>)
|
|
68
|
+
|
|
69
|
+
/** The system prompt for a run: a function is called with the context, a `Prompt` is filled from it. */
|
|
70
|
+
export async function renderInstructions(
|
|
71
|
+
instructions: Instructions | undefined,
|
|
72
|
+
context: Record<string, unknown>,
|
|
73
|
+
): Promise<string> {
|
|
74
|
+
const value = typeof instructions === 'function' ? await instructions(context) : (instructions ?? '')
|
|
75
|
+
return typeof value === 'string' ? value : value.render(context)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** `instructions = prompt('proposals/extract-offer')` → `resources/prompts/proposals/extract-offer.md`. */
|
|
79
|
+
export const prompt = (name: string) => new Prompt(name)
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Something an agent can call: an `@inject()` class with a name, a description, an input schema and `handle(input)`.
|
|
83
|
+
* The input is validated before `handle` runs; a validation failure or a thrown error goes back to the model as an
|
|
84
|
+
* error result, so it can correct itself.
|
|
85
|
+
*/
|
|
86
|
+
export abstract class Tool {
|
|
87
|
+
abstract name: string
|
|
88
|
+
abstract description: string
|
|
89
|
+
abstract input: Schema<unknown>
|
|
90
|
+
abstract handle(input: never): unknown
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** What a run calls: a `Tool`, or an MCP server's tool (its input is checked by that server). */
|
|
94
|
+
export type RunnableTool = {
|
|
95
|
+
name: string
|
|
96
|
+
description: string
|
|
97
|
+
input: Pick<Schema<unknown>, 'toJSONSchema' | 'safeParse'>
|
|
98
|
+
handle(input: never): unknown
|
|
99
|
+
}
|
|
100
|
+
export type ToolClass = Class<Tool>
|
|
101
|
+
|
|
102
|
+
export type RunOptions = {
|
|
103
|
+
input: string
|
|
104
|
+
context?: Record<string, unknown>
|
|
105
|
+
/**
|
|
106
|
+
* The conversation so far: a previous result's `messages`, unchanged. The run continues it (append-only, so the
|
|
107
|
+
* provider's prompt cache keeps the earlier turns).
|
|
108
|
+
*/
|
|
109
|
+
history?: Message[]
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* What an agent may declare besides `model`. These are deliberately not declared on `Agent` (as for jobs), so apps
|
|
114
|
+
* compiled with `noImplicitOverride` write `instructions = …` without `override`.
|
|
115
|
+
*/
|
|
116
|
+
export type AgentSettings = {
|
|
117
|
+
/** A model ID (`claude-opus-5-5`), or a role from config `ai.models` (`fast`, `smart`). */
|
|
118
|
+
model: string
|
|
119
|
+
/**
|
|
120
|
+
* A string, `prompt('name')` (a file with `{{ variables }}`), or a function of the run's `context` returning
|
|
121
|
+
* either (it may be async), for instructions built in code.
|
|
122
|
+
*/
|
|
123
|
+
instructions?: Instructions
|
|
124
|
+
/** Structured output: the answer is parsed and validated (`AiOutputError` otherwise). */
|
|
125
|
+
output?: Schema<unknown>
|
|
126
|
+
/**
|
|
127
|
+
* Tool classes, MCP servers' tools and tool objects: `tools = [FindOperatorsTool,
|
|
128
|
+
* ...mcp('maps').tools(['route_duration']), searchTool(helpIndex), recallTool()]`.
|
|
129
|
+
*/
|
|
130
|
+
tools?: (ToolClass | McpTools | RunnableTool)[]
|
|
131
|
+
/** Model calls before giving up (each tool round is one); default 8. */
|
|
132
|
+
maxSteps?: number
|
|
133
|
+
/** A provider from config `ai.providers` (default: `ai.default`). */
|
|
134
|
+
provider?: string
|
|
135
|
+
effort?: Effort
|
|
136
|
+
maxTokens?: number
|
|
137
|
+
/**
|
|
138
|
+
* Let the provider summarise a long history server-side (Anthropic compaction, at about 150K input tokens, on the
|
|
139
|
+
* models that support it). On by default in a `Conversation`; `false` turns it off there.
|
|
140
|
+
*/
|
|
141
|
+
compact?: boolean
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** What `run()` returns: the `output` schema's type, or the text. */
|
|
145
|
+
export type AgentOutput<A> = A extends { output: Schema<infer O> } ? O : string
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* An AI task as a class: a model, instructions, optional tools and an optional `output` schema
|
|
149
|
+
* ({@link AgentSettings}). `run()` returns the result; `stream()` yields the text as it arrives. Pass a previous
|
|
150
|
+
* result's `messages` as `history` to continue a conversation.
|
|
151
|
+
*/
|
|
152
|
+
export abstract class Agent {
|
|
153
|
+
abstract model: string
|
|
154
|
+
|
|
155
|
+
run(options: RunOptions): Promise<AgentOutput<this>> {
|
|
156
|
+
return resolve(Ai).run(this, options) as Promise<AgentOutput<this>>
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The run in detail: the value, the raw answer, `messages` (the conversation to pass as `history` next turn), usage, cost. */
|
|
160
|
+
result(options: RunOptions): Promise<AiResult<AgentOutput<this>>> {
|
|
161
|
+
return resolve(Ai).result(this, options) as Promise<AiResult<AgentOutput<this>>>
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The text as it arrives; `.result` gives the finished run once it has been read. */
|
|
165
|
+
stream(options: RunOptions): AiStream<AgentOutput<this>> {
|
|
166
|
+
return resolve(Ai).stream(this, options) as AiStream<AgentOutput<this>>
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -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
|
+
}
|