@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 +16 -0
- package/README.md +63 -2
- package/docs/agent.md +187 -0
- package/package.json +62 -3
- package/plugin.d.mts +5 -0
- package/plugin.mjs +134 -0
- package/src/bridge.ts +71 -0
- package/src/bridges/anthropic.ts +168 -0
- package/src/bridges/cli.ts +152 -0
- package/src/bridges/fn.ts +105 -0
- package/src/bridges/rust.ts +188 -0
- package/src/drizzle.ts +228 -0
- package/src/index.ts +154 -0
- package/src/mcp.ts +93 -0
- package/src/server/conversations.ts +131 -0
- package/src/server/core.ts +92 -0
- package/src/server/extension.ts +115 -0
- package/src/server/run.ts +204 -0
- package/src/server/tokens.ts +119 -0
- package/src/server.ts +45 -0
- package/src/setup.mjs +232 -0
- package/src/store.ts +104 -0
- package/src/test.ts +42 -0
- package/src/tools.ts +93 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// The `server.extension@1` half: who a bearer token is, the guard every function call passes, and the MCP endpoint.
|
|
2
|
+
// The guard is the point: a tool call runs as the signed-in person, through their `auth`, and then must also be a
|
|
3
|
+
// function that opted in with `agent:` and one the grant allows. A person's own calls are never touched.
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import type { Context } from '@kerf-js/start'
|
|
6
|
+
import type { ExtensionApi, ServerExtension } from '@kerf-js/start/extension'
|
|
7
|
+
import { allows } from '../index'
|
|
8
|
+
import { serveMcp } from '../mcp'
|
|
9
|
+
import { allTools, toolsFor } from '../tools'
|
|
10
|
+
import { AgentError, acting, liveTurns, type Core } from './core'
|
|
11
|
+
import { decide, runTool, type Call, type Result } from './run'
|
|
12
|
+
import { bearer } from './tokens'
|
|
13
|
+
|
|
14
|
+
/** Checked, held or run: what an MCP call comes to. */
|
|
15
|
+
async function outcome(
|
|
16
|
+
core: Core,
|
|
17
|
+
ctx: Context,
|
|
18
|
+
call: ExtensionApi['call'],
|
|
19
|
+
{ id, tool: name, input }: Call,
|
|
20
|
+
): Promise<Result> {
|
|
21
|
+
const caller = ctx.agent!
|
|
22
|
+
const tool = allTools().find((t) => t.name === name)
|
|
23
|
+
if (!tool) return { status: 'error', output: `There's no tool called ${name}` }
|
|
24
|
+
if (!allows(caller.grants, tool.permission))
|
|
25
|
+
return { status: 'refused', output: `Not allowed: this needs ${tool.permission}` }
|
|
26
|
+
if (tool.confirm && caller.via.kind === 'token')
|
|
27
|
+
return { status: 'refused', output: 'This one needs the owner to approve it in the app' }
|
|
28
|
+
if (!tool.confirm) return runTool(tool, input, caller, call)
|
|
29
|
+
const c = await core.store.conversation(caller.via.id)
|
|
30
|
+
return c
|
|
31
|
+
? decide(core, c, { id, tool: name, input }, caller)
|
|
32
|
+
: { status: 'error', output: 'The conversation is gone' }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** An MCP tool call, recorded on the turn it belongs to or as a token's usage. */
|
|
36
|
+
async function mcpCall(
|
|
37
|
+
core: Core,
|
|
38
|
+
ctx: Context,
|
|
39
|
+
call: ExtensionApi['call'],
|
|
40
|
+
name: string,
|
|
41
|
+
input: unknown,
|
|
42
|
+
) {
|
|
43
|
+
const caller = ctx.agent!
|
|
44
|
+
const live = caller.via.kind === 'conversation' ? liveTurns.get(caller.via.id) : undefined
|
|
45
|
+
const id = randomUUID()
|
|
46
|
+
live?.reply.parts.push({ type: 'call', id, tool: name, input })
|
|
47
|
+
live?.emit({ type: 'call', id, tool: name, input })
|
|
48
|
+
const result = await outcome(core, ctx, call, { id, tool: name, input })
|
|
49
|
+
live?.reply.parts.push({ type: 'result', id, tool: name, ...result })
|
|
50
|
+
live?.emit({ type: 'result', id, tool: name, status: result.status })
|
|
51
|
+
if (caller.via.kind === 'token')
|
|
52
|
+
await core.store.addUsage({
|
|
53
|
+
conversation: null,
|
|
54
|
+
token: caller.via.id,
|
|
55
|
+
bridge: 'mcp',
|
|
56
|
+
model: 'external',
|
|
57
|
+
input: 0,
|
|
58
|
+
output: 0,
|
|
59
|
+
calls: 1,
|
|
60
|
+
ms: 0,
|
|
61
|
+
at: Date.now(),
|
|
62
|
+
})
|
|
63
|
+
return result
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The guard: inside a tool call, the outermost function must be offered and granted. It reads no `ctx`: a cached query's
|
|
68
|
+
* ctx refuses personal fields (Q006), and an agent only gets one on the MCP endpoint, where every call runs under `acting`.
|
|
69
|
+
*/
|
|
70
|
+
function guard(fn: { id: string }) {
|
|
71
|
+
const a = acting.getStore()
|
|
72
|
+
if (!a || a.checked) return
|
|
73
|
+
a.checked = true
|
|
74
|
+
const tool = allTools().find((t) => t.id === fn.id)
|
|
75
|
+
if (!tool)
|
|
76
|
+
throw new AgentError('AGENT008', `\`${fn.id}\` isn't offered to agents: add \`agent:\` to it`)
|
|
77
|
+
if (!allows(a.caller.grants, tool.permission))
|
|
78
|
+
throw new AgentError('AGENT009', `Not allowed: this needs ${tool.permission}`)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** The extension `defineAgent` hands kerf. */
|
|
82
|
+
export function agentExtension(core: Core): ServerExtension {
|
|
83
|
+
return {
|
|
84
|
+
options: ['agent'],
|
|
85
|
+
personal: ['agent'],
|
|
86
|
+
context: (ctx) => bearer(core, ctx),
|
|
87
|
+
guard,
|
|
88
|
+
async handle(request, path, ext) {
|
|
89
|
+
const [head, which, ...rest] = path.split('/')
|
|
90
|
+
if (head === 'bridges') {
|
|
91
|
+
const b = core.options.bridges.find((x) => x.id === which && x.serve)
|
|
92
|
+
return b ? b.serve!(request, rest.join('/')) : new Response('Not found', { status: 404 })
|
|
93
|
+
}
|
|
94
|
+
if (path !== 'mcp') return new Response('Not found', { status: 404 })
|
|
95
|
+
const ctx = await ext.ctx()
|
|
96
|
+
if (!ctx.agent)
|
|
97
|
+
return new Response('A bearer token is required', {
|
|
98
|
+
status: 401,
|
|
99
|
+
headers: { 'www-authenticate': 'Bearer' },
|
|
100
|
+
})
|
|
101
|
+
return serveMcp(request, {
|
|
102
|
+
tools: () => toolsFor(ctx.agent!.grants),
|
|
103
|
+
call: (name, input) => mcpCall(core, ctx, (id, i) => ext.call(id, i), name, input),
|
|
104
|
+
})
|
|
105
|
+
},
|
|
106
|
+
check(dev) {
|
|
107
|
+
if (!dev && core.store.memory)
|
|
108
|
+
throw new AgentError(
|
|
109
|
+
'AGENT010',
|
|
110
|
+
'`memoryAgentStore()` on a production server: conversations would vanish on restart',
|
|
111
|
+
500,
|
|
112
|
+
)
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// A turn: the bridge writes, asks for tools, gets their results and writes again, until it's done, a call waits for
|
|
2
|
+
// the owner, or it runs out of steps. Every step's usage is recorded; the reply is saved as one message.
|
|
3
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
4
|
+
import { serverCall, type Context } from '@kerf-js/start'
|
|
5
|
+
import type { Bridge } from '../bridge'
|
|
6
|
+
import {
|
|
7
|
+
allows,
|
|
8
|
+
type AgentCaller,
|
|
9
|
+
type Conversation,
|
|
10
|
+
type Message,
|
|
11
|
+
type Part,
|
|
12
|
+
type ToolInfo,
|
|
13
|
+
type TurnEvent,
|
|
14
|
+
} from '../index'
|
|
15
|
+
import { allTools, toolsFor, unwrap } from '../tools'
|
|
16
|
+
import { AgentError, MCP, acting, liveTurns, turnTokens, userOf, type Core } from './core'
|
|
17
|
+
|
|
18
|
+
export type Result = { status: Extract<Part, { type: 'result' }>['status']; output: unknown }
|
|
19
|
+
/** A tool call as a bridge asks for it. */
|
|
20
|
+
export type Call = { id: string; tool: string; input: unknown }
|
|
21
|
+
|
|
22
|
+
type Failed = {
|
|
23
|
+
answer?: { message?: string }
|
|
24
|
+
data?: { message?: unknown }
|
|
25
|
+
issues?: { path?: readonly unknown[]; message: string }[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** What went wrong, in words the agent can act on: a declared error's message, or each input issue by its path. */
|
|
29
|
+
export function failure(e: unknown): string {
|
|
30
|
+
const f = (e ?? {}) as Failed
|
|
31
|
+
if (f.answer?.message) return f.answer.message
|
|
32
|
+
if (typeof f.data?.message === 'string') return f.data.message
|
|
33
|
+
if (f.issues?.length) {
|
|
34
|
+
const key = (p: unknown) => String(typeof p === 'object' && p ? (p as { key: unknown }).key : p)
|
|
35
|
+
return `Fix the input: ${f.issues.map((i) => `${(i.path ?? []).map(key).join('.') || 'input'}: ${i.message}`).join('; ')}`
|
|
36
|
+
}
|
|
37
|
+
return e instanceof Error ? e.message : String(e)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Run one tool as the signed-in caller, checked against `caller`'s grants by the guard. */
|
|
41
|
+
export async function runTool(
|
|
42
|
+
tool: ToolInfo,
|
|
43
|
+
input: unknown,
|
|
44
|
+
caller: AgentCaller,
|
|
45
|
+
call = serverCall,
|
|
46
|
+
): Promise<Result> {
|
|
47
|
+
try {
|
|
48
|
+
const output = await acting.run({ caller, checked: false }, () =>
|
|
49
|
+
call(tool.id, unwrap(tool, input)),
|
|
50
|
+
)
|
|
51
|
+
return { status: 'ok', output: output ?? null }
|
|
52
|
+
} catch (e) {
|
|
53
|
+
return { status: 'error', output: failure(e) }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Whether a call runs now, waits for the owner, or is refused, and its result. */
|
|
58
|
+
export async function decide(
|
|
59
|
+
core: Core,
|
|
60
|
+
c: Conversation,
|
|
61
|
+
call: Call,
|
|
62
|
+
caller: AgentCaller,
|
|
63
|
+
): Promise<Result> {
|
|
64
|
+
const tool = allTools().find((t) => t.name === call.tool)
|
|
65
|
+
if (!tool) return { status: 'error', output: `There's no tool called ${call.tool}` }
|
|
66
|
+
if (!allows(caller.grants, tool.permission))
|
|
67
|
+
return { status: 'refused', output: `Not allowed: this needs ${tool.permission}` }
|
|
68
|
+
if (tool.confirm) {
|
|
69
|
+
await core.store.hold({
|
|
70
|
+
id: call.id,
|
|
71
|
+
conversation: c.id,
|
|
72
|
+
tool: tool.name,
|
|
73
|
+
input: call.input,
|
|
74
|
+
at: Date.now(),
|
|
75
|
+
})
|
|
76
|
+
return { status: 'waiting', output: 'Waiting for the owner to approve this' }
|
|
77
|
+
}
|
|
78
|
+
return runTool(tool, call.input, caller)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A token and a live reply for a bridge that calls tools over MCP; `end` takes both down. */
|
|
82
|
+
function openMcp(
|
|
83
|
+
ctx: Context,
|
|
84
|
+
c: Conversation,
|
|
85
|
+
caller: AgentCaller,
|
|
86
|
+
reply: Message,
|
|
87
|
+
emit: (e: TurnEvent) => void,
|
|
88
|
+
) {
|
|
89
|
+
const token = `wt_${randomBytes(24).toString('base64url')}`
|
|
90
|
+
turnTokens.set(token, {
|
|
91
|
+
conversation: c.id,
|
|
92
|
+
user: userOf(ctx),
|
|
93
|
+
grants: [...caller.grants],
|
|
94
|
+
expires: Date.now() + 15 * 60_000,
|
|
95
|
+
})
|
|
96
|
+
liveTurns.set(c.id, { reply, emit })
|
|
97
|
+
return {
|
|
98
|
+
mcp: { url: new URL(MCP, ctx.request.url).href, token },
|
|
99
|
+
end() {
|
|
100
|
+
turnTokens.delete(token)
|
|
101
|
+
liveTurns.delete(c.id)
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** What a turn carries from step to step. */
|
|
107
|
+
type Turning = {
|
|
108
|
+
c: Conversation
|
|
109
|
+
caller: AgentCaller
|
|
110
|
+
reply: Message
|
|
111
|
+
emit: (e: TurnEvent) => void
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Run a step's calls in order, recording each; true when one waits for the owner. */
|
|
115
|
+
async function runCalls(core: Core, calls: Call[], t: Turning) {
|
|
116
|
+
const { c, caller, reply, emit } = t
|
|
117
|
+
let waiting = false
|
|
118
|
+
for (const call of calls) {
|
|
119
|
+
reply.parts.push({ type: 'call', ...call })
|
|
120
|
+
emit({ type: 'call', ...call })
|
|
121
|
+
const result = await decide(core, c, call, caller)
|
|
122
|
+
if (result.status === 'waiting') waiting = true
|
|
123
|
+
reply.parts.push({ type: 'result', id: call.id, tool: call.tool, ...result })
|
|
124
|
+
emit({ type: 'result', id: call.id, tool: call.tool, status: result.status })
|
|
125
|
+
}
|
|
126
|
+
return waiting
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** One step: the bridge's answer, kept on the reply, and its usage recorded. */
|
|
130
|
+
async function oneStep(
|
|
131
|
+
core: Core,
|
|
132
|
+
b: Bridge,
|
|
133
|
+
c: Conversation,
|
|
134
|
+
ask: Parameters<Bridge['step']>[0],
|
|
135
|
+
reply: Message,
|
|
136
|
+
) {
|
|
137
|
+
const started = Date.now()
|
|
138
|
+
const out = await b.step(ask)
|
|
139
|
+
if (out.raw !== undefined) reply.parts.push({ type: 'native', bridge: b.id, content: out.raw })
|
|
140
|
+
if (out.text) reply.parts.push({ type: 'text', text: out.text })
|
|
141
|
+
await core.store.addUsage({
|
|
142
|
+
conversation: c.id,
|
|
143
|
+
token: null,
|
|
144
|
+
bridge: b.id,
|
|
145
|
+
model: out.usage.model,
|
|
146
|
+
input: out.usage.input,
|
|
147
|
+
output: out.usage.output,
|
|
148
|
+
calls: out.calls.length,
|
|
149
|
+
ms: Date.now() - started,
|
|
150
|
+
at: Date.now(),
|
|
151
|
+
})
|
|
152
|
+
return out.calls
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Run a turn on `c` to its end, emitting the reply as it's written; saves the reply and returns it. */
|
|
156
|
+
export async function turn(
|
|
157
|
+
core: Core,
|
|
158
|
+
ctx: Context,
|
|
159
|
+
c: Conversation,
|
|
160
|
+
emit: (e: TurnEvent) => void,
|
|
161
|
+
signal: AbortSignal,
|
|
162
|
+
) {
|
|
163
|
+
const grants = core.grantsOf(userOf(ctx))
|
|
164
|
+
const caller: AgentCaller = { via: { kind: 'conversation', id: c.id }, grants }
|
|
165
|
+
const b = core.bridge(c.bridge)
|
|
166
|
+
if (!b) throw new AgentError('AGENT003', 'No assistant is set up to answer', 503)
|
|
167
|
+
const { system: sys } = core.options
|
|
168
|
+
const system = typeof sys === 'function' ? await sys(ctx) : sys
|
|
169
|
+
const history = await core.store.messages(c.id)
|
|
170
|
+
const reply: Message = {
|
|
171
|
+
id: randomUUID(),
|
|
172
|
+
conversation: c.id,
|
|
173
|
+
role: 'assistant',
|
|
174
|
+
parts: [],
|
|
175
|
+
at: Date.now(),
|
|
176
|
+
}
|
|
177
|
+
const live = b.tools === 'mcp' ? openMcp(ctx, c, caller, reply, emit) : undefined
|
|
178
|
+
try {
|
|
179
|
+
for (let n = 0; n < core.steps; n++) {
|
|
180
|
+
const calls = await oneStep(
|
|
181
|
+
core,
|
|
182
|
+
b,
|
|
183
|
+
c,
|
|
184
|
+
{
|
|
185
|
+
system,
|
|
186
|
+
messages: [...history, ...(reply.parts.length ? [reply] : [])],
|
|
187
|
+
tools: toolsFor(grants),
|
|
188
|
+
signal,
|
|
189
|
+
who: c.owner,
|
|
190
|
+
text: (delta) => emit({ type: 'text', delta }),
|
|
191
|
+
...(live && { mcp: live.mcp }),
|
|
192
|
+
},
|
|
193
|
+
reply,
|
|
194
|
+
)
|
|
195
|
+
if (!calls.length || (await runCalls(core, calls, { c, caller, reply, emit }))) break
|
|
196
|
+
}
|
|
197
|
+
} finally {
|
|
198
|
+
live?.end()
|
|
199
|
+
}
|
|
200
|
+
await core.store.addMessage(reply)
|
|
201
|
+
await core.store.saveConversation({ ...c, updated: Date.now() })
|
|
202
|
+
emit({ type: 'done', message: reply.id })
|
|
203
|
+
return reply
|
|
204
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Tokens for agents outside the app, and what a person's agent has spent. A token never grants more than its creator
|
|
2
|
+
// holds, then or now.
|
|
3
|
+
import { randomBytes, randomUUID } from 'node:crypto'
|
|
4
|
+
import type { Context } from '@kerf-js/start'
|
|
5
|
+
import { allows, type AgentCaller, type AgentToken, type Usage } from '../index'
|
|
6
|
+
import { AgentError, MCP, hash, turnTokens, userOf, type Core, type User } from './core'
|
|
7
|
+
|
|
8
|
+
/** The grants of `wanted` that `held` covers. */
|
|
9
|
+
const within = (held: string[], wanted: string[]) =>
|
|
10
|
+
wanted.filter(
|
|
11
|
+
(g) =>
|
|
12
|
+
held.includes('*') ||
|
|
13
|
+
held.includes(g) ||
|
|
14
|
+
(!g.includes('*') && allows(held, g.includes('.') ? g : `${g}.write`)),
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
type Total = {
|
|
18
|
+
bridge: string
|
|
19
|
+
model: string
|
|
20
|
+
input: number
|
|
21
|
+
output: number
|
|
22
|
+
calls: number
|
|
23
|
+
turns: number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Rows summed by bridge and model. */
|
|
27
|
+
function totals(rows: Usage[]): Total[] {
|
|
28
|
+
const by = new Map<string, Total>()
|
|
29
|
+
for (const r of rows) {
|
|
30
|
+
const k = `${r.bridge}:${r.model}`
|
|
31
|
+
const t = by.get(k) ?? {
|
|
32
|
+
bridge: r.bridge,
|
|
33
|
+
model: r.model,
|
|
34
|
+
input: 0,
|
|
35
|
+
output: 0,
|
|
36
|
+
calls: 0,
|
|
37
|
+
turns: 0,
|
|
38
|
+
}
|
|
39
|
+
t.input += r.input
|
|
40
|
+
t.output += r.output
|
|
41
|
+
t.calls += r.calls
|
|
42
|
+
t.turns++
|
|
43
|
+
by.set(k, t)
|
|
44
|
+
}
|
|
45
|
+
return [...by.values()]
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The usage and token methods of a `defineAgent` result. */
|
|
49
|
+
export function tokenApi(core: Core) {
|
|
50
|
+
const { store } = core
|
|
51
|
+
return {
|
|
52
|
+
/** Usage since `days` ago: rows, and totals by bridge and model. */
|
|
53
|
+
async usage(ctx: Context, days = 30) {
|
|
54
|
+
const rows = await store.usage(userOf(ctx).id, Date.now() - days * 86_400_000)
|
|
55
|
+
return { rows, totals: totals(rows) }
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
tokens: (ctx: Context) => store.tokens(userOf(ctx).id),
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A token for an agent outside the app. Its grants can't exceed the creator's. The secret is returned this once:
|
|
62
|
+
* give it to Claude Code, Codex or a script as `Authorization: Bearer <secret>` on `/_kerf/x/agent/mcp`.
|
|
63
|
+
*/
|
|
64
|
+
async createToken(ctx: Context, input: { name: string; grants: string[] }) {
|
|
65
|
+
const u = userOf(ctx)
|
|
66
|
+
const grants = within(core.grantsOf(u), input.grants)
|
|
67
|
+
if (!grants.length)
|
|
68
|
+
throw new AgentError(
|
|
69
|
+
'AGENT006',
|
|
70
|
+
'Give the token at least one thing you can do yourself',
|
|
71
|
+
422,
|
|
72
|
+
)
|
|
73
|
+
const secret = `wa_${randomBytes(32).toString('base64url')}`
|
|
74
|
+
const token: AgentToken = {
|
|
75
|
+
id: randomUUID(),
|
|
76
|
+
name: input.name.trim() || 'Token',
|
|
77
|
+
owner: u.id,
|
|
78
|
+
grants,
|
|
79
|
+
created: Date.now(),
|
|
80
|
+
used: null,
|
|
81
|
+
revoked: false,
|
|
82
|
+
}
|
|
83
|
+
await store.saveToken({ ...token, hash: hash(secret) })
|
|
84
|
+
return { token, secret }
|
|
85
|
+
},
|
|
86
|
+
|
|
87
|
+
async revokeToken(ctx: Context, id: string) {
|
|
88
|
+
const row = await store.token(id)
|
|
89
|
+
if (!row || row.owner !== userOf(ctx).id)
|
|
90
|
+
throw new AgentError('AGENT002', 'No such token', 404)
|
|
91
|
+
await store.saveToken({ ...row, revoked: true })
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The caller behind a bearer token on the MCP endpoint: a turn's, or an API token's. */
|
|
97
|
+
export async function bearer(core: Core, ctx: Context): Promise<object> {
|
|
98
|
+
const secret = /^Bearer\s+(\S+)$/i.exec(ctx.request.headers.get('authorization') ?? '')?.[1]
|
|
99
|
+
if (!secret) return {}
|
|
100
|
+
if (!new URL(ctx.request.url).pathname.startsWith(MCP)) {
|
|
101
|
+
// an agent's token anywhere else would be ignored and the call made as nobody: say where it goes instead
|
|
102
|
+
if (/^w[at]_/.test(secret)) throw new AgentError('AGENT007', `Agents call tools through ${MCP}`)
|
|
103
|
+
return {}
|
|
104
|
+
}
|
|
105
|
+
const t = turnTokens.get(secret)
|
|
106
|
+
if (t && t.expires > Date.now())
|
|
107
|
+
return {
|
|
108
|
+
user: t.user,
|
|
109
|
+
agent: { via: { kind: 'conversation', id: t.conversation }, grants: t.grants },
|
|
110
|
+
}
|
|
111
|
+
const row = await core.store.tokenByHash(hash(secret))
|
|
112
|
+
if (!row || row.revoked || !core.options.user) return { user: null }
|
|
113
|
+
const user = await core.options.user(row.owner, ctx)
|
|
114
|
+
if (!user) return { user: null }
|
|
115
|
+
void core.store.saveToken({ ...row, used: Date.now() })
|
|
116
|
+
// never more than the owner can grant now: a demoted owner's old token shrinks with them
|
|
117
|
+
const grants = within(core.grantsOf(user as User), row.grants)
|
|
118
|
+
return { user, agent: { via: { kind: 'token', id: row.id }, grants } satisfies AgentCaller }
|
|
119
|
+
}
|
package/src/server.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// The server half. `src/agent.server.ts` default-exports `defineAgent({ … })`: that turns the extension on, and
|
|
2
|
+
// `src/server/agent.ts` (which `kerf add agent` writes) wraps its methods as the app's own queries and mutations, so the
|
|
3
|
+
// pages get caching, invalidation and live updates like any other data.
|
|
4
|
+
import type { Context } from '@kerf-js/start'
|
|
5
|
+
import type { ServerExtension } from '@kerf-js/start/extension'
|
|
6
|
+
import { scopes, toolsFor } from './tools'
|
|
7
|
+
import { conversationApi, turnApi } from './server/conversations'
|
|
8
|
+
import { makeCore, userOf, type AgentOptions } from './server/core'
|
|
9
|
+
import { agentExtension } from './server/extension'
|
|
10
|
+
import { tokenApi } from './server/tokens'
|
|
11
|
+
|
|
12
|
+
export type { Bridge, BridgeStep, BridgeTurn } from './bridge'
|
|
13
|
+
export { transcript } from './bridge'
|
|
14
|
+
export { memoryAgentStore, type AgentStore, type TokenRow } from './store'
|
|
15
|
+
export { allTools, scopes, toolsFor } from './tools'
|
|
16
|
+
export { AgentError, agentCaller, type AgentOptions } from './server/core'
|
|
17
|
+
|
|
18
|
+
/** The app's assistant: conversations, turns, tokens and usage, as methods `src/server/agent.ts` wraps, plus the extension. */
|
|
19
|
+
export function defineAgent(options: AgentOptions) {
|
|
20
|
+
const core = makeCore(options)
|
|
21
|
+
return {
|
|
22
|
+
options,
|
|
23
|
+
/** What this person may let the agent do. */
|
|
24
|
+
grants: (ctx: Context) => core.grantsOf(userOf(ctx)),
|
|
25
|
+
/** The tools this person's agent can see. */
|
|
26
|
+
tools: (ctx: Context) => toolsFor(core.grantsOf(userOf(ctx))),
|
|
27
|
+
/** Every scope a tool names: the grants editor's rows. */
|
|
28
|
+
scopes,
|
|
29
|
+
/** The bridges that can answer here, for the picker. */
|
|
30
|
+
bridges: () => core.usable().map((b) => ({ id: b.id, label: b.label })),
|
|
31
|
+
...conversationApi(core),
|
|
32
|
+
...turnApi(core),
|
|
33
|
+
...tokenApi(core),
|
|
34
|
+
extension: agentExtension(core),
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** What `defineAgent` returns. */
|
|
39
|
+
export type Agent = ReturnType<typeof defineAgent>
|
|
40
|
+
|
|
41
|
+
/** The `server.extension@1` provider: `src/agent.server.ts` default-exports `defineAgent(...)`. */
|
|
42
|
+
export const extension = (app: Agent): ServerExtension => app.extension
|
|
43
|
+
|
|
44
|
+
/** The extension's key: its routes live under `/_kerf/x/agent/`. */
|
|
45
|
+
export const key = 'agent'
|