@kerf-js/agent 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ravonus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,64 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="https://github.com/Ravonus/kerf">
3
+ <img src="https://raw.githubusercontent.com/Ravonus/kerf/main/site/public/logo.svg" width="88" height="88" alt="Kerf">
4
+ </a>
5
+ </p>
2
6
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
7
+ <h1 align="center">@kerf-js/agent</h1>
8
+
9
+ <p align="center">
10
+ <strong>An assistant that runs your Kerf app: your server functions are its tools, and grants decide what it may do.</strong><br>
11
+ Conversations, usage, tokens for outside agents over MCP, and bridges to the Rust bridge daemon, Claude, the Claude CLI or your own planner.
12
+ </p>
13
+
14
+ <p align="center">
15
+ <a href="https://www.npmjs.com/package/@kerf-js/agent"><img src="https://img.shields.io/npm/v/@kerf-js/agent?color=145c3c&label=npm" alt="npm version"></a>
16
+ <a href="https://github.com/Ravonus/kerf/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-MIT-145c3c" alt="MIT license"></a>
17
+ </p>
18
+
19
+ > [!IMPORTANT]
20
+ > **Early release (0.1.x).** APIs can change between minor versions. Pin the version and read the
21
+ > [changelog](https://github.com/Ravonus/kerf/blob/main/CHANGELOG.md) before you upgrade.
22
+
23
+ ## Quick start
24
+
25
+ ```bash
26
+ kerf add agent
27
+ ```
28
+
29
+ It writes `src/agent.server.ts`, `src/server/agent.ts` and `src/db/agent.schema.ts`. Then mark the functions the
30
+ assistant may use:
31
+
32
+ <!-- example: skip fragments of a server module -->
33
+
34
+ ```ts
35
+ export const setPrice = mutation({
36
+ auth: { role: 'owner' },
37
+ input: z.object({ item: z.string(), cents: z.int().min(0) }),
38
+ invalidates: ['menu'],
39
+ agent: { say: 'Change an item price', confirm: true },
40
+ run: ({ input }) => updatePrice(input),
41
+ })
42
+ ```
43
+
44
+ That's a tool named `setPrice` needing `menu.write`, held for the owner's approval on each call.
45
+
46
+ ## What it does
47
+
48
+ - **Tools from your functions.** Any query or mutation with `agent:` is a tool, typed by its input schema. Nothing
49
+ else is.
50
+ - **Grants.** `roles: { owner: ['*'], staff: ['orders.*', 'menu.read'] }`. A call runs as the person asking, through
51
+ the function's own `auth`, and must also be granted.
52
+ - **Conversations.** Start, rename, pin, archive, delete. Replies stream to the page; held calls wait for approval.
53
+ - **Usage.** Input and output tokens per step, by bridge and model, and calls per token.
54
+ - **MCP.** `/_kerf/x/agent/mcp` serves the same tools to Claude Code, Codex or a script, with a token that never
55
+ grants more than its creator holds.
56
+ - **Bridges.** `rustBridge()` (the Technomancy AI Bridge daemon and its signed-in CLIs), `anthropic()` (the API
57
+ with native tool use), `claudeCli()` (the local CLI, which calls tools over MCP), `fnBridge({ fn })` (any server
58
+ function) and `fakeBridge()` for tests. `AGENT_BRIDGE=<id>` picks the default; each conversation can swap.
59
+
60
+ Read the guide with `kerf docs agent`, or in [`docs/agent.md`](./docs/agent.md).
61
+
62
+ ## License
63
+
64
+ MIT
package/docs/agent.md ADDED
@@ -0,0 +1,187 @@
1
+ # Agent
2
+
3
+ This is a plugin, `@kerf-js/agent`, and nothing in kerf names it. It gives an app an assistant that runs the site:
4
+ conversations you can rename, pin, archive and delete, tools that are your own server functions, grants per role and per
5
+ token, usage per conversation and token, and bridges to Claude, the local Claude CLI or your own planner.
6
+
7
+ `kerf add agent` needs auth and a database. It writes:
8
+
9
+ - `src/agent.server.ts`: `defineAgent({ store, bridges, system, roles, user })`, which turns the extension on;
10
+ - `src/server/agent.ts`: the app's own queries, mutations and stream for conversations, turns, usage and tokens;
11
+ - `src/db/agent.schema.ts`: five tables, re-exported from `src/db/schema.ts`.
12
+
13
+ ## Tools are functions that opt in
14
+
15
+ A query or mutation becomes a tool by saying so beside `auth`:
16
+
17
+ <!-- example: skip fragments of a server module -->
18
+
19
+ ```ts
20
+ export const menu = query({
21
+ auth: 'user',
22
+ tags: ['menu'],
23
+ agent: { say: 'The menu with prices in cents' },
24
+ run: () => listMenu(),
25
+ })
26
+
27
+ export const setPrice = mutation({
28
+ auth: { role: 'owner' },
29
+ input: z.object({ item: z.string(), cents: z.int().min(0) }),
30
+ invalidates: ['menu'],
31
+ agent: { say: 'Change an item price', confirm: true },
32
+ run: ({ input }) => updatePrice(input),
33
+ })
34
+ ```
35
+
36
+ - The tool's name is the export name, its description is `say`, and its input is the function's input schema.
37
+ - Its permission is `<scope>.read` for a query and `<scope>.write` for a mutation. The scope is `agent.scope`, else the
38
+ first tag (query) or `invalidates` entry (mutation), else the export name. Above: `menu.read` and `menu.write`.
39
+ - `confirm: true` holds each call until the owner approves or declines it in the conversation.
40
+ - `agent: true` opts in with the defaults.
41
+
42
+ A function without `agent:` is never a tool, and an agent can't reach it by any route (AGENT008).
43
+
44
+ ## Grants
45
+
46
+ `roles` maps each role to what it may let the agent do:
47
+
48
+ <!-- example: skip needs what `kerf add agent` writes -->
49
+
50
+ ```ts
51
+ export default defineAgent({
52
+ store,
53
+ bridges: [anthropic(), claudeCli()],
54
+ system: 'You run the shop for its owner.',
55
+ roles: { owner: ['*'], staff: ['orders.*', 'menu.read'] },
56
+ // the user a token acts as
57
+ user: (id) => findUser(id),
58
+ })
59
+ ```
60
+
61
+ - `*` is everything; `orders.*` or `orders` is every `orders` permission; `menu.write` covers `menu.read`.
62
+ - Without `roles`, every signed-in user grants `*`.
63
+ - Grants never widen `auth`: a tool call runs as the signed-in person, through the function's own `auth`, and then must
64
+ also be granted. Staff with `*` still can't run an owner-only function.
65
+ - Only the outermost call is checked. What a tool calls in turn is the tool's own business.
66
+
67
+ ## Conversations and turns
68
+
69
+ `send` saves what the person said and runs a turn: the bridge writes, asks for tools, gets their results and writes
70
+ again, until it is done, a call waits for the owner, or it runs out of `steps` (default 8). The reply is saved as one
71
+ message with its text, calls and results. The scaffolded `turn` stream carries it to the page as it is written.
72
+
73
+ `resolveCall({ conversation, call, approve })` answers a held call. The agent hears the result and goes on.
74
+
75
+ ## Bridges
76
+
77
+ | Bridge | Import | Runs tools | Available when |
78
+ | ------------------- | -------------------------- | ------------------ | -------------------------- |
79
+ | `rustBridge()` | `@kerf-js/agent/rust` | the loop runs them | the daemon polled in 90s |
80
+ | `anthropic()` | `@kerf-js/agent/anthropic` | the loop runs them | `ANTHROPIC_API_KEY` is set |
81
+ | `claudeCli()` | `@kerf-js/agent/cli` | itself, over MCP | `claude` is on PATH |
82
+ | `fnBridge({ fn })` | `@kerf-js/agent/fn` | the loop runs them | always |
83
+ | `fakeBridge(lines)` | `@kerf-js/agent/test` | either | always |
84
+
85
+ A new conversation takes `AGENT_BRIDGE` (a bridge id) when that one can answer, else the first in `bridges` that can.
86
+ Each conversation keeps its own and can swap at any time with `update({ bridge })`; when its bridge goes away (the
87
+ daemon stops, the key is removed) it answers with the next one that can. So switching the whole app from the bridge to
88
+ the API is one variable: `AGENT_BRIDGE=claude`, or back with `AGENT_BRIDGE=rust`.
89
+
90
+ ### The Rust bridge
91
+
92
+ `rustBridge()` sends each step to the Technomancy AI Bridge daemon, which runs it through the `claude` and `codex` CLIs
93
+ signed in on its own machine and meters and caps the spend per site and per person. The app holds the job queue; the
94
+ daemon long-polls it from outside, so the app can be deployed anywhere and the daemon's machine never listens publicly.
95
+
96
+ 1. `technomancy-bridge token` makes a token. Set it as `AGENT_BRIDGE_TOKEN` on the app.
97
+ 2. Add the app to the daemon's `bridge.toml`:
98
+
99
+ ```toml
100
+ [[server]]
101
+ name = "shop"
102
+ url = "https://shop.example"
103
+ token = "<the same token>"
104
+ queues = ["/_kerf/x/agent/bridges/rust/jobs"]
105
+ ```
106
+
107
+ The picker offers it while the daemon polls. `model` picks the daemon's route: `claude` (the default) is Claude first,
108
+ `terra`, `sol` or `luna` is Codex first. Its usage rows carry the tokens the daemon reports.
109
+
110
+ ### Your own function
111
+
112
+ `fnBridge` turns any server function that takes `bridgeInput` and returns `bridgeOutput` into a bridge: a rules engine,
113
+ a local model, or a Rust sidecar with `impl: remote('rust://planner')`, which gets serde types for both:
114
+
115
+ <!-- example: skip fragments of a server module -->
116
+
117
+ ```ts
118
+ import { bridgeInput, bridgeOutput } from '@kerf-js/agent/fn'
119
+ import { fnBridge } from '@kerf-js/agent/fn'
120
+
121
+ export const planner = mutation({
122
+ input: bridgeInput,
123
+ output: bridgeOutput,
124
+ impl: remote('rust://planner'),
125
+ })
126
+
127
+ // src/agent.server.ts
128
+ const house = fnBridge({ fn: planner, label: 'House rules' })
129
+ defineAgent({ bridges: [rustBridge(), anthropic(), house], … })
130
+ ```
131
+
132
+ ## Outside agents: MCP and tokens
133
+
134
+ The app is an MCP server at `/_kerf/x/agent/mcp` (Streamable HTTP, JSON answers). `createToken({ name, grants })`
135
+ returns a secret once. Give it to Claude Code, Codex or a script as `Authorization: Bearer <secret>`:
136
+
137
+ ```bash
138
+ claude mcp add --transport http shop \
139
+ https://example.com/_kerf/x/agent/mcp \
140
+ --header "Authorization: Bearer wa_…"
141
+ ```
142
+
143
+ - A token never grants more than its creator holds, when it's made or later: a demoted owner's tokens shrink with them.
144
+ - Tools with `confirm` are refused to tokens: approve those in the app.
145
+ - A token only works on the MCP endpoint (AGENT007). Revoke it with `revokeToken`.
146
+ - Tokens need `user` in `defineAgent`, to load the person a token acts as.
147
+
148
+ ## Usage
149
+
150
+ Every bridge step records its model and input and output tokens, and every token's MCP call records one call.
151
+ `usage({ days })` returns the rows and totals by bridge and model, for this person's conversations and tokens.
152
+
153
+ ## Testing
154
+
155
+ <!-- example: skip test fragment -->
156
+
157
+ ```ts
158
+ import { memoryAgentStore } from '@kerf-js/agent/server'
159
+ import { fakeBridge } from '@kerf-js/agent/test'
160
+
161
+ const input = { item: 'latte', cents: 400 }
162
+ const setPrice = { tool: 'setPrice', input }
163
+ const bridge = fakeBridge([{ call: setPrice }, 'Done.'])
164
+ const agent = defineAgent({
165
+ store: memoryAgentStore(),
166
+ bridges: [bridge],
167
+ system: '',
168
+ })
169
+ ```
170
+
171
+ Each line answers one step: words, a call or calls, or a function of the turn. `bridge.turns` keeps what it was handed.
172
+ `memoryAgentStore()` is for dev and tests; a production server refuses it (AGENT010).
173
+
174
+ ## Codes
175
+
176
+ | Code | Status | Means |
177
+ | -------- | ------ | ----------------------------------------------- |
178
+ | AGENT001 | 401 | Not signed in |
179
+ | AGENT002 | 404 | No such conversation or token, or not yours |
180
+ | AGENT003 | 503 | No bridge is available |
181
+ | AGENT004 | 422 | An empty message |
182
+ | AGENT005 | 409 | A held call answered twice |
183
+ | AGENT006 | 422 | A token with no grant its creator holds |
184
+ | AGENT007 | 403 | A token used outside `/_kerf/x/agent/mcp` |
185
+ | AGENT008 | 403 | A tool call reached a function without `agent:` |
186
+ | AGENT009 | 403 | A tool call the grant doesn't allow |
187
+ | AGENT010 | 500 | `memoryAgentStore()` on a production server |
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@kerf-js/agent",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "@kerf-js/agent: an assistant that runs your app. Server functions become its tools by opting in, with grants per role and per token, conversations, usage, and bridges to Claude, the Claude CLI or your own Rust",
5
+ "keywords": [
6
+ "agent",
7
+ "claude",
8
+ "mcp",
9
+ "kerf"
10
+ ],
11
+ "homepage": "https://github.com/Ravonus/kerf/tree/main/packages/agent#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Ravonus/kerf/issues"
14
+ },
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/Ravonus/kerf.git",
19
+ "directory": "packages/agent"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "docs",
24
+ "plugin.mjs",
25
+ "plugin.d.mts",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "type": "module",
30
+ "exports": {
31
+ ".": "./src/index.ts",
32
+ "./server": "./src/server.ts",
33
+ "./drizzle": "./src/drizzle.ts",
34
+ "./anthropic": "./src/bridges/anthropic.ts",
35
+ "./cli": "./src/bridges/cli.ts",
36
+ "./fn": "./src/bridges/fn.ts",
37
+ "./rust": "./src/bridges/rust.ts",
38
+ "./test": "./src/test.ts",
39
+ "./plugin": "./plugin.mjs"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "dependencies": {
45
+ "typescript": "6.0.3"
46
+ },
47
+ "peerDependencies": {
48
+ "@anthropic-ai/sdk": "^1.0.0",
49
+ "@kerf-js/core": "^0.1.0",
50
+ "@kerf-js/start": "^0.1.0",
51
+ "drizzle-orm": "^0.45.0",
52
+ "zod": "^4.0.0"
53
+ },
54
+ "peerDependenciesMeta": {
55
+ "@anthropic-ai/sdk": {
56
+ "optional": true
57
+ },
58
+ "drizzle-orm": {
59
+ "optional": true
60
+ }
61
+ },
62
+ "engines": {
63
+ "node": ">=24"
64
+ }
6
65
  }
