@websitekit/runner 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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/check.ts","../src/config.ts","../src/model.ts","../src/brain.ts","../src/prompt.ts","../src/receipt.ts","../src/store.ts","../src/run.ts","../src/channels.ts","../src/source.ts","../src/runner.ts"],"sourcesContent":["import type { Address, Hex } from 'viem';\n\nimport type { BotSource } from './source';\n\n/**\n * A receipt checked against the chain: its mind rebuilt at its block from the chain and IPFS, and\n * the hash compared with the one it records. Equal means the output was written from exactly the\n * mind it says. It says nothing about the output itself, which is the runner's word.\n *\n * Works on this runner's receipts and on the ones a site serving bots may publish\n * (`/v1/minds/<bot>/outputs/<id>`):\n * both carry `bot`, `token`, `block`, `spec` and `mindHash`.\n */\n\nexport interface Checkable {\n id?: string;\n bot: Address;\n token: { collection: Address; id: string };\n block: string;\n spec: string;\n mindHash: Hex;\n}\n\nexport interface CheckOutcome {\n id: string | null;\n block: string;\n ok: boolean;\n /** Why it does not match; null when it does. */\n problem: string | null;\n}\n\nexport async function checkReceipt(receipt: Checkable, source: BotSource): Promise<CheckOutcome> {\n const outcome = (problem: string | null): CheckOutcome => ({ id: receipt.id ?? null, block: receipt.block, ok: problem === null, problem });\n if (receipt.bot.toLowerCase() !== source.site.toLowerCase() || BigInt(receipt.token.id) !== source.token) {\n return outcome('it is a receipt of another bot');\n }\n if (receipt.spec !== source.specCid) return outcome(`it names the spec ${receipt.spec}, and the bot’s is ${source.specCid}`);\n const rebuilt = await source.read(BigInt(receipt.block));\n return rebuilt.mindHash.toLowerCase() === receipt.mindHash.toLowerCase()\n ? outcome(null)\n : outcome(`the mind at block ${receipt.block} hashes to ${rebuilt.mindHash}, and the receipt says ${receipt.mindHash}`);\n}\n","import type { Address } from 'viem';\nimport { MODEL_LISTS, type PricedProvider } from '@websitekit/sdk/agents';\n\n/**\n * A runner's configuration: which bot, which chain, which model endpoint and key, what the brain\n * seat may cost, how often to post, where posts go and where receipts are kept. Read from one JSON\n * file and parsed strictly, as a bot's spec is: an unknown field is refused, so a typo is an error\n * rather than a setting silently ignored.\n *\n * **Secrets are never in the file.** It names the environment variable that holds each one\n * (`keyEnv`, `tokenEnv`, `secretEnv`), so the file can be committed and shared.\n *\n * **The ceiling has no default.** A bot's brain seat lets whoever holds that line choose the model\n * this runner pays for; a runner that did not say what it will pay would pay whatever they chose.\n */\n\n/** What the brain seat may cost this runner. */\nexport type Ceiling =\n /** Any model on the runner's provider costing at most this per post, priced from that provider's own list. */\n | { usdPerPost: number; prices: PricedProvider }\n /** Only these models, by the provider's id: for a provider with no price list, or a local model. */\n | { models: string[] };\n\nexport type ChannelConfig =\n | { kind: 'stdout' }\n /** Each receipt, POSTed as JSON; signed when a secret is named. */\n | { kind: 'webhook'; url: string; secretEnv: string | null }\n /** Each post, sent by the runner's own Telegram bot to a chat or channel it can post in. */\n | { kind: 'telegram'; tokenEnv: string; chat: string };\n\nexport interface RunnerConfig {\n bot: {\n chain: number;\n /** Its token in the Agents collection, or its lines' address: exactly one. */\n token: bigint | null;\n site: Address | null;\n /** The collection; the chain's own when absent. */\n collection: Address | null;\n };\n /** A JSON-RPC endpoint for the chain; the chain's public one when absent. */\n rpc: string | null;\n /**\n * Instead, the variable holding it: a keyed endpoint is a secret. `check` on an older receipt needs\n * one that answers for old blocks (an archive node); a public endpoint may not.\n */\n rpcEnv: string | null;\n /** IPFS gateways, tried in order. Every byte is checked against its address whichever answers. */\n ipfs: string[];\n model: {\n /** An OpenAI-shaped API's base, e.g. `https://openrouter.ai/api/v1`; `/chat/completions` is added. */\n endpoint: string;\n /** The variable holding the API key; null for an endpoint that needs none (a local model). */\n keyEnv: string | null;\n /** The provider a brain seat must name for this runner to run its model, e.g. `openrouter`. */\n provider: string;\n /** The runner's own model: what writes when the brain seat names nothing this runner will pay for. */\n default: string;\n /** The longest answer asked for. Also what a post is priced at. */\n maxTokens: number;\n };\n ceiling: Ceiling;\n posts: {\n everyHours: number;\n maxChars: number;\n /** The runner's own rules, added after the mind section and the length. */\n rules: string | null;\n };\n channels: ChannelConfig[];\n /** Where receipts are kept. Relative to the config file. They are also the runner's memory. */\n state: string;\n}\n\nexport const DEFAULT_GATEWAYS = ['https://gateway.pinata.cloud/ipfs/', 'https://ipfs.io/ipfs/', 'https://dweb.link/ipfs/'];\n\ntype Parsed = { ok: true; config: RunnerConfig } | { ok: false; problems: string[] };\n\nconst ADDRESS = /^0x[0-9a-fA-F]{40}$/;\nconst ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction unknownFields(o: Record<string, unknown>, known: string[], where: string, problems: string[]) {\n for (const k of Object.keys(o)) if (!known.includes(k)) problems.push(`${where}.${k} is not a setting`);\n}\n\nexport function parseConfig(raw: unknown): Parsed {\n const problems: string[] = [];\n if (!isObject(raw)) return { ok: false, problems: ['the config must be a JSON object'] };\n unknownFields(raw, ['bot', 'rpc', 'rpcEnv', 'ipfs', 'model', 'ceiling', 'posts', 'channels', 'state'], 'config', problems);\n\n // The bot.\n const bot = isObject(raw.bot) ? raw.bot : {};\n if (!isObject(raw.bot)) problems.push('bot is required: { \"chain\", and \"token\" or \"site\" }');\n unknownFields(bot, ['chain', 'token', 'site', 'collection'], 'bot', problems);\n const chain = bot.chain;\n if (!Number.isSafeInteger(chain) || (chain as number) <= 0) problems.push('bot.chain must be a chain id');\n let token: bigint | null = null;\n if (bot.token !== undefined) {\n if ((typeof bot.token === 'string' && /^\\d{1,78}$/.test(bot.token)) || (Number.isSafeInteger(bot.token) && (bot.token as number) >= 0)) {\n token = BigInt(bot.token as string | number);\n } else problems.push('bot.token must be a whole number, as a string');\n }\n const site = bot.site === undefined ? null : typeof bot.site === 'string' && ADDRESS.test(bot.site) ? (bot.site as Address) : null;\n if (bot.site !== undefined && !site) problems.push('bot.site must be an address');\n if ((token === null) === (bot.site === undefined)) problems.push('bot needs exactly one of \"token\" and \"site\"');\n const collection =\n bot.collection === undefined ? null : typeof bot.collection === 'string' && ADDRESS.test(bot.collection) ? (bot.collection as Address) : null;\n if (bot.collection !== undefined && !collection) problems.push('bot.collection must be an address');\n\n // Where it reads from.\n const rpc = raw.rpc === undefined ? null : typeof raw.rpc === 'string' && /^https?:\\/\\//.test(raw.rpc) ? raw.rpc : null;\n if (raw.rpc !== undefined && !rpc) problems.push('rpc must be an http(s) address');\n const rpcEnv = raw.rpcEnv === undefined ? null : typeof raw.rpcEnv === 'string' && ENV_NAME.test(raw.rpcEnv) ? raw.rpcEnv : null;\n if (raw.rpcEnv !== undefined && !rpcEnv) problems.push('rpcEnv must name an environment variable');\n if (raw.rpc !== undefined && raw.rpcEnv !== undefined) problems.push('give rpc or rpcEnv, not both');\n let ipfs = DEFAULT_GATEWAYS;\n if (raw.ipfs !== undefined) {\n if (Array.isArray(raw.ipfs) && raw.ipfs.length > 0 && raw.ipfs.every((g) => typeof g === 'string' && /^https?:\\/\\//.test(g))) ipfs = raw.ipfs as string[];\n else problems.push('ipfs must be a list of gateway addresses, e.g. \"https://ipfs.io/ipfs/\"');\n }\n\n // The model.\n const model = isObject(raw.model) ? raw.model : {};\n if (!isObject(raw.model)) problems.push('model is required: { \"endpoint\", \"provider\", \"default\" }');\n unknownFields(model, ['endpoint', 'keyEnv', 'provider', 'default', 'maxTokens'], 'model', problems);\n if (!(typeof model.endpoint === 'string' && /^https?:\\/\\//.test(model.endpoint))) problems.push('model.endpoint must be an http(s) address');\n if (model.keyEnv !== undefined && !(typeof model.keyEnv === 'string' && ENV_NAME.test(model.keyEnv))) {\n problems.push('model.keyEnv must name an environment variable, e.g. \"OPENROUTER_API_KEY\"');\n }\n if (!(typeof model.provider === 'string' && /^[a-z0-9][a-z0-9-]*$/.test(model.provider))) problems.push('model.provider must be a provider name, e.g. \"openrouter\"');\n if (!(typeof model.default === 'string' && model.default.trim())) problems.push('model.default must name a model');\n const maxTokens = model.maxTokens === undefined ? 1_024 : model.maxTokens;\n if (!Number.isSafeInteger(maxTokens) || (maxTokens as number) < 16) problems.push('model.maxTokens must be a whole number of at least 16');\n\n // The ceiling: required, and nothing about it is assumed.\n let ceiling: Ceiling | null = null;\n if (!isObject(raw.ceiling)) {\n problems.push('ceiling is required: { \"usdPerPost\", \"prices\" } or { \"models\": [...] }. It is what a brain seat may cost you');\n } else if ('models' in raw.ceiling) {\n unknownFields(raw.ceiling, ['models'], 'ceiling', problems);\n const models = raw.ceiling.models;\n if (Array.isArray(models) && models.length > 0 && models.every((m) => typeof m === 'string' && m.trim())) ceiling = { models: models as string[] };\n else problems.push('ceiling.models must be a list of model ids');\n } else {\n unknownFields(raw.ceiling, ['usdPerPost', 'prices'], 'ceiling', problems);\n const usd = raw.ceiling.usdPerPost;\n const prices = raw.ceiling.prices;\n if (!(typeof usd === 'number' && Number.isFinite(usd) && usd >= 0)) problems.push('ceiling.usdPerPost must be a number of dollars, 0 or more');\n if (!(typeof prices === 'string' && prices in MODEL_LISTS)) problems.push(`ceiling.prices must be one of: ${Object.keys(MODEL_LISTS).join(', ')}`);\n if (typeof usd === 'number' && typeof prices === 'string' && prices in MODEL_LISTS) ceiling = { usdPerPost: usd, prices: prices as PricedProvider };\n }\n if (ceiling && 'prices' in ceiling && model.provider !== ceiling.prices) {\n problems.push(`ceiling.prices is ${ceiling.prices}'s list, but model.provider is ${String(model.provider)}: a brain is priced on the provider that runs it`);\n }\n\n // Posts.\n const posts = raw.posts === undefined ? {} : isObject(raw.posts) ? raw.posts : null;\n if (!posts) problems.push('posts must be an object');\n unknownFields(posts ?? {}, ['everyHours', 'maxChars', 'rules'], 'posts', problems);\n const everyHours = posts?.everyHours ?? 6;\n if (!(typeof everyHours === 'number' && everyHours > 0)) problems.push('posts.everyHours must be a number of hours above 0');\n const maxChars = posts?.maxChars ?? 280;\n if (!Number.isSafeInteger(maxChars) || (maxChars as number) < 1 || (maxChars as number) > 4_096) problems.push('posts.maxChars must be a whole number from 1 to 4096');\n const rules = posts?.rules === undefined ? null : typeof posts.rules === 'string' && posts.rules.trim() ? posts.rules : null;\n if (posts?.rules !== undefined && !rules) problems.push('posts.rules must be words');\n\n // Channels.\n const channels: ChannelConfig[] = [];\n const rawChannels = raw.channels === undefined ? [{ kind: 'stdout' }] : raw.channels;\n if (!Array.isArray(rawChannels) || rawChannels.length === 0) problems.push('channels must be a list with at least one channel');\n else {\n rawChannels.forEach((c, i) => {\n const where = `channels[${i}]`;\n if (!isObject(c)) return problems.push(`${where} must be an object`);\n if (c.kind === 'stdout') {\n unknownFields(c, ['kind'], where, problems);\n channels.push({ kind: 'stdout' });\n } else if (c.kind === 'webhook') {\n unknownFields(c, ['kind', 'url', 'secretEnv'], where, problems);\n if (!(typeof c.url === 'string' && /^https?:\\/\\//.test(c.url))) problems.push(`${where}.url must be an http(s) address`);\n if (c.secretEnv !== undefined && !(typeof c.secretEnv === 'string' && ENV_NAME.test(c.secretEnv))) problems.push(`${where}.secretEnv must name an environment variable`);\n channels.push({ kind: 'webhook', url: c.url as string, secretEnv: (c.secretEnv as string | undefined) ?? null });\n } else if (c.kind === 'telegram') {\n unknownFields(c, ['kind', 'tokenEnv', 'chat'], where, problems);\n if (!(typeof c.tokenEnv === 'string' && ENV_NAME.test(c.tokenEnv))) problems.push(`${where}.tokenEnv must name an environment variable`);\n if (!(typeof c.chat === 'string' && /^(@[A-Za-z0-9_]{5,32}|-?\\d{1,20})$/.test(c.chat))) problems.push(`${where}.chat must be @channelname or a chat id`);\n channels.push({ kind: 'telegram', tokenEnv: c.tokenEnv as string, chat: c.chat as string });\n } else problems.push(`${where}.kind must be stdout, webhook or telegram`);\n });\n }\n\n const state = raw.state === undefined ? './websitekit-run' : typeof raw.state === 'string' && raw.state.trim() ? raw.state : null;\n if (!state) problems.push('state must be a directory');\n\n if (problems.length || !ceiling || !state) return { ok: false, problems };\n return {\n ok: true,\n config: {\n bot: { chain: chain as number, token, site, collection },\n rpc,\n rpcEnv,\n ipfs,\n model: {\n endpoint: model.endpoint as string,\n keyEnv: (model.keyEnv as string | undefined) ?? null,\n provider: model.provider as string,\n default: (model.default as string).trim(),\n maxTokens: maxTokens as number,\n },\n ceiling,\n posts: { everyHours: everyHours as number, maxChars: maxChars as number, rules },\n channels,\n state,\n },\n };\n}\n\n/** The chain endpoint: the named variable's, the file's, or null for the chain's public one. */\nexport function rpcOf(config: Pick<RunnerConfig, 'rpc' | 'rpcEnv'>, env: Record<string, string | undefined>): string | null {\n return config.rpcEnv ? secretFrom(env, config.rpcEnv) : config.rpc;\n}\n\n/** Every secret the config names, as the environment holds them: what must never be printed. */\nexport function secretsOf(config: RunnerConfig, env: Record<string, string | undefined>): string[] {\n const names = [\n config.model.keyEnv,\n config.rpcEnv,\n ...config.channels.map((c) => (c.kind === 'telegram' ? c.tokenEnv : c.kind === 'webhook' ? c.secretEnv : null)),\n ];\n return names.flatMap((n) => (n && env[n]?.trim() ? [env[n]!.trim()] : []));\n}\n\n/** `text` with every secret in it replaced, for anything printed. */\nexport function redact(text: string, secrets: readonly string[]): string {\n return secrets.reduce((out, secret) => (secret ? out.split(secret).join('<secret>') : out), text);\n}\n\n/** A named secret from the environment, or a refusal that names the variable and never a value. */\nexport function secretFrom(env: Record<string, string | undefined>, name: string): string {\n const value = env[name]?.trim();\n if (!value) throw new Error(`${name} is not set`);\n return value;\n}\n","/**\n * One call to an OpenAI-shaped chat endpoint (OpenRouter, Venice, a local server), with the runner's\n * own key. Plain `fetch`, no SDK of any provider's.\n */\n\nexport interface ChatAnswer {\n text: string;\n /** The model that answered, as the endpoint says; the one asked for when it does not say. */\n model: string;\n usage: { promptTokens: number | null; completionTokens: number | null; costUsd: number | null };\n}\n\n/** The key was refused (401, 402, 403): nothing a retry or another prompt fixes. The runner stops. */\nexport class KeyRefused extends Error {}\n\nexport interface ChatCall {\n endpoint: string;\n apiKey: string | null;\n model: string;\n system: string;\n user: string;\n maxTokens: number;\n}\n\nexport async function chat(call: ChatCall, fetchImpl: typeof fetch = fetch): Promise<ChatAnswer> {\n const url = `${call.endpoint.replace(/\\/+$/, '')}/chat/completions`;\n const response = await fetchImpl(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(call.apiKey ? { authorization: `Bearer ${call.apiKey}` } : {}),\n },\n body: JSON.stringify({\n model: call.model,\n max_tokens: call.maxTokens,\n // Plain strings, never a list of parts: some providers refuse a list on a text-only model.\n messages: [\n { role: 'system', content: call.system },\n { role: 'user', content: call.user },\n ],\n }),\n signal: AbortSignal.timeout(90_000),\n });\n const body = (await response.json().catch(() => null)) as Record<string, any> | null;\n if (!response.ok) {\n // The provider's own words, never the request: the key rides in a header of it.\n const said = typeof body?.error?.message === 'string' ? body.error.message : `HTTP ${response.status}`;\n if ([401, 402, 403].includes(response.status)) throw new KeyRefused(`the model key was refused (${response.status}): ${said}`);\n throw new Error(`the model endpoint answered ${response.status}: ${said}`);\n }\n const content = body?.choices?.[0]?.message?.content;\n const text = typeof content === 'string' ? content : Array.isArray(content) ? content.map((p) => (typeof p?.text === 'string' ? p.text : '')).join('') : '';\n const usage = body?.usage ?? {};\n const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null);\n return {\n text,\n model: typeof body?.model === 'string' && body.model ? body.model : call.model,\n usage: { promptTokens: num(usage.prompt_tokens), completionTokens: num(usage.completion_tokens), costUsd: num(usage.cost) },\n };\n}\n","import { callCost, modelRefusal, type MindLine, type ModelPrices, type ModelRef, type ModelRefusal } from '@websitekit/sdk/agents';\n\nimport type { Ceiling } from './config';\n\n/**\n * Which model writes: the one the bot's brain seat names, when this runner will pay for it, and\n * otherwise the runner's own (`AGENT-SPEC.md`, the brain seat). Pure.\n *\n * **The seat is honoured under a ceiling the runner sets.** Whoever holds the brain line chooses a\n * model that somebody else pays for, so a brain this runner cannot price, or that costs more per\n * post than its ceiling, falls back to the runner's own model, and the receipt says why. The\n * runner's own model is never measured: it is the runner's own choice of what to spend.\n */\n\nexport interface BrainChoice {\n /** The model asked to write, on the runner's provider. */\n model: string;\n /** What the brain seat named, or null when the bot has no brain seat. */\n chosen: ModelRef | null;\n /** Why `chosen` is not what writes; null when it is, or when nothing was chosen. */\n refused: string | null;\n}\n\nexport interface BrainTerms {\n provider: string;\n fallback: string;\n ceiling: Ceiling;\n /** The provider's price list; null when it could not be read, which refuses every priced brain. */\n prices: ModelPrices | null;\n /** The prompt about to be sent, in tokens (`promptTokensOf`), and the longest answer asked for. */\n promptTokens: number;\n maxTokens: number;\n}\n\nconst REFUSALS: Record<ModelRefusal, string> = {\n unlisted: 'its provider does not list it',\n router: 'it picks a model by itself',\n unfixed: 'its price is not fixed',\n 'not-chat': 'it does not answer a chat in words',\n 'small-context': 'it cannot hold this prompt',\n};\n\nfunction dollars(usd: number): string {\n // Two significant figures under a cent, without trailing zeros: $0.005, $0.0012.\n return usd < 0.01 ? `$${Number(usd.toPrecision(2))}` : `$${usd.toFixed(2)}`;\n}\n\n/** Why this runner will not pay for `chosen`, or null when it will. */\nexport function brainRefusal(chosen: ModelRef, t: BrainTerms): string | null {\n if (chosen.provider !== t.provider) return `this runner runs ${t.provider} models only`;\n if ('models' in t.ceiling) return t.ceiling.models.includes(chosen.model) ? null : 'it is not on this runner’s list';\n if (!t.prices) return `${t.provider}’s prices could not be read`;\n const refusal = modelRefusal(chosen.model, t.prices, t.promptTokens + t.maxTokens);\n if (refusal) return REFUSALS[refusal];\n const cost = callCost(t.prices.get(chosen.model)!, t.promptTokens, t.maxTokens);\n return cost > t.ceiling.usdPerPost\n ? `it costs up to ${dollars(cost)} a post, over this runner’s ceiling of ${dollars(t.ceiling.usdPerPost)}`\n : null;\n}\n\nexport function chooseBrain(lines: readonly MindLine[], t: BrainTerms): BrainChoice {\n // A brain seat nobody has bought names its default, the creator's choice: priced the same way.\n const chosen = lines.find((l) => l.kind === 'brain')?.brain ?? null;\n if (!chosen) return { model: t.fallback, chosen: null, refused: null };\n if (chosen.provider === t.provider && chosen.model === t.fallback) return { model: t.fallback, chosen, refused: null };\n const refused = brainRefusal(chosen, t);\n return refused ? { model: t.fallback, chosen, refused } : { model: chosen.model, chosen, refused: null };\n}\n","import { attr, escapeForPrompt, type Moment } from '@websitekit/sdk/agents';\n\n/**\n * This runner's prompt around a bot's mind. The mind section is the protocol's and comes first,\n * unchanged, so its hash is what anyone can rebuild; everything here comes after it and is this\n * runner's own: the length, the runner's rules, recent posts and the moment. Pure.\n *\n * Holders' words only appear inside the mind section and the moment's escaped blocks, never spliced\n * into a sentence of the runner's.\n */\n\n/** How many recent posts go into the prompt, so the bot does not repeat itself. */\nexport const RECENT_POSTS = 10;\n\nexport interface Prompt {\n system: string;\n user: string;\n}\n\n/** The time of day rather than a timestamp: a post has no use for a date. */\nfunction timeOfDay(now: Date): string {\n const day = now.toLocaleDateString('en-GB', { weekday: 'long', timeZone: 'UTC' });\n return `It is ${day}, ${String(now.getUTCHours()).padStart(2, '0')}:00 UTC.`;\n}\n\nfunction momentBlock(moment: Moment, now: Date): string {\n const time = timeOfDay(now);\n if (moment.kind === 'scheduled') return `${time} Write your next post.`;\n const before = moment.before ? escapeForPrompt(moment.before) : '(nothing)';\n const after = moment.after ? escapeForPrompt(moment.after) : '(nothing)';\n return `${time} The line \"${attr(moment.label)}\" in your mind just changed.\n<before>${before}</before>\n<after>${after}</after>\nWrite a post reacting to this change in your own mind, in your own voice.`;\n}\n\nexport function buildPrompt(input: {\n /** The mind section, exactly as built from the chain (`mindSection`). */\n section: string;\n /** Newest first. */\n recent: string[];\n moment: Moment;\n now: Date;\n maxChars: number;\n rules: string | null;\n /** Why the previous attempt was refused, on a retry. */\n refused?: string;\n}): Prompt {\n const rules = [\n `Write exactly one post, at most ${input.maxChars} characters. No hashtags.`,\n ...(input.rules ? [input.rules.trim()] : []),\n 'Answer with the post itself and nothing else: no quotation marks around it, no label, no explanation.',\n ].join('\\n\\n');\n const recent = input.recent.slice(0, RECENT_POSTS);\n const parts = [\n recent.length\n ? `<recent_posts newest_first=\"true\">\\n${recent.map((p) => `<post>${escapeForPrompt(p)}</post>`).join('\\n')}\\n</recent_posts>\\nDo not repeat yourself.`\n : '<recent_posts>(none yet: this is your first post)</recent_posts>',\n momentBlock(input.moment, input.now),\n ...(input.refused ? [`Your previous attempt was refused: ${input.refused}. Write a new post.`] : []),\n ];\n return { system: `${input.section}\\n\\n${rules}`, user: parts.join('\\n\\n') };\n}\n\n/** What a model wrote, as a post: trimmed, and one pair of wrapping quotation marks taken off. */\nexport function postFrom(text: string): string {\n const trimmed = text.trim();\n const quoted = /^([\"“”'])([\\s\\S]*)([\"“”'])$/.exec(trimmed);\n return quoted ? quoted[2]!.trim() : trimmed;\n}\n","import type { Address, Hex } from 'viem';\nimport type { MindLine, ModelRef, Moment } from '@websitekit/sdk/agents';\n\n/**\n * A receipt: what the runner read and what it wrote, one per output. Its `mindHash` is checkable by\n * anyone from the chain at `block` and IPFS (`checkReceipt`); its body is the runner's word.\n *\n * **The same shape as the receipts a site serving bots publishes** (`/v1/minds/<bot>/outputs/<id>`) — `bot`,\n * `token`, `block`, `spec`, `mindHash`, `mind` — so one checker reads both. What a runner adds is\n * after: the chain, which brain the seat chose and why it was refused, why an attempt failed.\n * Names no holder: a line is owned or rented, never by whom.\n */\nexport interface Receipt {\n /** The site the bot's lines are. */\n bot: Address;\n token: { collection: Address; id: string };\n chain: number;\n /** The runner's own count, from 1. */\n id: string;\n kind: 'scheduled' | 'reaction' | 'failed';\n /** The post; null when the attempt failed. */\n body: string | null;\n failure: string | null;\n /** The model that answered, as its endpoint says. */\n model: string;\n brain: { asked: string; chosen: ModelRef | null; refused: string | null };\n /** The spec's IPFS address. */\n spec: string;\n block: string;\n mindHash: Hex;\n moment: Moment;\n at: string;\n /** The mind as read, most expensive first: brain and face included. */\n mind: Array<{ key: string; label: string; kind: string; words: string | null; source: 'chain' | 'default'; price: string; rented: boolean }>;\n}\n\nexport function mindOf(lines: readonly MindLine[]): Receipt['mind'] {\n return lines.map((l) => ({\n key: l.key,\n label: l.label,\n kind: l.kind,\n words: l.text,\n source: l.source,\n price: l.charged.toString(),\n rented: l.rented,\n }));\n}\n\n/** The receipt's lines as the SDK's schedule reads a last run. */\nexport function lastRunOf(receipt: Pick<Receipt, 'mind' | 'at'> | null) {\n return receipt ? { lines: receipt.mind.map((m) => ({ key: m.key, text: m.words })), at: new Date(receipt.at) } : null;\n}\n","import { appendFile, mkdir, open, readFile, rm, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { Receipt } from './receipt';\n\n/**\n * Where a runner keeps its receipts, which are also its memory: the newest is what the next run\n * compares the mind against, and the recent posts go back into the prompt. One JSON line per\n * receipt, appended, never rewritten.\n */\nexport interface Store {\n receipts(): Promise<Receipt[]>;\n append(receipt: Receipt): Promise<void>;\n /** A delivery's outcome, kept apart so a receipt stays what was read and what was written. */\n delivered(entry: { id: string; channel: string; ok: boolean; error: string | null; at: string }): Promise<void>;\n}\n\nexport function fileStore(dir: string): Store {\n const receiptsFile = path.join(dir, 'receipts.jsonl');\n const deliveriesFile = path.join(dir, 'deliveries.jsonl');\n return {\n async receipts() {\n const text = await readFile(receiptsFile, 'utf-8').catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') return '';\n throw error;\n });\n return text\n .split('\\n')\n .filter((line) => line.trim())\n .map((line) => JSON.parse(line) as Receipt);\n },\n async append(receipt) {\n await mkdir(dir, { recursive: true });\n await appendFile(receiptsFile, `${JSON.stringify(receipt)}\\n`, 'utf-8');\n },\n async delivered(entry) {\n await mkdir(dir, { recursive: true });\n await appendFile(deliveriesFile, `${JSON.stringify(entry)}\\n`, 'utf-8');\n },\n };\n}\n\n/** Newest first, posts only: a failed attempt said nothing. */\nexport function recentPosts(receipts: readonly Receipt[], limit: number): string[] {\n return receipts\n .filter((r) => r.kind !== 'failed' && r.body)\n .slice(-limit)\n .reverse()\n .map((r) => r.body!);\n}\n\n/** A lock older than this is a run that died; the next run takes it over. */\nconst STALE_MS = 10 * 60 * 1000;\n\n/**\n * One pass at a time per state directory, so a cron that overlaps a slow run skips it rather than\n * posting twice. Null when another run holds the lock.\n */\nexport async function withLock<T>(dir: string, work: () => Promise<T>, now = Date.now()): Promise<{ value: T } | null> {\n await mkdir(dir, { recursive: true });\n const file = path.join(dir, 'lock');\n let handle;\n try {\n handle = await open(file, 'wx');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n const held = await stat(file).catch(() => null);\n if (held && now - held.mtimeMs < STALE_MS) return null;\n await rm(file, { force: true });\n handle = await open(file, 'wx');\n }\n try {\n await handle.writeFile(String(process.pid));\n await handle.close();\n return { value: await work() };\n } finally {\n await rm(file, { force: true });\n }\n}\n","import { nextMoment, promptTokensOf, type ModelPrices, type Moment } from '@websitekit/sdk/agents';\n\nimport { chooseBrain, type BrainChoice } from './brain';\nimport type { Channel } from './channels';\nimport type { RunnerConfig } from './config';\nimport { KeyRefused, type ChatAnswer } from './model';\nimport { buildPrompt, postFrom, RECENT_POSTS } from './prompt';\nimport { lastRunOf, mindOf, type Receipt } from './receipt';\nimport type { BotSource } from './source';\nimport { recentPosts, type Store } from './store';\n\n/**\n * One pass of the runner: read the mind at the head, decide whether a post is due (the SDK's\n * `nextMoment`, the rule every runner shares), choose the brain under the ceiling, write,\n * keep the receipt, then send it to every channel.\n *\n * A model that cannot write a post twice is recorded as a `failed` receipt, which moves the schedule\n * as a post does, so the same change is not retried every pass. A refused KEY records nothing and\n * stops the pass: no prompt fixes it, and a failed receipt would swallow the change it was for.\n */\n\nexport interface PassDeps {\n source: BotSource;\n store: Store;\n channels: Channel[];\n /** The runner's model call, with its key already in hand. */\n chat: (call: { model: string; system: string; user: string; maxTokens: number }) => Promise<ChatAnswer>;\n /** The provider's price list, or null when it cannot be read. Asked only when a ceiling prices. */\n prices: () => Promise<ModelPrices | null>;\n now: () => Date;\n /**\n * The runner's own check on what was written, after the length: a reason to refuse it, or null.\n * Optional. Code, a list of words, a classifier: the runner's rules, never the protocol's.\n */\n check?: (post: string) => string | null | Promise<string | null>;\n}\n\nexport type PassResult =\n | { kind: 'not-due' }\n | { kind: 'written'; receipt: Receipt; deliveries: Array<{ channel: string; ok: boolean; error: string | null }> };\n\n/** Room for the retry's sentence, so the brain priced is never under what is sent. */\nconst RETRY_CHARS = 200;\n\nexport async function runPass(config: RunnerConfig, deps: PassDeps): Promise<PassResult> {\n const read = await deps.source.read();\n const receipts = await deps.store.receipts();\n const last = receipts[receipts.length - 1] ?? null;\n const now = deps.now();\n const moment = nextMoment(read.mind.lines, lastRunOf(last), config.posts.everyHours * 3600, now);\n if (!moment) return { kind: 'not-due' };\n\n const recent = recentPosts(receipts, RECENT_POSTS);\n const promptOf = (refused?: string) =>\n buildPrompt({ section: read.section, recent, moment, now, maxChars: config.posts.maxChars, rules: config.posts.rules, refused });\n const first = promptOf();\n const brain = chooseBrain(read.mind.lines, {\n provider: config.model.provider,\n fallback: config.model.default,\n ceiling: config.ceiling,\n prices: 'prices' in config.ceiling ? await deps.prices() : null,\n promptTokens: promptTokensOf(first.system.length + first.user.length + RETRY_CHARS),\n maxTokens: config.model.maxTokens,\n });\n\n const written = await write(config, deps, brain, first, promptOf);\n const receipt: Receipt = {\n bot: deps.source.site,\n token: { collection: deps.source.collection, id: deps.source.token.toString() },\n chain: deps.source.chain,\n id: String(receipts.length + 1),\n kind: written.ok ? moment.kind : 'failed',\n body: written.ok ? written.post : null,\n failure: written.ok ? null : written.failure,\n model: written.model,\n brain: { asked: brain.model, chosen: brain.chosen, refused: brain.refused },\n spec: deps.source.specCid,\n block: read.mind.atBlock.toString(),\n mindHash: read.mindHash,\n moment,\n at: now.toISOString(),\n mind: mindOf(read.mind.lines),\n };\n // Kept before it is sent: a channel that fails must not make the next pass write it again.\n await deps.store.append(receipt);\n\n const deliveries: Array<{ channel: string; ok: boolean; error: string | null }> = [];\n for (const channel of deps.channels) {\n const outcome = await channel.send(receipt).then(\n () => ({ ok: true, error: null }),\n (error: unknown) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }),\n );\n deliveries.push({ channel: channel.name, ...outcome });\n await deps.store.delivered({ id: receipt.id, channel: channel.name, ...outcome, at: new Date().toISOString() });\n }\n return { kind: 'written', receipt, deliveries };\n}\n\ntype Written = { ok: true; post: string; model: string } | { ok: false; failure: string; model: string };\n\n/** Two attempts: the second told why the first was refused. */\nasync function write(\n config: RunnerConfig,\n deps: PassDeps,\n brain: BrainChoice,\n first: { system: string; user: string },\n promptOf: (refused?: string) => { system: string; user: string },\n): Promise<Written> {\n let prompt = first;\n let failure = '';\n let model = brain.model;\n for (let attempt = 0; attempt < 2; attempt++) {\n let answer: ChatAnswer;\n try {\n answer = await deps.chat({ model: brain.model, ...prompt, maxTokens: config.model.maxTokens });\n } catch (error) {\n if (error instanceof KeyRefused) throw error;\n failure = error instanceof Error ? error.message : String(error);\n continue;\n }\n model = answer.model;\n const post = postFrom(answer.text);\n const problem = !post\n ? 'it wrote nothing'\n : post.length > config.posts.maxChars\n ? `it was ${post.length} characters, over ${config.posts.maxChars}`\n : ((await deps.check?.(post)) ?? null);\n if (!problem) return { ok: true, post, model };\n failure = problem;\n prompt = promptOf(problem);\n }\n return { ok: false, failure, model };\n}\n\nexport type { Moment };\n","import { createHmac } from 'node:crypto';\n\nimport type { ChannelConfig } from './config';\nimport { secretFrom } from './config';\nimport type { Receipt } from './receipt';\n\n/**\n * Where a run's output goes. Each is an adapter with one method; the runner sends every receipt to\n * every channel, and each decides what of it to say: standard output says everything, a webhook gets\n * the whole receipt, Telegram gets the post alone and nothing for a failed attempt.\n */\nexport interface Channel {\n name: string;\n send(receipt: Receipt): Promise<void>;\n}\n\nexport function stdoutChannel(write: (text: string) => void = (text) => process.stdout.write(text)): Channel {\n return {\n name: 'stdout',\n async send(r) {\n const brain = r.brain.refused ? ` (its brain line chose ${r.brain.chosen?.model}: refused, ${r.brain.refused})` : '';\n if (r.kind === 'failed') write(`#${r.id} failed on ${r.model}${brain}: ${r.failure}\\n`);\n else write(`#${r.id} ${r.kind}${r.moment.kind === 'reaction' ? ` to ${r.moment.key}` : ''} by ${r.model}${brain}\\n${r.body}\\n`);\n },\n };\n}\n\n/**\n * Each receipt POSTed as JSON. With a secret, signed: `x-websitekit-signature: sha256=<hex>` over the\n * exact body, so the receiver can tell it came from this runner.\n */\nexport function webhookChannel(url: string, secret: string | null, fetchImpl: typeof fetch = fetch): Channel {\n return {\n name: `webhook ${new URL(url).host}`,\n async send(r) {\n const body = JSON.stringify(r);\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n if (secret) headers['x-websitekit-signature'] = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`;\n const response = await fetchImpl(url, { method: 'POST', headers, body, redirect: 'error', signal: AbortSignal.timeout(20_000) });\n if (!response.ok) throw new Error(`the webhook answered ${response.status}`);\n },\n };\n}\n\n/**\n * The post, sent by the runner's own Telegram bot (made with @BotFather, free) to a chat or channel\n * it can post in. The token is in every Bot API address, so a failure names Telegram's words only.\n */\nexport function telegramChannel(token: string, chat: string, fetchImpl: typeof fetch = fetch): Channel {\n return {\n name: `telegram ${chat}`,\n async send(r) {\n if (r.kind === 'failed' || !r.body) return;\n const response = await fetchImpl(`https://api.telegram.org/bot${token}/sendMessage`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ chat_id: chat, text: r.body, link_preview_options: { is_disabled: true } }),\n signal: AbortSignal.timeout(20_000),\n });\n const said = (await response.json().catch(() => null)) as { ok?: boolean; description?: string } | null;\n if (!response.ok || !said?.ok) throw new Error(`Telegram refused sendMessage: ${said?.description ?? `HTTP ${response.status}`}`);\n },\n };\n}\n\n/** The configured channels, with their secrets read from the environment now. */\nexport function channelsOf(configs: readonly ChannelConfig[], env: Record<string, string | undefined>, fetchImpl: typeof fetch = fetch): Channel[] {\n return configs.map((c) => {\n if (c.kind === 'stdout') return stdoutChannel();\n if (c.kind === 'webhook') return webhookChannel(c.url, c.secretEnv ? secretFrom(env, c.secretEnv) : null, fetchImpl);\n return telegramChannel(secretFrom(env, c.tokenEnv), c.chat, fetchImpl);\n });\n}\n","import { createPublicClient, http, sha256, type Address, type Hex, type PublicClient } from 'viem';\nimport { chainFor, contentHashToCid, deploymentFor } from '@websitekit/sdk';\nimport {\n agentDeploymentFor,\n agentMindAt,\n bytesByCid,\n loadSpec,\n readAgent,\n readTokenOfSite,\n specCid,\n type BotSpec,\n type Mind,\n} from '@websitekit/sdk/agents';\n\n/**\n * A bot read from the chain and IPFS alone, the way any runner reads one: its token in the Agents\n * collection, its spec by the digest the collection records, and its mind at a block. Nothing from\n * any site, so a runner keeps working whatever a site does.\n */\n\nexport interface BotRef {\n chain: number;\n token: bigint | null;\n site: Address | null;\n collection: Address | null;\n}\n\nexport interface MindRead {\n mind: Mind;\n section: string;\n mindHash: Hex;\n}\n\nexport interface BotSource {\n chain: number;\n collection: Address;\n token: bigint;\n site: Address;\n spec: BotSpec;\n specCid: string;\n /** The mind at `block`, or at the head when absent. */\n read(block?: bigint): Promise<MindRead>;\n}\n\n/**\n * An IPFS fetch that returns bytes only when they hash to the address asked for, from the first\n * gateway that serves them so. A gateway is never trusted: a wrong byte is the next gateway's turn.\n */\nexport function ipfsFetcher(gateways: readonly string[], fetchImpl: typeof fetch = fetch): (cid: string) => Promise<Uint8Array | null> {\n return async (cid) => {\n for (const gateway of gateways) {\n try {\n const response = await fetchImpl(`${gateway.replace(/\\/*$/, '/')}${cid}`, {\n headers: { accept: 'application/octet-stream, */*' },\n signal: AbortSignal.timeout(20_000),\n });\n if (!response.ok) continue;\n const bytes = new Uint8Array(await response.arrayBuffer());\n if (contentHashToCid(sha256(bytes)) === cid) return bytes;\n } catch {\n // The next gateway.\n }\n }\n return null;\n };\n}\n\nexport function clientFor(chain: number, rpc: string | null): PublicClient {\n const known = chainFor(chain);\n return createPublicClient({ transport: http(rpc ?? known.rpcUrl, { retryCount: 2 }) }) as PublicClient;\n}\n\nexport async function openBot(\n ref: BotRef,\n o: { client: PublicClient; fetchCid: (cid: string) => Promise<Uint8Array | null> },\n): Promise<BotSource> {\n const collection = ref.collection ?? agentDeploymentFor(ref.chain).collection;\n const reader = deploymentFor(ref.chain).reader;\n if (!reader) throw new Error(`no slot reader is deployed on chain ${ref.chain}`);\n const token = ref.token ?? (await readTokenOfSite(o.client, collection, ref.site!));\n if (token === 0n) throw new Error(`${ref.site} is no bot of the collection ${collection}`);\n const agent = await readAgent(o.client, collection, token);\n if (ref.site && agent.site.toLowerCase() !== ref.site.toLowerCase()) throw new Error(`token ${token} is not the bot at ${ref.site}`);\n const spec = await loadSpec(agent.spec, o.fetchCid);\n if (!spec) throw new Error(`the spec at ${specCid(agent.spec)} could not be fetched from IPFS`);\n const bytes = bytesByCid(o.fetchCid);\n return {\n chain: ref.chain,\n collection,\n token,\n site: agent.site,\n spec,\n specCid: specCid(agent.spec),\n async read(block) {\n const read = await agentMindAt(o.client, { collection, tokenId: token, ref: { site: agent.site, reader } }, spec, o.fetchCid, bytes, block);\n return { mind: read.mind, section: read.section, mindHash: read.mindHash };\n },\n };\n}\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { MODEL_LISTS, PRICE_PARSERS, type ModelPrices, type PricedProvider } from '@websitekit/sdk/agents';\n\nimport { channelsOf } from './channels';\nimport { parseConfig, rpcOf, secretFrom, type RunnerConfig } from './config';\nimport { chat } from './model';\nimport type { PassDeps } from './run';\nimport { clientFor, ipfsFetcher, openBot } from './source';\nimport { fileStore } from './store';\n\n/** A provider's price list, read now; null when it cannot be read or reads as empty. */\nexport async function priceList(provider: PricedProvider, fetchImpl: typeof fetch = fetch): Promise<ModelPrices | null> {\n try {\n const response = await fetchImpl(MODEL_LISTS[provider], { signal: AbortSignal.timeout(20_000) });\n if (!response.ok) return null;\n const prices = PRICE_PARSERS[provider](await response.json());\n return prices.size ? prices : null;\n } catch {\n return null;\n }\n}\n\nexport interface Runner {\n config: RunnerConfig;\n /** The state directory, resolved against the config file. */\n stateDir: string;\n deps: PassDeps;\n}\n\n/**\n * Everything a pass needs, from a config file and the environment: the file parsed strictly, every\n * named secret read now (a missing one stops here, before the chain is read), the bot opened.\n */\nexport async function loadRunner(configPath: string, env: Record<string, string | undefined>, fetchImpl: typeof fetch = fetch): Promise<Runner> {\n const raw = JSON.parse(await readFile(configPath, 'utf-8')) as unknown;\n const parsed = parseConfig(raw);\n if (!parsed.ok) throw new Error(`${configPath} is not a runner config:\\n - ${parsed.problems.join('\\n - ')}`);\n const config = parsed.config;\n const apiKey = config.model.keyEnv ? secretFrom(env, config.model.keyEnv) : null;\n const channels = channelsOf(config.channels, env, fetchImpl);\n const stateDir = path.resolve(path.dirname(configPath), config.state);\n\n const fetchCid = ipfsFetcher(config.ipfs, fetchImpl);\n const source = await openBot(config.bot, { client: clientFor(config.bot.chain, rpcOf(config, env)), fetchCid });\n const ceiling = config.ceiling;\n return {\n config,\n stateDir,\n deps: {\n source,\n store: fileStore(stateDir),\n channels,\n chat: (call) => chat({ endpoint: config.model.endpoint, apiKey, ...call }, fetchImpl),\n prices: () => ('prices' in ceiling ? priceList(ceiling.prices, fetchImpl) : Promise.resolve(null)),\n now: () => new Date(),\n },\n };\n}\n"],"mappings":";AA+BA,eAAsB,aAAa,SAAoB,QAA0C;AAC/F,QAAM,UAAU,CAAC,aAA0C,EAAE,IAAI,QAAQ,MAAM,MAAM,OAAO,QAAQ,OAAO,IAAI,YAAY,MAAM,QAAQ;AACzI,MAAI,QAAQ,IAAI,YAAY,MAAM,OAAO,KAAK,YAAY,KAAK,OAAO,QAAQ,MAAM,EAAE,MAAM,OAAO,OAAO;AACxG,WAAO,QAAQ,gCAAgC;AAAA,EACjD;AACA,MAAI,QAAQ,SAAS,OAAO,QAAS,QAAO,QAAQ,qBAAqB,QAAQ,IAAI,2BAAsB,OAAO,OAAO,EAAE;AAC3H,QAAM,UAAU,MAAM,OAAO,KAAK,OAAO,QAAQ,KAAK,CAAC;AACvD,SAAO,QAAQ,SAAS,YAAY,MAAM,QAAQ,SAAS,YAAY,IACnE,QAAQ,IAAI,IACZ,QAAQ,qBAAqB,Q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AAA,EACF;AACF;","names":["write","chat","readFile","path","MODEL_LISTS","MODEL_LISTS","readFile","path"]}
package/dist/cli.js ADDED
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ KeyRefused,
4
+ checkReceipt,
5
+ clientFor,
6
+ fileStore,
7
+ ipfsFetcher,
8
+ loadRunner,
9
+ openBot,
10
+ parseConfig,
11
+ redact,
12
+ rpcOf,
13
+ runPass,
14
+ secretsOf,
15
+ withLock
16
+ } from "./chunk-YFKTNVGJ.js";
17
+
18
+ // src/cli.ts
19
+ import { readFile } from "fs/promises";
20
+ import path from "path";
21
+ import { parseArgs } from "util";
22
+ var USAGE = `usage: websitekit-run <once|watch|mind|check> [--config websitekit-run.json] [--every minutes] [receipt \u2026]`;
23
+ var UsageError = class extends Error {
24
+ };
25
+ async function once(configPath) {
26
+ const runner = await loadRunner(configPath, process.env);
27
+ const locked = await withLock(runner.stateDir, () => runPass(runner.config, runner.deps));
28
+ if (!locked) {
29
+ console.error("another pass holds the lock; skipped");
30
+ return 0;
31
+ }
32
+ const result = locked.value;
33
+ if (result.kind === "not-due") {
34
+ console.error("nothing due");
35
+ return 0;
36
+ }
37
+ for (const d of result.deliveries) if (!d.ok) console.error(`${d.channel}: ${hide(d.error ?? "")}`);
38
+ return 0;
39
+ }
40
+ async function watch(configPath, everyMinutes) {
41
+ for (; ; ) {
42
+ try {
43
+ await once(configPath);
44
+ } catch (error) {
45
+ console.error(`pass failed: ${message(error)}`);
46
+ if (error instanceof KeyRefused) return 1;
47
+ }
48
+ await new Promise((resolve) => setTimeout(resolve, everyMinutes * 6e4));
49
+ }
50
+ }
51
+ async function mind(configPath) {
52
+ const runner = await loadRunner(configPath, process.env);
53
+ const read = await runner.deps.source.read();
54
+ process.stdout.write(`${read.section}
55
+
56
+ `);
57
+ console.error(`block ${read.mind.atBlock} \xB7 mind hash ${read.mindHash}`);
58
+ return 0;
59
+ }
60
+ async function receiptsFrom(sources) {
61
+ const out = [];
62
+ for (const from of sources) {
63
+ if (/^https?:\/\//.test(from)) {
64
+ const response = await fetch(from, { signal: AbortSignal.timeout(2e4) });
65
+ if (!response.ok) throw new Error(`${from} answered ${response.status}`);
66
+ out.push(await response.json());
67
+ continue;
68
+ }
69
+ const text = (await readFile(from, "utf-8")).trim();
70
+ if (text.startsWith("{") && !text.includes("\n")) out.push(JSON.parse(text));
71
+ else for (const line of text.split("\n")) if (line.trim()) out.push(JSON.parse(line));
72
+ }
73
+ return out;
74
+ }
75
+ async function check(configPath, sources) {
76
+ const raw = JSON.parse(await readFile(configPath, "utf-8"));
77
+ const parsed = parseConfig(raw);
78
+ if (!parsed.ok) throw new UsageError(`${configPath} is not a runner config:
79
+ - ${parsed.problems.join("\n - ")}`);
80
+ const config = parsed.config;
81
+ const receipts = sources.length ? await receiptsFrom(sources) : await fileStore(path.resolve(path.dirname(configPath), config.state)).receipts();
82
+ if (!receipts.length) {
83
+ console.error("no receipts to check");
84
+ return 0;
85
+ }
86
+ const client = clientFor(config.bot.chain, rpcOf(config, process.env));
87
+ const fetchCid = ipfsFetcher(config.ipfs);
88
+ const opened = /* @__PURE__ */ new Map();
89
+ let failed = 0;
90
+ for (const receipt of receipts) {
91
+ const key = `${receipt.token.collection.toLowerCase()}:${receipt.token.id}`;
92
+ let source = opened.get(key);
93
+ if (!source) {
94
+ source = await openBot({ chain: config.bot.chain, token: BigInt(receipt.token.id), site: null, collection: receipt.token.collection }, { client, fetchCid });
95
+ opened.set(key, source);
96
+ }
97
+ const outcome = await checkReceipt(receipt, source);
98
+ if (!outcome.ok) failed++;
99
+ console.log(`${outcome.ok ? "ok " : "FAIL"} #${outcome.id ?? "?"} at block ${outcome.block}${outcome.problem ? `: ${outcome.problem}` : ""}`);
100
+ }
101
+ console.error(`${receipts.length - failed} of ${receipts.length} rebuilt to their hash`);
102
+ return failed ? 1 : 0;
103
+ }
104
+ var SECRETS = [];
105
+ function hide(text) {
106
+ return redact(text, SECRETS);
107
+ }
108
+ function message(error) {
109
+ return hide((error instanceof Error ? error.message : String(error)).split("\n").slice(0, 8).join("\n"));
110
+ }
111
+ async function learnSecrets(configPath) {
112
+ const raw = await readFile(configPath, "utf-8").catch(() => null);
113
+ if (raw === null) return;
114
+ let parsed;
115
+ try {
116
+ parsed = parseConfig(JSON.parse(raw));
117
+ } catch {
118
+ return;
119
+ }
120
+ if (parsed.ok) SECRETS.push(...secretsOf(parsed.config, process.env));
121
+ }
122
+ async function main(argv) {
123
+ const { values, positionals } = parseArgs({
124
+ args: argv,
125
+ allowPositionals: true,
126
+ options: { config: { type: "string", short: "c" }, every: { type: "string" }, help: { type: "boolean", short: "h" } }
127
+ });
128
+ const [command, ...rest] = positionals;
129
+ if (values.help || !command) {
130
+ console.log(USAGE);
131
+ return values.help ? 0 : 2;
132
+ }
133
+ const configPath = path.resolve(values.config ?? "websitekit-run.json");
134
+ await learnSecrets(configPath);
135
+ if (command === "once") return once(configPath);
136
+ if (command === "watch") {
137
+ const every = values.every === void 0 ? 15 : Number(values.every);
138
+ if (!Number.isFinite(every) || every < 1) throw new UsageError("--every is a number of minutes, 1 or more");
139
+ return watch(configPath, every);
140
+ }
141
+ if (command === "mind") return mind(configPath);
142
+ if (command === "check") return check(configPath, rest);
143
+ throw new UsageError(USAGE);
144
+ }
145
+ main(process.argv.slice(2)).then(
146
+ (code) => process.exit(code),
147
+ (error) => {
148
+ console.error(message(error));
149
+ const configWrong = error instanceof UsageError || /is not a runner config|is not set|ENOENT/.test(String(error?.message ?? error));
150
+ process.exit(configWrong ? 2 : 1);
151
+ }
152
+ );
153
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `websitekit-run` — run a websitekit bot yourself.\n *\n * websitekit-run once [--config websitekit-run.json] one pass: post if one is due, then exit\n * websitekit-run watch [--config …] [--every 15] a pass now and every N minutes\n * websitekit-run mind [--config …] the bot's mind section now, and its hash\n * websitekit-run check [--config …] [receipt …] rebuild receipts' minds from the chain\n *\n * `check` takes receipt files (one JSON receipt, or JSON lines) or addresses of receipts, ours\n * included (`https://…/v1/minds/<bot>/outputs/<id>`); with none, this runner's own.\n *\n * Exit codes: 0 done (nothing due is done); 1 a pass failed, or a receipt did not match; 2 the\n * config or the command is wrong.\n */\nimport { readFile } from 'node:fs/promises';\nimport path from 'node:path';\nimport { parseArgs } from 'node:util';\n\nimport { checkReceipt, type Checkable } from './check';\nimport { parseConfig, redact, rpcOf, secretsOf } from './config';\nimport { KeyRefused } from './model';\nimport { runPass } from './run';\nimport { loadRunner } from './runner';\nimport { clientFor, ipfsFetcher, openBot, type BotSource } from './source';\nimport { fileStore, withLock } from './store';\n\nconst USAGE = `usage: websitekit-run <once|watch|mind|check> [--config websitekit-run.json] [--every minutes] [receipt …]`;\n\nclass UsageError extends Error {}\n\nasync function once(configPath: string): Promise<number> {\n const runner = await loadRunner(configPath, process.env);\n const locked = await withLock(runner.stateDir, () => runPass(runner.config, runner.deps));\n if (!locked) {\n console.error('another pass holds the lock; skipped');\n return 0;\n }\n const result = locked.value;\n if (result.kind === 'not-due') {\n console.error('nothing due');\n return 0;\n }\n for (const d of result.deliveries) if (!d.ok) console.error(`${d.channel}: ${hide(d.error ?? '')}`);\n return 0;\n}\n\nasync function watch(configPath: string, everyMinutes: number): Promise<number> {\n for (;;) {\n try {\n await once(configPath);\n } catch (error) {\n console.error(`pass failed: ${message(error)}`);\n // A refused key does not fix itself; every other failure is tried again next time.\n if (error instanceof KeyRefused) return 1;\n }\n await new Promise((resolve) => setTimeout(resolve, everyMinutes * 60_000));\n }\n}\n\nasync function mind(configPath: string): Promise<number> {\n const runner = await loadRunner(configPath, process.env);\n const read = await runner.deps.source.read();\n process.stdout.write(`${read.section}\\n\\n`);\n console.error(`block ${read.mind.atBlock} · mind hash ${read.mindHash}`);\n return 0;\n}\n\n/** Receipts from files (one JSON receipt or JSON lines) and addresses. */\nasync function receiptsFrom(sources: string[]): Promise<Checkable[]> {\n const out: Checkable[] = [];\n for (const from of sources) {\n if (/^https?:\\/\\//.test(from)) {\n const response = await fetch(from, { signal: AbortSignal.timeout(20_000) });\n if (!response.ok) throw new Error(`${from} answered ${response.status}`);\n out.push((await response.json()) as Checkable);\n continue;\n }\n const text = (await readFile(from, 'utf-8')).trim();\n if (text.startsWith('{') && !text.includes('\\n')) out.push(JSON.parse(text) as Checkable);\n else for (const line of text.split('\\n')) if (line.trim()) out.push(JSON.parse(line) as Checkable);\n }\n return out;\n}\n\nasync function check(configPath: string, sources: string[]): Promise<number> {\n const raw = JSON.parse(await readFile(configPath, 'utf-8')) as unknown;\n const parsed = parseConfig(raw);\n if (!parsed.ok) throw new UsageError(`${configPath} is not a runner config:\\n - ${parsed.problems.join('\\n - ')}`);\n const config = parsed.config;\n const receipts = sources.length ? await receiptsFrom(sources) : await fileStore(path.resolve(path.dirname(configPath), config.state)).receipts();\n if (!receipts.length) {\n console.error('no receipts to check');\n return 0;\n }\n // Each bot is opened once, on the config's chain: a receipt names its bot, not its chain.\n const client = clientFor(config.bot.chain, rpcOf(config, process.env));\n const fetchCid = ipfsFetcher(config.ipfs);\n const opened = new Map<string, BotSource>();\n let failed = 0;\n for (const receipt of receipts) {\n const key = `${receipt.token.collection.toLowerCase()}:${receipt.token.id}`;\n let source = opened.get(key);\n if (!source) {\n source = await openBot({ chain: config.bot.chain, token: BigInt(receipt.token.id), site: null, collection: receipt.token.collection }, { client, fetchCid });\n opened.set(key, source);\n }\n const outcome = await checkReceipt(receipt, source);\n if (!outcome.ok) failed++;\n console.log(`${outcome.ok ? 'ok ' : 'FAIL'} #${outcome.id ?? '?'} at block ${outcome.block}${outcome.problem ? `: ${outcome.problem}` : ''}`);\n }\n console.error(`${receipts.length - failed} of ${receipts.length} rebuilt to their hash`);\n return failed ? 1 : 0;\n}\n\n/**\n * Values never to print. A keyed RPC address rides in the chain library's own error text, and a\n * Telegram token in every Bot API address: every message goes through `hide`.\n */\nconst SECRETS: string[] = [];\n\nfunction hide(text: string): string {\n return redact(text, SECRETS);\n}\n\nfunction message(error: unknown): string {\n return hide((error instanceof Error ? error.message : String(error)).split('\\n').slice(0, 8).join('\\n'));\n}\n\n/** The config's secrets, read before any command runs so nothing it prints can carry one. */\nasync function learnSecrets(configPath: string): Promise<void> {\n const raw = await readFile(configPath, 'utf-8').catch(() => null);\n if (raw === null) return;\n let parsed;\n try {\n parsed = parseConfig(JSON.parse(raw));\n } catch {\n return;\n }\n if (parsed.ok) SECRETS.push(...secretsOf(parsed.config, process.env));\n}\n\nasync function main(argv: string[]): Promise<number> {\n const { values, positionals } = parseArgs({\n args: argv,\n allowPositionals: true,\n options: { config: { type: 'string', short: 'c' }, every: { type: 'string' }, help: { type: 'boolean', short: 'h' } },\n });\n const [command, ...rest] = positionals;\n if (values.help || !command) {\n console.log(USAGE);\n return values.help ? 0 : 2;\n }\n const configPath = path.resolve(values.config ?? 'websitekit-run.json');\n await learnSecrets(configPath);\n if (command === 'once') return once(configPath);\n if (command === 'watch') {\n const every = values.every === undefined ? 15 : Number(values.every);\n if (!Number.isFinite(every) || every < 1) throw new UsageError('--every is a number of minutes, 1 or more');\n return watch(configPath, every);\n }\n if (command === 'mind') return mind(configPath);\n if (command === 'check') return check(configPath, rest);\n throw new UsageError(USAGE);\n}\n\nmain(process.argv.slice(2)).then(\n (code) => process.exit(code),\n (error) => {\n console.error(message(error));\n const configWrong = error instanceof UsageError || /is not a runner config|is not set|ENOENT/.test(String(error?.message ?? error));\n process.exit(configWrong ? 2 : 1);\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;AAeA,SAAS,gBAAgB;AACzB,OAAO,UAAU;AACjB,SAAS,iBAAiB;AAU1B,IAAM,QAAQ;AAEd,IAAM,aAAN,cAAyB,MAAM;AAAC;AAEhC,eAAe,KAAK,YAAqC;AACvD,QAAM,SAAS,MAAM,WAAW,YAAY,QAAQ,GAAG;AACvD,QAAM,SAAS,MAAM,SAAS,OAAO,UAAU,MAAM,QAAQ,OAAO,QAAQ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