import type {CallResult} from './types' export const METHOD_DEFS = [ { fq: 'agent.app.bsky.graph.muteActor', doc: 'Mute an account by DID.', inputType: 'MuteActorInput', input: `interface MuteActorInput {\n actor: Did\n}`, signature: `muteActor(input: MuteActorInput): Promise`, }, { fq: 'agent.app.bsky.graph.unmuteActor', doc: 'Undo a previous account mute by DID.', inputType: 'UnmuteActorInput', input: `interface UnmuteActorInput {\n actor: Did\n}`, signature: `unmuteActor(input: UnmuteActorInput): Promise`, }, { fq: 'agent.app.bsky.graph.blockActor', doc: 'Block an account by DID. Blocks are public atproto records.', inputType: 'BlockActorInput', input: `interface BlockActorInput {\n actor: Did\n}`, signature: `blockActor(input: BlockActorInput): Promise`, }, { fq: 'agent.app.bsky.graph.unblockActor', doc: 'Undo a previous account block by DID.', inputType: 'UnblockActorInput', input: `interface UnblockActorInput {\n actor: Did\n}`, signature: `unblockActor(input: UnblockActorInput): Promise`, }, { fq: 'agent.app.bsky.notification.putActivitySubscription', doc: 'Change activity-subscription settings for one actor DID.', inputType: 'PutActivitySubscriptionInput', input: [ 'interface PutActivitySubscriptionInput {', ' subject: Did', ' activitySubscription: {', ' post: boolean', ' reply: boolean', ' }', '}', ].join('\n'), signature: `putActivitySubscription(input: PutActivitySubscriptionInput): Promise`, }, { fq: 'agent.app.bsky.notification.updateSeen', doc: 'Advance the global notification seen cursor.', inputType: 'UpdateSeenInput', input: `interface UpdateSeenInput {\n seenAt: string\n}`, signature: `updateSeen(input: UpdateSeenInput): Promise`, }, ] as const const ALLOWED_METHODS = METHOD_DEFS.map(def => def.fq) export class CodeValidationError extends Error {} export const SDK_SURFACE = [ 'type Did = string', '', 'interface EvidenceNotification {', ' uri: string', ' reason: string', ' authorDid?: Did', ' authorHandle: string', ' authorName: string', ' indexedAt: string', ' text?: string', ' subjectText?: string', ' isReply: boolean', '}', '', 'interface Ctx {', ' sourceUris: string[]', ' notifications: EvidenceNotification[]', '}', '', ...METHOD_DEFS.flatMap(def => ['', `/** ${def.doc} */`, def.input]), '', 'interface BlueskyAgentSurface {', ' app: {', ' bsky: {', ' graph: {', ...METHOD_DEFS.filter(def => def.fq.includes('.graph.')).map(def => ` ${def.signature}`), ' }', ' notification: {', ...METHOD_DEFS.filter(def => def.fq.includes('.notification.')).map(def => ` ${def.signature}`), ' }', ' }', ' }', '}', '', 'Write exactly (plain JavaScript, no type annotations):', 'async function run(agent, ctx) {', ' // your code', '}', ].join('\n') export function validateCode(code: string) { const trimmed = code.trim() if (!trimmed) throw new CodeValidationError('empty code proposal') if (!trimmed.includes('async function run(')) { throw new CodeValidationError('proposal must define async function run(agent, ctx)') } const blocked = [ 'import ', 'require(', 'process.', 'Bun.', 'fetch(', 'XMLHttpRequest', 'WebSocket', 'setTimeout(', 'setInterval(', ] for (const token of blocked) { if (trimmed.includes(token)) { throw new CodeValidationError(`blocked token: ${token}`) } } const matches = [...trimmed.matchAll(/agent(?:\.[A-Za-z_$][\w$]*)+/g)].map(m => m[0]) for (const match of matches) { const isAllowed = ALLOWED_METHODS.some(method => match.startsWith(method)) if (!isAllowed) { throw new CodeValidationError(`blocked agent method: ${match}`) } } } export function parseFq(fq: string) { const parts = fq.replace(/^agent\./, '').split('.') return {name: parts[parts.length - 1], path: parts.slice(0, -1)} } // biome-ignore lint/suspicious/noExplicitAny: agent is structurally typed from METHOD_DEFS export type AgentSurface = Record export type QueuedCall = {method: string; input: unknown} function actorInput(input: unknown) { if (!input || typeof input !== 'object' || typeof (input as {actor?: unknown}).actor !== 'string') { throw new Error('expected input.actor DID') } return (input as {actor: string}).actor } async function findBlockUri(agent: AgentSurface, actor: string) { let cursor: string | undefined do { const res = await agent.app.bsky.graph.getBlocks({cursor, limit: 100}) const profile = res.data.blocks.find((row: {did?: string}) => row.did === actor) const uri = profile?.viewer?.blocking if (typeof uri === 'string' && uri) return uri cursor = res.data.cursor } while (cursor) return '' } const METHOD_DISPATCH_OVERRIDES: Record Promise> = { blockActor: async (agent, input) => { const actor = actorInput(input) return agent.app.bsky.graph.block.create( {repo: agent.assertDid}, {subject: actor, createdAt: new Date().toISOString()}, ) }, unblockActor: async (agent, input) => { const actor = actorInput(input) const uri = await findBlockUri(agent, actor) if (!uri) return undefined const rkey = uri.split('/').filter(Boolean).pop() if (!rkey) throw new Error(`could not parse block record URI: ${uri}`) return agent.app.bsky.graph.block.delete({repo: agent.assertDid, rkey}) }, } export const METHOD_DISPATCH: Record Promise> = Object.fromEntries( METHOD_DEFS.map(def => { const {name, path} = parseFq(def.fq) return [name, METHOD_DISPATCH_OVERRIDES[name] || ((agent: AgentSurface, input: unknown) => { let target = agent for (const segment of path) target = target[segment] return target[name](input) })] }), ) export function replayQueuedCalls( agent: AgentSurface, callQueue: QueuedCall[], ): Promise { return Promise.all( callQueue.map(async call => { const dispatch = METHOD_DISPATCH[call.method] if (!dispatch) { return {method: call.method, input: call.input, status: 'failed', error: 'unknown method in queue'} satisfies CallResult } try { await dispatch(agent, call.input) return {method: call.method, input: call.input, status: 'ok'} satisfies CallResult } catch (err) { return { method: call.method, input: call.input, status: 'failed', error: err instanceof Error ? err.message : String(err), } satisfies CallResult } }), ) } export const SANDBOX_PREAMBLE = (() => { const grouped = new Map() for (const def of METHOD_DEFS) { const {name, path} = parseFq(def.fq) const key = path.join('.') const existing = grouped.get(key) || [] existing.push(` ${name}: function(input) { __calls.push({ method: "${name}", input: input }); return Promise.resolve(); }`) grouped.set(key, existing) } const namespaces = new Map() for (const [ns, methods] of grouped) { const parts = ns.split('.') const leaf = parts[parts.length - 1] namespaces.set(leaf, methods) } const nsBlocks = [...namespaces.entries()] .map(([leaf, methods]) => ` ${leaf}: {\n${methods.join(',\n')}\n }`) .join(',\n') return `\nvar __calls = [];\nvar agent = {\n app: {\n bsky: {\n${nsBlocks}\n }\n }\n};\n` })()