Something went wrong. Try again.
notification manager for bsky noti.waow.tech
Something went wrong. Try again.
TypeScript
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238import 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<void>`, }, { 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<void>`, }, { 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<void>`, }, { 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<void>`, }, { 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<void>`, }, { 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<void>`, },] 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_DEFSexport type AgentSurface = Record<string, any>
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<string, (agent: AgentSurface, input: unknown) => Promise<unknown>> = { 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<string, (agent: AgentSurface, input: unknown) => Promise<unknown>> = 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<CallResult[]> { 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<string, string[]>() 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<string, string[]>() 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`})()