package/plugin.d.mts ADDED
@@ -0,0 +1,5 @@
1
+ import type { PluginInstance } from '@kerf-js/core/plugin'
2
+
3
+ declare const plugin: (options?: Record<string, never>) => PluginInstance<unknown>
4
+ /** `agent()` for `kerf.config.ts`: the app's assistant, its tools, grants, conversations and MCP endpoint. */
5
+ export default plugin
package/plugin.mjs ADDED
@@ -0,0 +1,134 @@
1
+ // agent() for kerf.config.ts: the app's assistant. Server functions opt in as tools with `agent:`, grants decide what
2
+ // it may do, conversations and usage live in the app's database, and the app speaks MCP at /_kerf/x/agent/mcp for
3
+ // agents outside it. Built like `@kerf-js/pay`: one pure manifest, the server part behind the slot's lazy load.
4
+ import { definePlugin, defineSlot, provide } from '@kerf-js/core/plugin'
5
+ import { setup } from './src/setup.mjs'
6
+
7
+ const extension = defineSlot({
8
+ id: 'server.extension',
9
+ version: 1,
10
+ cardinality: 'keyed',
11
+ sides: ['server'],
12
+ })
13
+
14
+ const diagnostics = [
15
+ [
16
+ 'AGENT001',
17
+ 'error',
18
+ 'The assistant used by someone signed out',
19
+ "Every agent function is `auth: 'user'`",
20
+ ],
21
+ [
22
+ 'AGENT002',
23
+ 'error',
24
+ "A conversation or token that isn't the caller's",
25
+ 'Only its owner reads or changes it',
26
+ ],
27
+ [
28
+ 'AGENT003',
29
+ 'error',
30
+ 'No bridge can answer here',
31
+ 'Start the Rust bridge daemon, set ANTHROPIC_API_KEY, or sign in to the `claude` CLI',
32
+ ],
33
+ ['AGENT004', 'error', 'An empty message', 'Say something first'],
34
+ ['AGENT005', 'error', 'A held call answered twice', 'Each is approved or declined once'],
35
+ [
36
+ 'AGENT006',
37
+ 'error',
38
+ 'A token with nothing its creator may grant',
39
+ 'Give it grants you hold yourself',
40
+ ],
41
+ [
42
+ 'AGENT007',
43
+ 'error',
44
+ 'A token used on `/_kerf/fn/` directly',
45
+ 'Agents call tools through `/_kerf/x/agent/mcp`',
46
+ ],
47
+ [
48
+ 'AGENT008',
49
+ 'error',
50
+ "A tool call to a function that didn't opt in",
51
+ "Add `agent: { say: '…' }` to it",
52
+ ],
53
+ [
54
+ 'AGENT009',
55
+ 'error',
56
+ "A tool call the grant doesn't allow",
57
+ 'Grant its permission (`scope.read` / `scope.write`) to the role or token',
58
+ ],
59
+ [
60
+ 'AGENT010',
61
+ 'error',
62
+ '`memoryAgentStore()` on a production server',
63
+ '`drizzleAgentStore(db, tables)`, or your own `AgentStore`',
64
+ ],
65
+ ].map(([code, severity, catches, fix]) => ({ code, severity, catches, fix }))
66
+
67
+ export const agent = definePlugin({
68
+ name: '@kerf-js/agent',
69
+ version: '0.1.0',
70
+ kerf: '*',
71
+ namespace: 'AGENT',
72
+ permissions: {
73
+ net: ['api.anthropic.com'],
74
+ env: ['ANTHROPIC_API_KEY', 'AGENT_BRIDGE', 'AGENT_BRIDGE_TOKEN'],
75
+ spawn: ['claude'],
76
+ },
77
+ contribute: () => ({
78
+ provides: [
79
+ provide(extension, {
80
+ key: 'agent',
81
+ sides: { server: { module: '@kerf-js/agent/server', export: 'extension' } },
82
+ }),
83
+ ],
84
+ diagnostics,
85
+ docs: {
86
+ topic: 'agent',
87
+ summary:
88
+ "The app's assistant: tools from server functions, grants, conversations, usage, MCP, bridges; AGENT-codes",
89
+ file: new URL('./docs/agent.md', import.meta.url).pathname,
90
+ },
91
+ setup,
92
+ agents: {
93
+ title: 'Assistant',
94
+ text: "A query or mutation becomes an assistant tool with `agent: { say: '…' }` beside `auth`; add `confirm: true` where the owner should approve each call, and `scope` to name its permission (`menu` → `menu.read` / `menu.write`). Tools run as the signed-in person, through their `auth`, and only when the grant allows. Roles map to grants in `src/agent.server.ts`; tokens for outside agents use `/_kerf/x/agent/mcp`. `kerf docs agent`.",
95
+ },
96
+ catalog: [
97
+ {
98
+ name: 'defineAgent',
99
+ import: '@kerf-js/agent/server',
100
+ summary: 'The assistant: src/agent.server.ts default-exports it',
101
+ },
102
+ {
103
+ name: 'anthropic',
104
+ import: '@kerf-js/agent/anthropic',
105
+ summary: 'Answer through the Anthropic API, with tool use',
106
+ },
107
+ {
108
+ name: 'claudeCli',
109
+ import: '@kerf-js/agent/cli',
110
+ summary: 'Answer through the local claude CLI, tools over MCP',
111
+ },
112
+ {
113
+ name: 'rustBridge',
114
+ import: '@kerf-js/agent/rust',
115
+ summary: 'Answer through the Rust bridge daemon and its signed-in CLIs',
116
+ },
117
+ {
118
+ name: 'fnBridge',
119
+ import: '@kerf-js/agent/fn',
120
+ summary: 'Answer through your own server function',
121
+ },
122
+ { name: 'fakeBridge', import: '@kerf-js/agent/test', summary: 'A scripted bridge for tests' },
123
+ ],
124
+ map: [
125
+ {
126
+ want: 'Let the assistant do something',
127
+ call: "`agent: { say: 'What it does' }` on the query or mutation",
128
+ have: '`kerf docs agent`',
129
+ },
130
+ ],
131
+ }),
132
+ })
133
+
134
+ export default agent
package/src/bridge.ts ADDED
@@ -0,0 +1,71 @@
1
+ // A bridge is whatever answers: the Anthropic API, the local Claude CLI, a Rust service, a test script. The loop in
2
+ // `server.ts` hands it the conversation and the tools the grant allows, and it says what to write and what to call.
3
+ import type { Message, ToolInfo } from './index'
4
+
5
+ /** What a bridge is handed for one step of a turn. */
6
+ export interface BridgeTurn {
7
+ system: string
8
+ /** The conversation so far, ending with what the owner just said (and the calls already answered this turn). */
9
+ messages: Message[]
10
+ tools: ToolInfo[]
11
+ signal: AbortSignal
12
+ /** Who the turn is for (the conversation's owner): a bridge that meters spend per person names them. */
13
+ who: string
14
+ /** Words as they arrive: the page shows them as they're written. */
15
+ text(delta: string): void
16
+ /**
17
+ * For a bridge that runs tools itself (the CLI): the app's MCP endpoint and a token for this turn, good for these
18
+ * tools only. Such a bridge returns no `calls`: the endpoint records each as it runs.
19
+ */
20
+ mcp?: { url: string; token: string }
21
+ }
22
+
23
+ /** What a bridge answers with for one step. */
24
+ export interface BridgeStep {
25
+ /** What it wrote this step. */
26
+ text: string
27
+ /** Tools it wants run before it goes on. None: the turn is over. */
28
+ calls: { id: string; tool: string; input: unknown }[]
29
+ usage: { model: string; input: number; output: number }
30
+ /** The bridge's own form of this step, kept as a `native` part and handed back to it next time. */
31
+ raw?: unknown
32
+ }
33
+
34
+ /** Whatever answers: the Anthropic API, the Claude CLI, a Rust function, a test script. */
35
+ export interface Bridge {
36
+ /** Short and stable: stored on each conversation. */
37
+ id: string
38
+ /** What the owner sees in the picker. */
39
+ label: string
40
+ /** `native`: returns calls for the loop to run. `mcp`: runs them itself through `turn.mcp`. */
41
+ tools: 'native' | 'mcp'
42
+ /** False when it can't run here (no key, no CLI): the picker leaves it out. */
43
+ available?(): boolean
44
+ step(turn: BridgeTurn): Promise<BridgeStep>
45
+ /**
46
+ * Requests to `/_kerf/x/agent/bridges/<id>/<path>`: for a bridge that something outside calls in to, such as the
47
+ * Rust bridge daemon long-polling for jobs. It checks its own credentials.
48
+ */
49
+ serve?: (request: Request, path: string) => Response | Promise<Response>
50
+ }
51
+
52
+ /** A message's parts as plain text: what a bridge without structured history (the CLI, a Rust planner) reads. */
53
+ export function transcript(messages: Message[]): string {
54
+ return messages
55
+ .map((m) => {
56
+ const said = m.parts
57
+ .filter((p) => p.type !== 'native')
58
+ .map((p) =>
59
+ p.type === 'text'
60
+ ? p.text
61
+ : p.type === 'call'
62
+ ? `[called ${p.tool} ${JSON.stringify(p.input)}]`
63
+ : p.type === 'result'
64
+ ? `[${p.tool} → ${p.status}: ${JSON.stringify(p.output).slice(0, 2000)}]`
65
+ : '',
66
+ )
67
+ .join('\n')
68
+ return `${m.role === 'user' ? 'Owner' : 'Assistant'}: ${said}`
69
+ })
70
+ .join('\n\n')
71
+ }