Something went wrong. Try again.
Open source agent hosting on the AT Protocol
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161// The xrpc tool: model-written JavaScript run in pi's QuickJS sandbox (@earendil-works/pi-codemode),// where the only capability is calling the XRPC methods the agent's policy lets it see.//// Each call is checked against the policy before its handler runs, and recorded. The sandbox has no// fetch, timers, modules or process, so a script reaches nothing but these methods.
import { CodemodeSandbox, renderDeclarations, toCodemodeIdentifier, type CodemodeTool } from '@earendil-works/pi-codemode'import { METHODS, type Method } from './methods.ts'import { decide, visible, type Policy, type PolicyRequest } from './policy.ts'import type { NestedCall } from './records.ts'import type { AgentStore } from './store.ts'
const TIMEOUT_MS = 60_000/** A policy that can ask the owner gives scripts long enough to wait for an answer (runs wait 10 minutes). */const TIMEOUT_ASKING_MS = 11 * 60_000const MEMORY_LIMIT = 64 * 1024 * 1024/** Script output beyond this is cut off, to keep one call from filling the context. */export const MAX_SCRIPT_OUTPUT = 30_000const MAX_RECORDED_ARGS = 2000
/** The methods an agent's policy shows it, in registry order. */export function visibleMethods(policy: Policy): Method[] { return METHODS.filter((m) => visible(policy, m.nsid, m.shape))}
/** The `<xrpc>` part of the system prompt. Depends only on the policy, so it stays put between turns. */export function renderXrpcContext(policy: Policy, collections: Record<string, string>): string { const methods = visibleMethods(policy) if (!methods.length) return '<xrpc>\nYour policy allows no XRPC methods.\n</xrpc>' const lines = [ '<xrpc>', 'Methods you can call from the xrpc tool, as tools.<NSID with dots as underscores>(args). `await describeTool(name)` shows one\'s full type.', ] for (const m of methods) lines.push(`- ${m.nsid} (${m.kind}): ${m.description}`) const listable = Object.entries(collections).filter(([c]) => decide(policy, { method: 'com.atproto.repo.listRecords', repo: 'self', collection: c, write: false }).effect === 'allow') if (listable.length && methods.some((m) => m.nsid.startsWith('com.atproto.repo.'))) { lines.push('Collections in your space (omit `repo` to read them):') for (const [c, what] of listable) lines.push(`- ${c}: ${what}`) } lines.push('</xrpc>') return lines.join('\n')}
/** What a call asking for approval would do, in words for the owner: "create app.bsky.feed.post/3abc in its public repo". */export function describeCall(req: PolicyRequest): string { const verbs: Record<string, string> = { 'com.atproto.repo.createRecord': 'create', 'com.atproto.repo.putRecord': 'write', 'com.atproto.repo.deleteRecord': 'delete' } const what = req.collection ? `${req.collection}${req.rkey ? `/${req.rkey}` : ''}` : '' const verb = verbs[req.method] if (!verb) return `call ${req.method}${what ? ` on ${what}` : ''}` return `${verb} a ${what} record in ${req.repo === 'self' ? 'its own space' : 'its public repo'}`}
function sandboxTool(m: Method, store: AgentStore, policy: Policy, calls: NestedCall[], turn: Set<string> | undefined, signal: AbortSignal | undefined, callId: string | undefined, asked: { n: number }): CodemodeTool { const allowed = (req: PolicyRequest) => decide(policy, req).effect === 'allow' return { name: m.nsid, description: m.description, inputSchema: m.input, outputSchema: m.output, async execute(args, ctx) { const started = Date.now() const call: NestedCall = { method: m.nsid, argumentsJson: clip(JSON.stringify(args ?? {}), MAX_RECORDED_ARGS), status: 'ok', durationMs: 0 } calls.push(call) const finish = (status: NestedCall['status'], error?: string) => { call.status = status call.durationMs = Math.round(Date.now() - started) if (error) call.error = clip(error, 500) } let req: PolicyRequest try { req = { method: m.nsid, ...m.target(args ?? {}, { did: store.entry.agent.did, handle: store.entry.agent.handle }) } } catch (e: any) { finish('error', e.message) throw e } const d = m.perCollection && req.collection === undefined ? { effect: 'allow' as const, reason: '' } : decide(policy, req) if (d.effect === 'deny') { finish('denied', d.reason) throw new Error(`denied: ${d.reason}`) } if (d.effect === 'approve') { const ok = await store.approveScriptCall(callId, ++asked.n, m.nsid, describeCall(req), args) if (ok !== true) { const why = `${d.reason}; not approved: ${ok}` finish('denied', why) throw new Error(`denied: ${why}`) } } try { const value = await m.run(args ?? {}, { store, allowed, turn, signal: signal ? AbortSignal.any([signal, ctx.signal]) : ctx.signal }) finish('ok') return value } catch (e: any) { finish('error', e?.message ?? String(e)) throw e } }, }}
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s)
export interface ScriptOutcome { text: string isError: boolean calls: NestedCall[] /** What the script returned, if it finished. */ value?: unknown}
/** * Run one script of the xrpc tool for an agent. `turn` is the records of the turn it runs in * ("collection/rkey"), which search leaves out. `callId` is the xrpc call's, for asking the owner * about method calls the policy says to approve. */export async function runScript(store: AgentStore, code: unknown, signal?: AbortSignal, turn?: Set<string>, callId?: string, policy: Policy = store.policy()): Promise<ScriptOutcome> { if (typeof code !== 'string' || !code.trim()) return { text: 'code is required: the body of an async JavaScript function', isError: true, calls: [] } const calls: NestedCall[] = [] const asked = { n: 0 } const tools = visibleMethods(policy).map((m) => sandboxTool(m, store, policy, calls, turn, signal, callId, asked)) const find = (name: unknown) => tools.find((t) => t.name === name || toCodemodeIdentifier(t.name) === name) const globals: CodemodeTool[] = [ { name: 'describeTool', description: "A method's TypeScript declaration, by NSID or by its name on `tools`.", async execute(name) { const t = find(name) if (!t) throw new Error(`no method ${JSON.stringify(name)}; ALL_TOOLS lists them`) const kind = METHODS.find((m) => m.nsid === t.name)!.kind return `// ${t.name} (${kind}): tools.${toCodemodeIdentifier(t.name)}(args)\n${renderDeclarations({ tools: [t] })}` }, }, { name: 'searchTools', description: 'Methods whose NSID or description contains every word of the query.', async execute(query) { const words = String(query ?? '').toLowerCase().split(/\s+/).filter(Boolean) return tools .filter((t) => words.every((w) => `${t.name} ${t.description}`.toLowerCase().includes(w))) .map((t) => ({ nsid: t.name, name: toCodemodeIdentifier(t.name), description: t.description })) }, }, ]
const sandbox = new CodemodeSandbox({ tools, globals, timeoutMs: policy.rules.some((r) => r.effect === 'approve') ? TIMEOUT_ASKING_MS : TIMEOUT_MS, memoryLimitBytes: MEMORY_LIMIT }) try { const r = await sandbox.execute(code, { signal }) const parts = r.output.map((o) => (o.type === 'text' ? o.text : '[image]')) if (r.ok && r.value !== undefined) parts.push(JSON.stringify(r.value)) if (!r.ok) parts.push(`${r.error.kind} error: ${r.error.stack ?? r.error.message}`) let text = parts.join('\n') if (!text) text = '(no output: use text(value) or return a value)' if (text.length > MAX_SCRIPT_OUTPUT) { text = `${text.slice(0, MAX_SCRIPT_OUTPUT)}\n… [${text.length - MAX_SCRIPT_OUTPUT} more chars cut; return less, or page with limit and cursor]` } return { text, isError: !r.ok, calls, value: r.ok ? r.value : undefined } } finally { await sandbox.close() }}