@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/src/drizzle.ts ADDED
@@ -0,0 +1,228 @@
1
+ // An `AgentStore` on the app's own Drizzle tables (`kerf add agent` writes them to `src/db/agent.schema.ts`), on
2
+ // Postgres, SQLite or MySQL. JSON goes in text columns and flags in integers, so one store reads all three.
3
+ import {
4
+ and,
5
+ desc,
6
+ eq,
7
+ getTableName,
8
+ gte,
9
+ inArray,
10
+ or,
11
+ type AnyColumn,
12
+ type SQL,
13
+ type Table,
14
+ } from 'drizzle-orm'
15
+ import type { DbHandle } from '@kerf-js/start/db/core'
16
+ import type { AgentToken, Conversation, Message, PendingCall, Usage } from './index'
17
+ import type { AgentStore, TokenRow } from './store'
18
+
19
+ type Row = Record<string, unknown>
20
+ type Query = Promise<Row[]> & {
21
+ limit(n: number): Promise<Row[]>
22
+ orderBy(...c: SQL[]): Promise<Row[]>
23
+ }
24
+ interface Client {
25
+ select(fields?: Record<string, AnyColumn>): {
26
+ from(table: Table): { where(on: SQL | undefined): Query }
27
+ }
28
+ insert(table: Table): {
29
+ values(row: object): Promise<unknown> & {
30
+ onDuplicateKeyUpdate(update: { set: object }): Promise<unknown>
31
+ onConflictDoUpdate(update: { target: AnyColumn; set: object }): Promise<unknown>
32
+ }
33
+ }
34
+ delete(table: Table): { where(on: SQL | undefined): Promise<unknown> }
35
+ }
36
+
37
+ type T<C extends string> = Table & Record<C, AnyColumn>
38
+
39
+ /** The five agent tables from `src/db/agent.schema.ts`. */
40
+ export interface AgentTables {
41
+ conversations: T<'id' | 'owner' | 'state' | 'pinned' | 'updated'>
42
+ messages: T<'id' | 'conversation' | 'at'>
43
+ usage: T<'id' | 'conversation' | 'token' | 'at'>
44
+ pending: T<'id' | 'conversation'>
45
+ tokens: T<'id' | 'owner' | 'hash' | 'created'>
46
+ }
47
+
48
+ const parse = <V>(s: unknown, fallback: V): V => {
49
+ try {
50
+ return typeof s === 'string' ? (JSON.parse(s) as V) : fallback
51
+ } catch {
52
+ return fallback
53
+ }
54
+ }
55
+
56
+ const conversationOf = (r: Row): Conversation => ({
57
+ id: String(r.id),
58
+ title: String(r.title),
59
+ owner: String(r.owner),
60
+ state: r.state === 'archived' ? 'archived' : 'open',
61
+ pinned: !!Number(r.pinned),
62
+ bridge: String(r.bridge),
63
+ created: Number(r.created),
64
+ updated: Number(r.updated),
65
+ })
66
+ const tokenOf = (r: Row): TokenRow => ({
67
+ id: String(r.id),
68
+ name: String(r.name),
69
+ owner: String(r.owner),
70
+ grants: parse<string[]>(r.grants, []),
71
+ hash: String(r.hash),
72
+ created: Number(r.created),
73
+ used: r.used == null ? null : Number(r.used),
74
+ revoked: !!Number(r.revoked),
75
+ })
76
+
77
+ const pendingOf = (r: Row): PendingCall => ({
78
+ id: String(r.id),
79
+ conversation: String(r.conversation),
80
+ tool: String(r.tool),
81
+ input: parse(r.input, {}),
82
+ at: Number(r.at),
83
+ })
84
+
85
+ type Upsert = (table: Table & { id: AnyColumn }, row: Row) => Promise<void>
86
+
87
+ /** Conversations and their messages. */
88
+ function conversationRows(
89
+ client: Client,
90
+ upsert: Upsert,
91
+ { conversations, messages, pending }: AgentTables,
92
+ ) {
93
+ return {
94
+ async conversations(owner, state) {
95
+ const rows = await client
96
+ .select()
97
+ .from(conversations)
98
+ .where(and(eq(conversations.owner, owner), eq(conversations.state, state)))
99
+ .orderBy(desc(conversations.pinned), desc(conversations.updated))
100
+ return rows.map(conversationOf)
101
+ },
102
+ async conversation(id) {
103
+ const [r] = await client.select().from(conversations).where(eq(conversations.id, id)).limit(1)
104
+ return r ? conversationOf(r) : null
105
+ },
106
+ saveConversation: (c) => upsert(conversations, { ...c, pinned: c.pinned ? 1 : 0 }),
107
+ async removeConversation(id) {
108
+ await client.delete(messages).where(eq(messages.conversation, id))
109
+ await client.delete(pending).where(eq(pending.conversation, id))
110
+ await client.delete(conversations).where(eq(conversations.id, id))
111
+ },
112
+ async messages(conversation) {
113
+ const rows = await client
114
+ .select()
115
+ .from(messages)
116
+ .where(eq(messages.conversation, conversation))
117
+ .orderBy(messages.at as unknown as SQL)
118
+ return rows.map((r): Message => ({
119
+ id: String(r.id),
120
+ conversation: String(r.conversation),
121
+ role: r.role === 'assistant' ? 'assistant' : 'user',
122
+ parts: parse(r.parts, []),
123
+ at: Number(r.at),
124
+ }))
125
+ },
126
+ addMessage: (m) => upsert(messages, { ...m, parts: JSON.stringify(m.parts) }),
127
+ } satisfies Partial<AgentStore>
128
+ }
129
+
130
+ /** Usage rows, read back for one owner's conversations and tokens. */
131
+ function usageRows(client: Client, upsert: Upsert, { conversations, usage, tokens }: AgentTables) {
132
+ return {
133
+ addUsage: (u) => upsert(usage, { id: crypto.randomUUID(), ...u }),
134
+ async usage(owner, since) {
135
+ const mine = (
136
+ await client
137
+ .select({ id: conversations.id })
138
+ .from(conversations)
139
+ .where(eq(conversations.owner, owner))
140
+ ).map((r) => String(r.id))
141
+ const theirs = (
142
+ await client.select({ id: tokens.id }).from(tokens).where(eq(tokens.owner, owner))
143
+ ).map((r) => String(r.id))
144
+ if (!mine.length && !theirs.length) return []
145
+ const rows = await client
146
+ .select()
147
+ .from(usage)
148
+ .where(
149
+ and(
150
+ gte(usage.at, since),
151
+ or(
152
+ mine.length ? inArray(usage.conversation, mine) : undefined,
153
+ theirs.length ? inArray(usage.token, theirs) : undefined,
154
+ ),
155
+ ),
156
+ )
157
+ return rows.map((r): Usage => ({
158
+ conversation: typeof r.conversation === 'string' ? r.conversation : null,
159
+ token: typeof r.token === 'string' ? r.token : null,
160
+ bridge: String(r.bridge),
161
+ model: String(r.model),
162
+ input: Number(r.input),
163
+ output: Number(r.output),
164
+ calls: Number(r.calls),
165
+ ms: Number(r.ms),
166
+ at: Number(r.at),
167
+ }))
168
+ },
169
+ } satisfies Partial<AgentStore>
170
+ }
171
+
172
+ /** Held calls and tokens. */
173
+ function heldAndTokens(client: Client, upsert: Upsert, { pending, tokens }: AgentTables) {
174
+ return {
175
+ async pending(conversation) {
176
+ const rows = await client.select().from(pending).where(eq(pending.conversation, conversation))
177
+ return rows.map(pendingOf)
178
+ },
179
+ hold: (p) => upsert(pending, { ...p, input: JSON.stringify(p.input ?? {}) }),
180
+ async take(id) {
181
+ const [r] = await client.select().from(pending).where(eq(pending.id, id)).limit(1)
182
+ if (!r) return null
183
+ await client.delete(pending).where(eq(pending.id, id))
184
+ return pendingOf(r)
185
+ },
186
+ async tokens(owner) {
187
+ const rows = await client
188
+ .select()
189
+ .from(tokens)
190
+ .where(eq(tokens.owner, owner))
191
+ .orderBy(desc(tokens.created))
192
+ return rows.map((r): AgentToken => {
193
+ const { hash: _, ...t } = tokenOf(r)
194
+ return t
195
+ })
196
+ },
197
+ async token(id) {
198
+ const [r] = await client.select().from(tokens).where(eq(tokens.id, id)).limit(1)
199
+ return r ? tokenOf(r) : null
200
+ },
201
+ async tokenByHash(hash) {
202
+ const [r] = await client.select().from(tokens).where(eq(tokens.hash, hash)).limit(1)
203
+ return r ? tokenOf(r) : null
204
+ },
205
+ saveToken: (t) =>
206
+ upsert(tokens, { ...t, grants: JSON.stringify(t.grants), revoked: t.revoked ? 1 : 0 }),
207
+ } satisfies Partial<AgentStore>
208
+ }
209
+
210
+ /** An `AgentStore` on the app's Drizzle database and the tables `kerf add agent` wrote. */
211
+ export function drizzleAgentStore(db: { $kerf: DbHandle }, tables: AgentTables): AgentStore {
212
+ const client = db as unknown as Client
213
+ const mysql = db.$kerf.dialect === 'mysql'
214
+ // written by turns and by the MCP endpoint, outside any one function: the app's queries tag them `agent`
215
+ for (const t of Object.values(tables)) db.$kerf.exempt.add(getTableName(t))
216
+ const upsert: Upsert = async (table, row) => {
217
+ const { id: _, ...set } = row
218
+ const insert = client.insert(table).values(row)
219
+ await (mysql
220
+ ? insert.onDuplicateKeyUpdate({ set })
221
+ : insert.onConflictDoUpdate({ target: table.id, set }))
222
+ }
223
+ return {
224
+ ...conversationRows(client, upsert, tables),
225
+ ...usageRows(client, upsert, tables),
226
+ ...heldAndTokens(client, upsert, tables),
227
+ }
228
+ }
package/src/index.ts ADDED
@@ -0,0 +1,154 @@
1
+ // @kerf-js/agent, the part both sides share: what a function says to agents, how grants read, and the shapes of a
2
+ // conversation. The server half is `@kerf-js/agent/server`; nothing here touches a model, a key or the database.
3
+
4
+ /**
5
+ * What a server function offers an agent, on `agent:` beside `auth`. A function without it is invisible to every
6
+ * agent, whatever the grant: access is opted into, one function at a time.
7
+ *
8
+ * - `scope`: the permission's first half, `menu` in `menu.write`. Default: the function's first tag (a query) or
9
+ * first invalidated tag (a mutation), else its export name.
10
+ * - `confirm`: the owner approves each call before it runs. A mutation that costs money or can't be undone wants it.
11
+ * - `say`: what it does, for the model. Default: the export name in words.
12
+ */
13
+ export interface AgentAccess {
14
+ scope?: string
15
+ confirm?: boolean
16
+ say?: string
17
+ }
18
+
19
+ declare module '@kerf-js/start' {
20
+ interface FnOptions {
21
+ /** Offer this function to agents as a tool: `true`, or what it needs (`@kerf-js/agent`). */
22
+ agent?: boolean | AgentAccess
23
+ }
24
+ interface Context {
25
+ /** Set when an agent is the caller: who it acts for, and what it may do. Absent for a person. */
26
+ agent?: AgentCaller
27
+ }
28
+ }
29
+
30
+ /** An agent calling, as `ctx.agent` reads. */
31
+ export interface AgentCaller {
32
+ /** The conversation, or the token, it's acting through. */
33
+ via: { kind: 'conversation' | 'token'; id: string }
34
+ /** What it may call: `menu.read`, `menu.*`, `*.read`, `*`. */
35
+ grants: readonly string[]
36
+ }
37
+
38
+ /**
39
+ * Whether `grants` allow `permission` (`menu.write`). A grant is `scope.action` where either half may be `*`; a bare
40
+ * `scope` means `scope.*`. `write` covers `read`: what may change something may look at it.
41
+ */
42
+ export function allows(grants: readonly string[], permission: string): boolean {
43
+ const [scope = '', action = ''] = permission.split('.')
44
+ return grants.some((g) => {
45
+ const [gs = '', ga = '*'] = g.split('.')
46
+ const scopeOk = gs === '*' || gs === scope
47
+ const actionOk = ga === '*' || ga === action || (ga === 'write' && action === 'read')
48
+ return scopeOk && actionOk
49
+ })
50
+ }
51
+
52
+ /** One tool as a model sees it. */
53
+ export interface ToolInfo {
54
+ /** The model's name for it: the export name, `[a-zA-Z0-9_-]`. */
55
+ name: string
56
+ /** The server function's `$id`. */
57
+ id: string
58
+ kind: 'query' | 'mutation'
59
+ /** `scope.read` for a query, `scope.write` for a mutation. */
60
+ permission: string
61
+ confirm: boolean
62
+ description: string
63
+ /** JSON Schema of the input. */
64
+ input: Record<string, unknown>
65
+ }
66
+
67
+ /** A conversation's line, as the list shows it. */
68
+ export interface Conversation {
69
+ id: string
70
+ title: string
71
+ /** Who started it: the user's id. */
72
+ owner: string
73
+ state: 'open' | 'archived'
74
+ pinned: boolean
75
+ /** The bridge that answers it: `claude`, `cli`, `rust`… */
76
+ bridge: string
77
+ created: number
78
+ updated: number
79
+ }
80
+
81
+ /** One part of a message: what was said, a tool the agent called, or what came back. */
82
+ export type Part =
83
+ | { type: 'text'; text: string }
84
+ | { type: 'call'; id: string; tool: string; input: unknown }
85
+ | {
86
+ type: 'result'
87
+ id: string
88
+ tool: string
89
+ /** `ok` ran, `error` threw, `refused` the grant didn't allow it, `waiting` for the owner, `declined` by them. */
90
+ status: 'ok' | 'error' | 'refused' | 'waiting' | 'declined'
91
+ output: unknown
92
+ }
93
+ /**
94
+ * A bridge's own record of a step, sent back to it unchanged (the API's thinking blocks are tied to the
95
+ * conversation). Pages skip it.
96
+ */
97
+ | { type: 'native'; bridge: string; content: unknown }
98
+
99
+ /** One message in a conversation: what someone said, or what the agent wrote and called. */
100
+ export interface Message {
101
+ id: string
102
+ conversation: string
103
+ role: 'user' | 'assistant'
104
+ parts: Part[]
105
+ at: number
106
+ }
107
+
108
+ /** What one turn cost. */
109
+ export interface Usage {
110
+ conversation: string | null
111
+ /** Set for a call through an API token rather than the app's own chat. */
112
+ token: string | null
113
+ bridge: string
114
+ model: string
115
+ input: number
116
+ output: number
117
+ /** Tool calls made in the turn. */
118
+ calls: number
119
+ ms: number
120
+ at: number
121
+ }
122
+
123
+ /** A call held for the owner: a tool with `confirm`, waiting on Approve or Decline. */
124
+ export interface PendingCall {
125
+ id: string
126
+ conversation: string
127
+ tool: string
128
+ input: unknown
129
+ at: number
130
+ }
131
+
132
+ /** An API token for an agent outside the app (Claude Code, Codex, a script): its grants, never its secret. */
133
+ export interface AgentToken {
134
+ id: string
135
+ name: string
136
+ owner: string
137
+ grants: string[]
138
+ created: number
139
+ used: number | null
140
+ revoked: boolean
141
+ }
142
+
143
+ /** What streams to the page while a turn runs. Each message carries only what's new. */
144
+ export type TurnEvent =
145
+ | { type: 'text'; delta: string }
146
+ | { type: 'call'; id: string; tool: string; input: unknown }
147
+ | {
148
+ type: 'result'
149
+ id: string
150
+ tool: string
151
+ status: Extract<Part, { type: 'result' }>['status']
152
+ }
153
+ | { type: 'done'; message: string }
154
+ | { type: 'error'; message: string }
package/src/mcp.ts ADDED
@@ -0,0 +1,93 @@
1
+ // The app as an MCP server, at `/_kerf/x/agent/mcp`: Claude Code, Codex or anything that speaks MCP connects with a
2
+ // bearer token and sees exactly the tools its grants allow. Streamable HTTP, answered as plain JSON (no server-sent
3
+ // events: nothing here pushes), which is all a tools-only server needs.
4
+ import type { Part, ToolInfo } from './index'
5
+
6
+ type Result = { status: Extract<Part, { type: 'result' }>['status']; output: unknown }
7
+
8
+ interface Serve {
9
+ tools(): ToolInfo[]
10
+ call(name: string, input: unknown): Promise<Result>
11
+ }
12
+
13
+ const VERSION = '2025-06-18'
14
+
15
+ type Rpc = {
16
+ jsonrpc: '2.0'
17
+ id?: string | number | null
18
+ method: string
19
+ params?: Record<string, unknown>
20
+ }
21
+
22
+ const json = (body: unknown, status = 200) =>
23
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })
24
+
25
+ async function answer(m: Rpc, s: Serve): Promise<unknown> {
26
+ switch (m.method) {
27
+ case 'initialize':
28
+ return {
29
+ protocolVersion:
30
+ typeof m.params?.protocolVersion === 'string' ? m.params.protocolVersion : VERSION,
31
+ capabilities: { tools: { listChanged: false } },
32
+ serverInfo: { name: 'kerf-agent', version: '0.1.0' },
33
+ }
34
+ case 'ping':
35
+ return {}
36
+ case 'tools/list':
37
+ return {
38
+ tools: s.tools().map((t) => ({
39
+ name: t.name,
40
+ description: t.confirm
41
+ ? `${t.description} (the owner approves each call)`
42
+ : t.description,
43
+ inputSchema: t.input,
44
+ annotations: { readOnlyHint: t.kind === 'query' },
45
+ })),
46
+ }
47
+ case 'tools/call': {
48
+ const name = typeof m.params?.name === 'string' ? m.params.name : ''
49
+ const r = await s.call(name, m.params?.arguments ?? {})
50
+ const text = typeof r.output === 'string' ? r.output : JSON.stringify(r.output)
51
+ return { content: [{ type: 'text', text }], isError: r.status !== 'ok' }
52
+ }
53
+ default:
54
+ throw Object.assign(new Error(`Unknown method ${m.method}`), { rpc: -32601 })
55
+ }
56
+ }
57
+
58
+ export async function serveMcp(request: Request, s: Serve): Promise<Response> {
59
+ if (request.method === 'GET')
60
+ return new Response(null, { status: 405, headers: { allow: 'POST' } })
61
+ if (request.method === 'DELETE') return new Response(null, { status: 204 })
62
+ if (request.method !== 'POST')
63
+ return new Response(null, { status: 405, headers: { allow: 'POST' } })
64
+ let body: Rpc | Rpc[]
65
+ try {
66
+ body = (await request.json()) as Rpc | Rpc[]
67
+ } catch {
68
+ return json({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }, 400)
69
+ }
70
+ const one = async (m: Rpc) => {
71
+ // a notification (no id) gets no answer
72
+ if (m.id === undefined) {
73
+ if (m.method !== 'notifications/initialized') await answer(m, s).catch(() => {})
74
+ return undefined
75
+ }
76
+ try {
77
+ return { jsonrpc: '2.0', id: m.id, result: await answer(m, s) }
78
+ } catch (e) {
79
+ const code = (e as { rpc?: number }).rpc ?? -32603
80
+ return {
81
+ jsonrpc: '2.0',
82
+ id: m.id,
83
+ error: { code, message: e instanceof Error ? e.message : String(e) },
84
+ }
85
+ }
86
+ }
87
+ if (Array.isArray(body)) {
88
+ const out = (await Promise.all(body.map(one))).filter(Boolean)
89
+ return out.length ? json(out) : new Response(null, { status: 202 })
90
+ }
91
+ const out = await one(body)
92
+ return out ? json(out) : new Response(null, { status: 202 })
93
+ }
@@ -0,0 +1,131 @@
1
+ // A person's conversations: listed, opened, started, renamed, pinned, archived, deleted, and the two things that move
2
+ // one on, saying something and answering a held call.
3
+ import { randomUUID } from 'node:crypto'
4
+ import type { Context } from '@kerf-js/start'
5
+ import { allows, type Conversation, type TurnEvent } from '../index'
6
+ import { allTools } from '../tools'
7
+ import { AgentError, userOf, type Core } from './core'
8
+ import { runTool, turn } from './run'
9
+
10
+ type Change = { title?: string; state?: Conversation['state']; pinned?: boolean; bridge?: string }
11
+ const quiet = () => {}
12
+ const never = () => new AbortController().signal
13
+
14
+ /** The conversation methods of a `defineAgent` result. */
15
+ export function conversationApi(core: Core) {
16
+ const { store } = core
17
+ return {
18
+ conversations: (ctx: Context, state: Conversation['state'] = 'open') =>
19
+ store.conversations(userOf(ctx).id, state),
20
+
21
+ async conversation(ctx: Context, id: string) {
22
+ const c = await core.mine(ctx, id)
23
+ return { ...c, messages: await store.messages(id), pending: await store.pending(id) }
24
+ },
25
+
26
+ async start(ctx: Context, input: { title?: string; bridge?: string } = {}) {
27
+ const now = Date.now()
28
+ const c: Conversation = {
29
+ id: randomUUID(),
30
+ title: input.title?.trim() || 'New conversation',
31
+ owner: userOf(ctx).id,
32
+ state: 'open',
33
+ pinned: false,
34
+ bridge: core.bridge(input.bridge)?.id ?? 'none',
35
+ created: now,
36
+ updated: now,
37
+ }
38
+ await store.saveConversation(c)
39
+ return c
40
+ },
41
+
42
+ async update(ctx: Context, id: string, change: Change) {
43
+ const c = await core.mine(ctx, id)
44
+ const next = {
45
+ ...c,
46
+ ...(change.title !== undefined && { title: change.title.trim() || c.title }),
47
+ ...(change.state && { state: change.state }),
48
+ ...(change.pinned !== undefined && { pinned: change.pinned }),
49
+ ...(change.bridge &&
50
+ core.bridge(change.bridge)?.id === change.bridge && { bridge: change.bridge }),
51
+ updated: Date.now(),
52
+ }
53
+ await store.saveConversation(next)
54
+ return next
55
+ },
56
+
57
+ async remove(ctx: Context, id: string) {
58
+ await core.mine(ctx, id)
59
+ await store.removeConversation(id)
60
+ },
61
+ }
62
+ }
63
+
64
+ /** Saying something and answering a held call: the methods that run turns. */
65
+ export function turnApi(core: Core) {
66
+ const { store } = core
67
+ return {
68
+ /**
69
+ * Say something and run the turn. `emit` gets the reply as it's written (publish it to a topic for the page). The
70
+ * first message titles a new conversation.
71
+ */
72
+ async send(
73
+ ctx: Context,
74
+ input: { conversation: string; text: string },
75
+ emit: (e: TurnEvent) => void = quiet,
76
+ signal = never(),
77
+ ) {
78
+ let c = await core.mine(ctx, input.conversation)
79
+ const text = input.text.trim()
80
+ if (!text) throw new AgentError('AGENT004', 'Say something first', 422)
81
+ if (c.state === 'archived') c = { ...c, state: 'open' }
82
+ if (c.title === 'New conversation')
83
+ c = { ...c, title: text.length > 60 ? `${text.slice(0, 57)}…` : text }
84
+ await store.saveConversation(c)
85
+ await store.addMessage({
86
+ id: randomUUID(),
87
+ conversation: c.id,
88
+ role: 'user',
89
+ parts: [{ type: 'text', text }],
90
+ at: Date.now(),
91
+ })
92
+ try {
93
+ return await turn(core, ctx, c, emit, signal)
94
+ } catch (e) {
95
+ emit({ type: 'error', message: e instanceof Error ? e.message : String(e) })
96
+ throw e
97
+ }
98
+ },
99
+
100
+ /** The owner's answer to a held call: run it (or not), then let the agent go on from there. */
101
+ async resolve(
102
+ ctx: Context,
103
+ input: { call: string; approve: boolean },
104
+ emit: (e: TurnEvent) => void = quiet,
105
+ signal = never(),
106
+ ) {
107
+ const held = await store.take(input.call)
108
+ if (!held) throw new AgentError('AGENT005', 'That was already answered', 409)
109
+ const c = await core.mine(ctx, held.conversation)
110
+ const grants = core.grantsOf(userOf(ctx))
111
+ const tool = allTools().find((t) => t.name === held.tool)
112
+ const result =
113
+ !tool || !allows(grants, tool.permission)
114
+ ? { status: 'refused' as const, output: 'Not allowed any more' }
115
+ : input.approve
116
+ ? await runTool(tool, held.input, { via: { kind: 'conversation', id: c.id }, grants })
117
+ : { status: 'declined' as const, output: 'The owner said no' }
118
+ await store.addMessage({
119
+ id: randomUUID(),
120
+ conversation: c.id,
121
+ role: 'assistant',
122
+ parts: [{ type: 'result', id: held.id, tool: held.tool, ...result }],
123
+ at: Date.now(),
124
+ })
125
+ emit({ type: 'result', id: held.id, tool: held.tool, status: result.status })
126
+ // the agent hears how it went and says what's next, unless something else of this turn is still waiting
127
+ if ((await store.pending(c.id)).length) return null
128
+ return turn(core, ctx, c, emit, signal)
129
+ },
130
+ }
131
+ }
@@ -0,0 +1,92 @@
1
+ // What every part of the server half shares: the options, who's asking, what they may grant, and the state a turn
2
+ // keeps outside the store (its token and its reply in progress, for a bridge that calls tools over MCP).
3
+ import { AsyncLocalStorage } from 'node:async_hooks'
4
+ import { createHash } from 'node:crypto'
5
+ import { FnError, type Context } from '@kerf-js/start'
6
+ import type { Bridge } from '../bridge'
7
+ import type { AgentCaller, Message, TurnEvent } from '../index'
8
+ import type { AgentStore } from '../store'
9
+
10
+ export type User = { id: string; role?: string | string[] | null }
11
+
12
+ /** How the app's assistant is set up: `src/agent.server.ts` passes these to `defineAgent`. */
13
+ export interface AgentOptions {
14
+ store: AgentStore
15
+ /** Who answers, by id. The first available one is the default. */
16
+ bridges: Bridge[]
17
+ /** What the agent is told before each conversation: the shop, the rules, the tone. */
18
+ system: string | ((ctx: Context) => string | Promise<string>)
19
+ /**
20
+ * What each role may let an agent do: `{ owner: ['*'], staff: ['orders.*', 'menu.read'] }`. Roles are read from
21
+ * `user.role` like `auth: { role }` reads them. Without it, any signed-in user grants `*`: their own `auth` still holds.
22
+ */
23
+ roles?: Record<string, string[]>
24
+ /** The user a token acts as, by id: needed for tokens. Return null for one that's gone. */
25
+ user?: (id: string, ctx: Context) => Promise<object | null> | object | null
26
+ /** Most tool rounds in one turn. Default 8. */
27
+ steps?: number
28
+ }
29
+
30
+ /** A refusal the client sees as it is: `answer` carries the code, message and status. */
31
+ export class AgentError extends FnError {
32
+ answer: { code: string; message: string; status: number }
33
+ constructor(code: string, message: string, status = 403) {
34
+ super({ message, code }, status)
35
+ this.answer = { code, message, status }
36
+ }
37
+ }
38
+
39
+ export const MCP = '/_kerf/x/agent/mcp'
40
+
41
+ /** A tool call in progress: whose grants it runs under. Only the outermost call is checked; what it calls in turn is its own business. */
42
+ export const acting = new AsyncLocalStorage<{ caller: AgentCaller; checked: boolean }>()
43
+
44
+ /** Turn tokens: one per MCP turn, good for that conversation's grants until the turn ends. Process memory only. */
45
+ export const turnTokens = new Map<
46
+ string,
47
+ { conversation: string; user: object; grants: string[]; expires: number }
48
+ >()
49
+
50
+ /** An MCP turn in progress, so its tool calls land in the reply being written. */
51
+ export const liveTurns = new Map<string, { reply: Message; emit: (e: TurnEvent) => void }>()
52
+
53
+ export const hash = (secret: string) => createHash('sha256').update(secret).digest('hex')
54
+
55
+ const rolesOf = (u: User | null | undefined) =>
56
+ !u?.role ? [] : Array.isArray(u.role) ? u.role : u.role.split(',').map((r) => r.trim())
57
+
58
+ export function userOf(ctx: Context): User {
59
+ const u = (ctx as { user?: User | null }).user
60
+ if (!u) throw new AgentError('AGENT001', 'Sign in to use the assistant', 401)
61
+ return u
62
+ }
63
+
64
+ export type Core = ReturnType<typeof makeCore>
65
+
66
+ export function makeCore(options: AgentOptions) {
67
+ const { store } = options
68
+ const grantsOf = (u: User): string[] =>
69
+ options.roles ? [...new Set(rolesOf(u).flatMap((r) => options.roles![r] ?? []))] : ['*']
70
+ return {
71
+ options,
72
+ store,
73
+ steps: options.steps ?? 8,
74
+ grantsOf,
75
+ usable: () => options.bridges.filter((b) => b.available?.() ?? true),
76
+ /** `id` if it can answer, else `AGENT_BRIDGE`'s, else the first that can. */
77
+ bridge(id?: string) {
78
+ const usable = options.bridges.filter((b) => b.available?.() ?? true)
79
+ const preferred = process.env.AGENT_BRIDGE?.trim()
80
+ return usable.find((b) => b.id === id) ?? usable.find((b) => b.id === preferred) ?? usable[0]
81
+ },
82
+ async mine(ctx: Context, id: string) {
83
+ const c = await store.conversation(id)
84
+ if (!c || c.owner !== userOf(ctx).id)
85
+ throw new AgentError('AGENT002', 'No such conversation', 404)
86
+ return c
87
+ },
88
+ }
89
+ }
90
+
91
+ /** The agent calling right now, if any: inside a tool, `ctx.agent` for the request may be a person's. */
92
+ export const agentCaller = () => acting.getStore()?.caller