@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/setup.mjs ADDED
@@ -0,0 +1,232 @@
1
+ // What `kerf add agent` writes, as data: `kerf add` does the writing, so a dry run and a refusal come for free. Plain
2
+ // JS strings, because this loads with the config.
3
+
4
+ /** The five tables `drizzleAgentStore` reads: times in ms, JSON in text, flags in integers. */
5
+ function tables(engine) {
6
+ const cols = ({
7
+ table,
8
+ str,
9
+ long,
10
+ int,
11
+ key,
12
+ }) => `export const agentConversations = ${table}('agent_conversations', {
13
+ id: ${key}.primaryKey(),
14
+ title: ${str}.notNull(),
15
+ owner: ${key}.notNull(),
16
+ state: ${str}.notNull(),
17
+ pinned: ${int}.notNull(),
18
+ bridge: ${str}.notNull(),
19
+ created: ${long}.notNull(),
20
+ updated: ${long}.notNull(),
21
+ })
22
+
23
+ export const agentMessages = ${table}('agent_messages', {
24
+ id: ${key}.primaryKey(),
25
+ conversation: ${key}.notNull(),
26
+ role: ${str}.notNull(),
27
+ parts: text().notNull(),
28
+ at: ${long}.notNull(),
29
+ })
30
+
31
+ export const agentUsage = ${table}('agent_usage', {
32
+ id: ${key}.primaryKey(),
33
+ conversation: ${key},
34
+ token: ${key},
35
+ bridge: ${str}.notNull(),
36
+ model: ${str}.notNull(),
37
+ input: ${int}.notNull(),
38
+ output: ${int}.notNull(),
39
+ calls: ${int}.notNull(),
40
+ ms: ${int}.notNull(),
41
+ at: ${long}.notNull(),
42
+ })
43
+
44
+ export const agentPending = ${table}('agent_pending', {
45
+ id: ${key}.primaryKey(),
46
+ conversation: ${key}.notNull(),
47
+ tool: ${str}.notNull(),
48
+ input: text().notNull(),
49
+ at: ${long}.notNull(),
50
+ })
51
+
52
+ export const agentTokens = ${table}('agent_tokens', {
53
+ id: ${key}.primaryKey(),
54
+ name: ${str}.notNull(),
55
+ owner: ${key}.notNull(),
56
+ grants: text().notNull(),
57
+ hash: ${key}.notNull().unique(),
58
+ created: ${long}.notNull(),
59
+ used: ${long},
60
+ revoked: ${int}.notNull(),
61
+ })
62
+ `
63
+ return {
64
+ sqlite: () =>
65
+ `import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'\n\n${cols({ table: 'sqliteTable', str: 'text()', long: 'integer()', int: 'integer()', key: 'text()' })}`,
66
+ postgres: () =>
67
+ `import { bigint, integer, pgTable, text } from 'drizzle-orm/pg-core'\n\n${cols({ table: 'pgTable', str: 'text()', long: "bigint({ mode: 'number' })", int: 'integer()', key: 'text()' })}`,
68
+ mysql: () =>
69
+ `import { bigint, int, mysqlTable, text, varchar } from 'drizzle-orm/mysql-core'\n\n${cols({ table: 'mysqlTable', str: 'varchar({ length: 191 })', long: "bigint({ mode: 'number' })", int: 'int()', key: 'varchar({ length: 191 })' })}`,
70
+ }[engine]()
71
+ }
72
+
73
+ const server = (
74
+ drizzle,
75
+ ) => `${drizzle ? "import { drizzleAgentStore } from '@kerf-js/agent/drizzle'\n" : ''}import { anthropic } from '@kerf-js/agent/anthropic'
76
+ import { claudeCli } from '@kerf-js/agent/cli'
77
+ import { defineAgent${drizzle ? '' : ', memoryAgentStore'} } from '@kerf-js/agent/server'
78
+ ${drizzle ? "import { db } from '#/db/index.server'\nimport { agentConversations, agentMessages, agentPending, agentTokens, agentUsage } from '#/db/schema'\n" : ''}
79
+ // The app's assistant. A query or mutation becomes one of its tools by saying so: \`agent: { say: '…' }\` beside
80
+ // \`auth\`. Each runs as the person asking, through their own \`auth\`, and only if the grant below allows it.
81
+ // Outside agents (Claude Code, Codex) connect to /_kerf/x/agent/mcp with a token made in the app.
82
+ export default defineAgent({
83
+ store: ${drizzle ? 'drizzleAgentStore(db, { conversations: agentConversations, messages: agentMessages, usage: agentUsage, pending: agentPending, tokens: agentTokens })' : 'memoryAgentStore()'},
84
+ // first available answers by default: the API with ANTHROPIC_API_KEY set, else the \`claude\` CLI on this machine
85
+ bridges: [anthropic(), claudeCli()],
86
+ system: 'You run this site for its owner. Use the tools to look things up and make changes; say what you changed.',
87
+ // roles: { admin: ['*'], staff: ['orders.*', 'menu.read'] },
88
+ // user: (id) => …, // the user a token acts as: needed before tokens work
89
+ })
90
+ `
91
+
92
+ const functions = `import { mutation, query, stream, topic } from '@kerf-js/start'
93
+ import type { TurnEvent } from '@kerf-js/agent'
94
+ import { z } from 'zod'
95
+ import agent from '../agent.server'
96
+
97
+ const Event = z.custom<TurnEvent>((v) => !!v && typeof v === 'object' && 'type' in v)
98
+ const turns = topic('agent-turn', { key: z.string().max(64), message: Event })
99
+ const Id = z.string().min(1).max(64)
100
+
101
+ /** Conversations, newest first: \`open\` or \`archived\`. */
102
+ export const conversations = query({
103
+ auth: 'user',
104
+ input: z.object({ state: z.enum(['open', 'archived']).default('open') }),
105
+ tags: ['agent'],
106
+ run: ({ input, ctx }) => agent.conversations(ctx, input.state),
107
+ })
108
+
109
+ /** One conversation: its messages and the calls waiting on the owner. */
110
+ export const conversation = query({
111
+ auth: 'user',
112
+ input: z.object({ id: Id }),
113
+ tags: ['agent'],
114
+ run: ({ input, ctx }) => agent.conversation(ctx, input.id),
115
+ })
116
+
117
+ /** Who can answer, what this person may let it do, and every tool and scope: the settings page. */
118
+ export const agentInfo = query({
119
+ auth: 'user',
120
+ tags: ['agent'],
121
+ run: ({ ctx }) => ({ bridges: agent.bridges(), grants: agent.grants(ctx), tools: agent.tools(ctx), scopes: agent.scopes() }),
122
+ })
123
+
124
+ export const startConversation = mutation({
125
+ auth: 'user',
126
+ input: z.object({ title: z.string().max(120).optional(), bridge: z.string().max(40).optional() }),
127
+ invalidates: ['agent'],
128
+ run: ({ input, ctx }) => agent.start(ctx, input),
129
+ })
130
+
131
+ /** Rename, archive or bring back, pin, or switch who answers. */
132
+ export const updateConversation = mutation({
133
+ auth: 'user',
134
+ input: z.object({
135
+ id: Id,
136
+ title: z.string().max(120).optional(),
137
+ state: z.enum(['open', 'archived']).optional(),
138
+ pinned: z.boolean().optional(),
139
+ bridge: z.string().max(40).optional(),
140
+ }),
141
+ invalidates: ['agent'],
142
+ run: ({ input: { id, ...change }, ctx }) => agent.update(ctx, id, change),
143
+ })
144
+
145
+ export const deleteConversation = mutation({
146
+ auth: 'user',
147
+ input: z.object({ id: Id }),
148
+ invalidates: ['agent'],
149
+ run: ({ input, ctx }) => agent.remove(ctx, input.id),
150
+ })
151
+
152
+ /** Say something. The reply streams on \`turn({ conversation })\` while this runs. */
153
+ export const send = mutation({
154
+ auth: 'user',
155
+ input: z.object({ conversation: Id, text: z.string().trim().min(1).max(8000) }),
156
+ invalidates: ['agent'],
157
+ run: ({ input, ctx }) => agent.send(ctx, input, (e) => void turns.publish(input.conversation, e).catch(() => {})),
158
+ })
159
+
160
+ /** Approve or decline a call the agent is waiting on; it goes on from there. */
161
+ export const resolveCall = mutation({
162
+ auth: 'user',
163
+ input: z.object({ conversation: Id, call: z.string().min(1).max(200), approve: z.boolean() }),
164
+ invalidates: ['agent'],
165
+ run: ({ input, ctx }) =>
166
+ agent.resolve(ctx, input, (e) => void turns.publish(input.conversation, e).catch(() => {})),
167
+ })
168
+
169
+ /** A conversation's reply as it's written. */
170
+ export const turn = stream({
171
+ auth: 'user',
172
+ input: z.object({ conversation: Id }),
173
+ message: Event,
174
+ async *run({ input, ctx, signal }) {
175
+ await agent.conversation(ctx, input.conversation) // only its owner listens
176
+ for await (const m of turns.subscribe(input.conversation, { signal })) yield m
177
+ },
178
+ })
179
+
180
+ export const usage = query({
181
+ auth: 'user',
182
+ input: z.object({ days: z.int().min(1).max(366).default(30) }),
183
+ tags: ['agent'],
184
+ run: ({ input, ctx }) => agent.usage(ctx, input.days),
185
+ })
186
+
187
+ export const tokens = query({ auth: 'user', tags: ['agent'], run: ({ ctx }) => agent.tokens(ctx) })
188
+
189
+ /** A token for Claude Code, Codex or a script. The secret comes back once: show it, never store it. */
190
+ export const createToken = mutation({
191
+ auth: 'user',
192
+ input: z.object({ name: z.string().max(80), grants: z.array(z.string().max(80)).min(1).max(50) }),
193
+ invalidates: ['agent'],
194
+ run: ({ input, ctx }) => agent.createToken(ctx, input),
195
+ })
196
+
197
+ export const revokeToken = mutation({
198
+ auth: 'user',
199
+ input: z.object({ id: Id }),
200
+ invalidates: ['agent'],
201
+ run: ({ input, ctx }) => agent.revokeToken(ctx, input.id),
202
+ })
203
+ `
204
+
205
+ export const setup = {
206
+ with: [],
207
+ needs: ['auth'],
208
+ run({ engine, layer, read }) {
209
+ const drizzle = layer === 'drizzle'
210
+ return {
211
+ files: {
212
+ 'src/agent.server.ts': server(drizzle),
213
+ 'src/server/agent.ts': functions,
214
+ ...(drizzle && { 'src/db/agent.schema.ts': tables(engine) }),
215
+ },
216
+ edits: {
217
+ ...(drizzle && {
218
+ 'src/db/schema.ts': `${read('src/db/schema.ts').trimEnd()}\n\nexport * from './agent.schema'\n`,
219
+ }),
220
+ },
221
+ env: {},
222
+ next: [
223
+ ...(drizzle
224
+ ? ['`kerf db generate`, then reload: the migration applies on the next request']
225
+ : []),
226
+ "offer a function to the assistant: `agent: { say: 'What it does' }` beside `auth`, and `confirm: true` on one the owner should approve each time",
227
+ 'set ANTHROPIC_API_KEY, or sign in to the `claude` CLI on this machine',
228
+ 'for tokens, give `defineAgent` a `user: (id) => …` that loads the user a token acts as',
229
+ ],
230
+ }
231
+ },
232
+ }
package/src/store.ts ADDED
@@ -0,0 +1,104 @@
1
+ // Where conversations, usage, held calls and tokens live. `drizzleAgentStore` puts them in the app's database; write
2
+ // these methods for any other. `memoryAgentStore` is for dev and tests, and a production server refuses it (AGENT010).
3
+ import type { AgentToken, Conversation, Message, PendingCall, Usage } from './index'
4
+
5
+ /** A token's row: its grants and the hash of its secret. The secret itself is shown once and never stored. */
6
+ export interface TokenRow extends AgentToken {
7
+ hash: string
8
+ }
9
+
10
+ /** Where conversations, usage, held calls and tokens are kept. */
11
+ export interface AgentStore {
12
+ readonly memory?: boolean
13
+ conversations(owner: string, state: Conversation['state']): Promise<Conversation[]>
14
+ conversation(id: string): Promise<Conversation | null>
15
+ saveConversation(c: Conversation): Promise<void>
16
+ /** The conversation, its messages and its held calls. */
17
+ removeConversation(id: string): Promise<void>
18
+ messages(conversation: string): Promise<Message[]>
19
+ addMessage(m: Message): Promise<void>
20
+ addUsage(u: Usage): Promise<void>
21
+ /** Usage since `since` (ms), for one owner's conversations and tokens. */
22
+ usage(owner: string, since: number): Promise<Usage[]>
23
+ pending(conversation: string): Promise<PendingCall[]>
24
+ hold(p: PendingCall): Promise<void>
25
+ /** Takes it off the list: whoever takes it runs or declines it, once. */
26
+ take(id: string): Promise<PendingCall | null>
27
+ tokens(owner: string): Promise<AgentToken[]>
28
+ token(id: string): Promise<TokenRow | null>
29
+ tokenByHash(hash: string): Promise<TokenRow | null>
30
+ saveToken(t: TokenRow): Promise<void>
31
+ }
32
+
33
+ const ok = <T>(v: T) => Promise.resolve(v)
34
+ /** Settled with nothing, whatever the map call returned. */
35
+ const done = (_?: unknown) => Promise.resolve()
36
+
37
+ /** Everything in maps: lost on restart. `clear` empties it. */
38
+ export function memoryAgentStore(): AgentStore & { clear(): void } {
39
+ const conversations = new Map<string, Conversation>()
40
+ const messages = new Map<string, Message[]>()
41
+ const usage: Usage[] = []
42
+ const held = new Map<string, PendingCall>()
43
+ const tokens = new Map<string, TokenRow>()
44
+ const owned = (owner: string) =>
45
+ new Set([...conversations.values()].filter((c) => c.owner === owner).map((c) => c.id))
46
+ return {
47
+ memory: true,
48
+ clear() {
49
+ conversations.clear()
50
+ messages.clear()
51
+ usage.length = 0
52
+ held.clear()
53
+ tokens.clear()
54
+ },
55
+ conversations: (owner, state) =>
56
+ ok(
57
+ [...conversations.values()]
58
+ .filter((c) => c.owner === owner && c.state === state)
59
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.updated - a.updated),
60
+ ),
61
+ conversation: (id) => ok(conversations.get(id) ?? null),
62
+ saveConversation: (c) => done(conversations.set(c.id, { ...c })),
63
+ removeConversation(id) {
64
+ conversations.delete(id)
65
+ messages.delete(id)
66
+ for (const [k, p] of held) if (p.conversation === id) held.delete(k)
67
+ return done()
68
+ },
69
+ messages: (conversation) => ok([...(messages.get(conversation) ?? [])]),
70
+ addMessage: (m) =>
71
+ done(messages.set(m.conversation, [...(messages.get(m.conversation) ?? []), m])),
72
+ addUsage: (u) => done(usage.push(u)),
73
+ usage(owner, since) {
74
+ const mine = owned(owner)
75
+ const theirs = new Set([...tokens.values()].filter((t) => t.owner === owner).map((t) => t.id))
76
+ return ok(
77
+ usage.filter(
78
+ (u) =>
79
+ u.at >= since &&
80
+ ((u.conversation !== null && mine.has(u.conversation)) ||
81
+ (u.token !== null && theirs.has(u.token))),
82
+ ),
83
+ )
84
+ },
85
+ pending: (conversation) =>
86
+ ok([...held.values()].filter((p) => p.conversation === conversation)),
87
+ hold: (p) => done(held.set(p.id, p)),
88
+ take(id) {
89
+ const p = held.get(id) ?? null
90
+ held.delete(id)
91
+ return ok(p)
92
+ },
93
+ tokens: (owner) =>
94
+ ok(
95
+ [...tokens.values()]
96
+ .filter((t) => t.owner === owner)
97
+ .map(({ hash: _, ...t }) => t)
98
+ .sort((a, b) => b.created - a.created),
99
+ ),
100
+ token: (id) => ok(tokens.get(id) ?? null),
101
+ tokenByHash: (hash) => ok([...tokens.values()].find((t) => t.hash === hash) ?? null),
102
+ saveToken: (t) => done(tokens.set(t.id, { ...t })),
103
+ }
104
+ }
package/src/test.ts ADDED
@@ -0,0 +1,42 @@
1
+ // A bridge for tests: it answers from a script instead of a model, so a test can say "the agent calls `setPrice`
2
+ // with this" and check what the app did. Each step takes the next line; an empty script ends every turn.
3
+ import type { Bridge, BridgeTurn } from './bridge'
4
+
5
+ /** One scripted step: words, a call or calls, or a function of the turn that returns one. */
6
+ export type Line =
7
+ | string
8
+ | {
9
+ text?: string
10
+ call?: { tool: string; input?: unknown } | { tool: string; input?: unknown }[]
11
+ }
12
+ | ((turn: BridgeTurn) => Line | Promise<Line>)
13
+
14
+ /** A bridge that answers from `script`, one line per step, and keeps every turn it was handed in `turns`. */
15
+ export function fakeBridge(
16
+ script: Line[],
17
+ options: { id?: string; tools?: 'native' | 'mcp' } = {},
18
+ ): Bridge & {
19
+ turns: BridgeTurn[]
20
+ } {
21
+ const turns: BridgeTurn[] = []
22
+ let n = 0
23
+ return {
24
+ id: options.id ?? 'fake',
25
+ label: 'Script',
26
+ tools: options.tools ?? 'native',
27
+ turns,
28
+ async step(turn) {
29
+ turns.push(turn)
30
+ let line = script.shift() ?? ''
31
+ while (typeof line === 'function') line = await line(turn)
32
+ const { text = '', call } = typeof line === 'string' ? { text: line, call: undefined } : line
33
+ if (text) turn.text(text)
34
+ const calls = (Array.isArray(call) ? call : call ? [call] : []).map((c) => ({
35
+ id: `call-${++n}`,
36
+ tool: c.tool,
37
+ input: c.input ?? {},
38
+ }))
39
+ return { text, calls, usage: { model: 'script', input: text.length, output: text.length } }
40
+ },
41
+ }
42
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,93 @@
1
+ // The tools an agent may see: every query and mutation that opted in with `agent:`, named by export, described by
2
+ // `say` and typed by its input schema. The registry is kerf's own (`fns`), so a new function with `agent:` is a new
3
+ // tool, and nothing else has to know about it.
4
+ import { fns } from '@kerf-js/start/data'
5
+ import { allows, type AgentAccess, type ToolInfo } from './index'
6
+
7
+ type Def = { agent?: boolean | AgentAccess; input?: unknown; tags?: unknown; invalidates?: unknown }
8
+
9
+ /** `getMenuItems.3f9a1c` → `getMenuItems`. */
10
+ const exportName = (id: string) => id.replace(/\.[0-9a-f]{6}$/, '').replace(/[^a-zA-Z0-9_-]/g, '_')
11
+
12
+ /** `getMenuItems` → `get menu items`. */
13
+ const words = (name: string) =>
14
+ name
15
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
16
+ .replace(/[_-]+/g, ' ')
17
+ .toLowerCase()
18
+
19
+ function scopeOf(kind: 'query' | 'mutation', def: Def, name: string) {
20
+ const access = typeof def.agent === 'object' ? def.agent : {}
21
+ if (access.scope) return access.scope
22
+ const tags = kind === 'query' ? def.tags : def.invalidates
23
+ if (Array.isArray(tags) && typeof tags[0] === 'string') return tags[0].split(/[:.]/)[0]!
24
+ return name
25
+ }
26
+
27
+ /** JSON Schema for a Standard Schema input, or an empty object for a function that takes none. */
28
+ function inputSchema(schema: unknown): Record<string, unknown> {
29
+ const s = schema as {
30
+ '~standard'?: { jsonSchema?: { input(o: { target: string }): Record<string, unknown> } }
31
+ toJSONSchema?: () => Record<string, unknown>
32
+ }
33
+ if (!s) return { type: 'object', properties: {} }
34
+ try {
35
+ const json =
36
+ s['~standard']?.jsonSchema?.input({ target: 'draft-2020-12' }) ?? s.toJSONSchema?.()
37
+ if (json) {
38
+ const { $schema: _, ...rest } = json
39
+ return rest.type === 'object' ? rest : { type: 'object', properties: { input: rest } }
40
+ }
41
+ } catch {}
42
+ return { type: 'object', properties: {} }
43
+ }
44
+
45
+ /** Every function offered to agents, with or without a grant. */
46
+ export function allTools(): ToolInfo[] {
47
+ const out: ToolInfo[] = []
48
+ const seen = new Set<string>()
49
+ for (const fn of fns.values()) {
50
+ if (fn.kind !== 'query' && fn.kind !== 'mutation') continue
51
+ const def = fn.def as Def
52
+ if (!def.agent) continue
53
+ let name = exportName(fn.$id)
54
+ // two files exporting the same name: the second gets its hash, so neither shadows the other
55
+ if (seen.has(name)) name = `${name}_${fn.$id.slice(-6)}`
56
+ seen.add(name)
57
+ const access = typeof def.agent === 'object' ? def.agent : {}
58
+ const scope = scopeOf(fn.kind, def, name)
59
+ out.push({
60
+ name,
61
+ id: fn.$id,
62
+ kind: fn.kind,
63
+ permission: `${scope}.${fn.kind === 'query' ? 'read' : 'write'}`,
64
+ confirm: !!access.confirm,
65
+ description: access.say ?? `${fn.kind === 'query' ? 'Read' : 'Change'}: ${words(name)}`,
66
+ input: inputSchema(def.input),
67
+ })
68
+ }
69
+ return out.sort((a, b) => a.name.localeCompare(b.name))
70
+ }
71
+
72
+ /** The tools `grants` allow. */
73
+ export const toolsFor = (grants: readonly string[]) =>
74
+ allTools().filter((t) => allows(grants, t.permission))
75
+
76
+ /** The input wrapper `inputSchema` adds for a non-object schema, taken off again. */
77
+ export function unwrap(tool: ToolInfo, input: unknown) {
78
+ const props = tool.input.properties
79
+ const wrapped = !!props && typeof props === 'object' && Object.keys(props).join() === 'input'
80
+ return wrapped && input && typeof input === 'object' && 'input' in input ? input.input : input
81
+ }
82
+
83
+ /** Every scope a tool names, for the grants editor: `[{ scope: 'menu', read: [...], write: [...] }]`. */
84
+ export function scopes() {
85
+ const by = new Map<string, { scope: string; read: string[]; write: string[] }>()
86
+ for (const t of allTools()) {
87
+ const [scope = '', action] = t.permission.split('.')
88
+ const s = by.get(scope) ?? { scope, read: [], write: [] }
89
+ ;(action === 'read' ? s.read : s.write).push(t.name)
90
+ by.set(scope, s)
91
+ }
92
+ return [...by.values()].sort((a, b) => a.scope.localeCompare(b.scope))
93
+ }