@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,591 @@
1
+ // src/check.ts
2
+ async function checkReceipt(receipt, source) {
3
+ const outcome = (problem) => ({ id: receipt.id ?? null, block: receipt.block, ok: problem === null, problem });
4
+ if (receipt.bot.toLowerCase() !== source.site.toLowerCase() || BigInt(receipt.token.id) !== source.token) {
5
+ return outcome("it is a receipt of another bot");
6
+ }
7
+ if (receipt.spec !== source.specCid) return outcome(`it names the spec ${receipt.spec}, and the bot\u2019s is ${source.specCid}`);
8
+ const rebuilt = await source.read(BigInt(receipt.block));
9
+ return rebuilt.mindHash.toLowerCase() === receipt.mindHash.toLowerCase() ? outcome(null) : outcome(`the mind at block ${receipt.block} hashes to ${rebuilt.mindHash}, and the receipt says ${receipt.mindHash}`);
10
+ }
11
+
12
+ // src/config.ts
13
+ import { MODEL_LISTS } from "@websitekit/sdk/agents";
14
+ var DEFAULT_GATEWAYS = ["https://gateway.pinata.cloud/ipfs/", "https://ipfs.io/ipfs/", "https://dweb.link/ipfs/"];
15
+ var ADDRESS = /^0x[0-9a-fA-F]{40}$/;
16
+ var ENV_NAME = /^[A-Z_][A-Z0-9_]*$/;
17
+ function isObject(v) {
18
+ return typeof v === "object" && v !== null && !Array.isArray(v);
19
+ }
20
+ function unknownFields(o, known, where, problems) {
21
+ for (const k of Object.keys(o)) if (!known.includes(k)) problems.push(`${where}.${k} is not a setting`);
22
+ }
23
+ function parseConfig(raw) {
24
+ const problems = [];
25
+ if (!isObject(raw)) return { ok: false, problems: ["the config must be a JSON object"] };
26
+ unknownFields(raw, ["bot", "rpc", "rpcEnv", "ipfs", "model", "ceiling", "posts", "channels", "state"], "config", problems);
27
+ const bot = isObject(raw.bot) ? raw.bot : {};
28
+ if (!isObject(raw.bot)) problems.push('bot is required: { "chain", and "token" or "site" }');
29
+ unknownFields(bot, ["chain", "token", "site", "collection"], "bot", problems);
30
+ const chain = bot.chain;
31
+ if (!Number.isSafeInteger(chain) || chain <= 0) problems.push("bot.chain must be a chain id");
32
+ let token = null;
33
+ if (bot.token !== void 0) {
34
+ if (typeof bot.token === "string" && /^\d{1,78}$/.test(bot.token) || Number.isSafeInteger(bot.token) && bot.token >= 0) {
35
+ token = BigInt(bot.token);
36
+ } else problems.push("bot.token must be a whole number, as a string");
37
+ }
38
+ const site = bot.site === void 0 ? null : typeof bot.site === "string" && ADDRESS.test(bot.site) ? bot.site : null;
39
+ if (bot.site !== void 0 && !site) problems.push("bot.site must be an address");
40
+ if (token === null === (bot.site === void 0)) problems.push('bot needs exactly one of "token" and "site"');
41
+ const collection = bot.collection === void 0 ? null : typeof bot.collection === "string" && ADDRESS.test(bot.collection) ? bot.collection : null;
42
+ if (bot.collection !== void 0 && !collection) problems.push("bot.collection must be an address");
43
+ const rpc = raw.rpc === void 0 ? null : typeof raw.rpc === "string" && /^https?:\/\//.test(raw.rpc) ? raw.rpc : null;
44
+ if (raw.rpc !== void 0 && !rpc) problems.push("rpc must be an http(s) address");
45
+ const rpcEnv = raw.rpcEnv === void 0 ? null : typeof raw.rpcEnv === "string" && ENV_NAME.test(raw.rpcEnv) ? raw.rpcEnv : null;
46
+ if (raw.rpcEnv !== void 0 && !rpcEnv) problems.push("rpcEnv must name an environment variable");
47
+ if (raw.rpc !== void 0 && raw.rpcEnv !== void 0) problems.push("give rpc or rpcEnv, not both");
48
+ let ipfs = DEFAULT_GATEWAYS;
49
+ if (raw.ipfs !== void 0) {
50
+ if (Array.isArray(raw.ipfs) && raw.ipfs.length > 0 && raw.ipfs.every((g) => typeof g === "string" && /^https?:\/\//.test(g))) ipfs = raw.ipfs;
51
+ else problems.push('ipfs must be a list of gateway addresses, e.g. "https://ipfs.io/ipfs/"');
52
+ }
53
+ const model = isObject(raw.model) ? raw.model : {};
54
+ if (!isObject(raw.model)) problems.push('model is required: { "endpoint", "provider", "default" }');
55
+ unknownFields(model, ["endpoint", "keyEnv", "provider", "default", "maxTokens"], "model", problems);
56
+ if (!(typeof model.endpoint === "string" && /^https?:\/\//.test(model.endpoint))) problems.push("model.endpoint must be an http(s) address");
57
+ if (model.keyEnv !== void 0 && !(typeof model.keyEnv === "string" && ENV_NAME.test(model.keyEnv))) {
58
+ problems.push('model.keyEnv must name an environment variable, e.g. "OPENROUTER_API_KEY"');
59
+ }
60
+ 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"');
61
+ if (!(typeof model.default === "string" && model.default.trim())) problems.push("model.default must name a model");
62
+ const maxTokens = model.maxTokens === void 0 ? 1024 : model.maxTokens;
63
+ if (!Number.isSafeInteger(maxTokens) || maxTokens < 16) problems.push("model.maxTokens must be a whole number of at least 16");
64
+ let ceiling = null;
65
+ if (!isObject(raw.ceiling)) {
66
+ problems.push('ceiling is required: { "usdPerPost", "prices" } or { "models": [...] }. It is what a brain seat may cost you');
67
+ } else if ("models" in raw.ceiling) {
68
+ unknownFields(raw.ceiling, ["models"], "ceiling", problems);
69
+ const models = raw.ceiling.models;
70
+ if (Array.isArray(models) && models.length > 0 && models.every((m) => typeof m === "string" && m.trim())) ceiling = { models };
71
+ else problems.push("ceiling.models must be a list of model ids");
72
+ } else {
73
+ unknownFields(raw.ceiling, ["usdPerPost", "prices"], "ceiling", problems);
74
+ const usd = raw.ceiling.usdPerPost;
75
+ const prices = raw.ceiling.prices;
76
+ if (!(typeof usd === "number" && Number.isFinite(usd) && usd >= 0)) problems.push("ceiling.usdPerPost must be a number of dollars, 0 or more");
77
+ if (!(typeof prices === "string" && prices in MODEL_LISTS)) problems.push(`ceiling.prices must be one of: ${Object.keys(MODEL_LISTS).join(", ")}`);
78
+ if (typeof usd === "number" && typeof prices === "string" && prices in MODEL_LISTS) ceiling = { usdPerPost: usd, prices };
79
+ }
80
+ if (ceiling && "prices" in ceiling && model.provider !== ceiling.prices) {
81
+ 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`);
82
+ }
83
+ const posts = raw.posts === void 0 ? {} : isObject(raw.posts) ? raw.posts : null;
84
+ if (!posts) problems.push("posts must be an object");
85
+ unknownFields(posts ?? {}, ["everyHours", "maxChars", "rules"], "posts", problems);
86
+ const everyHours = posts?.everyHours ?? 6;
87
+ if (!(typeof everyHours === "number" && everyHours > 0)) problems.push("posts.everyHours must be a number of hours above 0");
88
+ const maxChars = posts?.maxChars ?? 280;
89
+ if (!Number.isSafeInteger(maxChars) || maxChars < 1 || maxChars > 4096) problems.push("posts.maxChars must be a whole number from 1 to 4096");
90
+ const rules = posts?.rules === void 0 ? null : typeof posts.rules === "string" && posts.rules.trim() ? posts.rules : null;
91
+ if (posts?.rules !== void 0 && !rules) problems.push("posts.rules must be words");
92
+ const channels = [];
93
+ const rawChannels = raw.channels === void 0 ? [{ kind: "stdout" }] : raw.channels;
94
+ if (!Array.isArray(rawChannels) || rawChannels.length === 0) problems.push("channels must be a list with at least one channel");
95
+ else {
96
+ rawChannels.forEach((c, i) => {
97
+ const where = `channels[${i}]`;
98
+ if (!isObject(c)) return problems.push(`${where} must be an object`);
99
+ if (c.kind === "stdout") {
100
+ unknownFields(c, ["kind"], where, problems);
101
+ channels.push({ kind: "stdout" });
102
+ } else if (c.kind === "webhook") {
103
+ unknownFields(c, ["kind", "url", "secretEnv"], where, problems);
104
+ if (!(typeof c.url === "string" && /^https?:\/\//.test(c.url))) problems.push(`${where}.url must be an http(s) address`);
105
+ if (c.secretEnv !== void 0 && !(typeof c.secretEnv === "string" && ENV_NAME.test(c.secretEnv))) problems.push(`${where}.secretEnv must name an environment variable`);
106
+ channels.push({ kind: "webhook", url: c.url, secretEnv: c.secretEnv ?? null });
107
+ } else if (c.kind === "telegram") {
108
+ unknownFields(c, ["kind", "tokenEnv", "chat"], where, problems);
109
+ if (!(typeof c.tokenEnv === "string" && ENV_NAME.test(c.tokenEnv))) problems.push(`${where}.tokenEnv must name an environment variable`);
110
+ 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`);
111
+ channels.push({ kind: "telegram", tokenEnv: c.tokenEnv, chat: c.chat });
112
+ } else problems.push(`${where}.kind must be stdout, webhook or telegram`);
113
+ });
114
+ }
115
+ const state = raw.state === void 0 ? "./websitekit-run" : typeof raw.state === "string" && raw.state.trim() ? raw.state : null;
116
+ if (!state) problems.push("state must be a directory");
117
+ if (problems.length || !ceiling || !state) return { ok: false, problems };
118
+ return {
119
+ ok: true,
120
+ config: {
121
+ bot: { chain, token, site, collection },
122
+ rpc,
123
+ rpcEnv,
124
+ ipfs,
125
+ model: {
126
+ endpoint: model.endpoint,
127
+ keyEnv: model.keyEnv ?? null,
128
+ provider: model.provider,
129
+ default: model.default.trim(),
130
+ maxTokens
131
+ },
132
+ ceiling,
133
+ posts: { everyHours, maxChars, rules },
134
+ channels,
135
+ state
136
+ }
137
+ };
138
+ }
139
+ function rpcOf(config, env) {
140
+ return config.rpcEnv ? secretFrom(env, config.rpcEnv) : config.rpc;
141
+ }
142
+ function secretsOf(config, env) {
143
+ const names = [
144
+ config.model.keyEnv,
145
+ config.rpcEnv,
146
+ ...config.channels.map((c) => c.kind === "telegram" ? c.tokenEnv : c.kind === "webhook" ? c.secretEnv : null)
147
+ ];
148
+ return names.flatMap((n) => n && env[n]?.trim() ? [env[n].trim()] : []);
149
+ }
150
+ function redact(text, secrets) {
151
+ return secrets.reduce((out, secret) => secret ? out.split(secret).join("<secret>") : out, text);
152
+ }
153
+ function secretFrom(env, name) {
154
+ const value = env[name]?.trim();
155
+ if (!value) throw new Error(`${name} is not set`);
156
+ return value;
157
+ }
158
+
159
+ // src/model.ts
160
+ var KeyRefused = class extends Error {
161
+ };
162
+ async function chat(call, fetchImpl = fetch) {
163
+ const url = `${call.endpoint.replace(/\/+$/, "")}/chat/completions`;
164
+ const response = await fetchImpl(url, {
165
+ method: "POST",
166
+ headers: {
167
+ "content-type": "application/json",
168
+ ...call.apiKey ? { authorization: `Bearer ${call.apiKey}` } : {}
169
+ },
170
+ body: JSON.stringify({
171
+ model: call.model,
172
+ max_tokens: call.maxTokens,
173
+ // Plain strings, never a list of parts: some providers refuse a list on a text-only model.
174
+ messages: [
175
+ { role: "system", content: call.system },
176
+ { role: "user", content: call.user }
177
+ ]
178
+ }),
179
+ signal: AbortSignal.timeout(9e4)
180
+ });
181
+ const body = await response.json().catch(() => null);
182
+ if (!response.ok) {
183
+ const said = typeof body?.error?.message === "string" ? body.error.message : `HTTP ${response.status}`;
184
+ if ([401, 402, 403].includes(response.status)) throw new KeyRefused(`the model key was refused (${response.status}): ${said}`);
185
+ throw new Error(`the model endpoint answered ${response.status}: ${said}`);
186
+ }
187
+ const content = body?.choices?.[0]?.message?.content;
188
+ const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((p) => typeof p?.text === "string" ? p.text : "").join("") : "";
189
+ const usage = body?.usage ?? {};
190
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
191
+ return {
192
+ text,
193
+ model: typeof body?.model === "string" && body.model ? body.model : call.model,
194
+ usage: { promptTokens: num(usage.prompt_tokens), completionTokens: num(usage.completion_tokens), costUsd: num(usage.cost) }
195
+ };
196
+ }
197
+
198
+ // src/brain.ts
199
+ import { callCost, modelRefusal } from "@websitekit/sdk/agents";
200
+ var REFUSALS = {
201
+ unlisted: "its provider does not list it",
202
+ router: "it picks a model by itself",
203
+ unfixed: "its price is not fixed",
204
+ "not-chat": "it does not answer a chat in words",
205
+ "small-context": "it cannot hold this prompt"
206
+ };
207
+ function dollars(usd) {
208
+ return usd < 0.01 ? `$${Number(usd.toPrecision(2))}` : `$${usd.toFixed(2)}`;
209
+ }
210
+ function brainRefusal(chosen, t) {
211
+ if (chosen.provider !== t.provider) return `this runner runs ${t.provider} models only`;
212
+ if ("models" in t.ceiling) return t.ceiling.models.includes(chosen.model) ? null : "it is not on this runner\u2019s list";
213
+ if (!t.prices) return `${t.provider}\u2019s prices could not be read`;
214
+ const refusal = modelRefusal(chosen.model, t.prices, t.promptTokens + t.maxTokens);
215
+ if (refusal) return REFUSALS[refusal];
216
+ const cost = callCost(t.prices.get(chosen.model), t.promptTokens, t.maxTokens);
217
+ return cost > t.ceiling.usdPerPost ? `it costs up to ${dollars(cost)} a post, over this runner\u2019s ceiling of ${dollars(t.ceiling.usdPerPost)}` : null;
218
+ }
219
+ function chooseBrain(lines, t) {
220
+ const chosen = lines.find((l) => l.kind === "brain")?.brain ?? null;
221
+ if (!chosen) return { model: t.fallback, chosen: null, refused: null };
222
+ if (chosen.provider === t.provider && chosen.model === t.fallback) return { model: t.fallback, chosen, refused: null };
223
+ const refused = brainRefusal(chosen, t);
224
+ return refused ? { model: t.fallback, chosen, refused } : { model: chosen.model, chosen, refused: null };
225
+ }
226
+
227
+ // src/prompt.ts
228
+ import { attr, escapeForPrompt } from "@websitekit/sdk/agents";
229
+ var RECENT_POSTS = 10;
230
+ function timeOfDay(now) {
231
+ const day = now.toLocaleDateString("en-GB", { weekday: "long", timeZone: "UTC" });
232
+ return `It is ${day}, ${String(now.getUTCHours()).padStart(2, "0")}:00 UTC.`;
233
+ }
234
+ function momentBlock(moment, now) {
235
+ const time = timeOfDay(now);
236
+ if (moment.kind === "scheduled") return `${time} Write your next post.`;
237
+ const before = moment.before ? escapeForPrompt(moment.before) : "(nothing)";
238
+ const after = moment.after ? escapeForPrompt(moment.after) : "(nothing)";
239
+ return `${time} The line "${attr(moment.label)}" in your mind just changed.
240
+ <before>${before}</before>
241
+ <after>${after}</after>
242
+ Write a post reacting to this change in your own mind, in your own voice.`;
243
+ }
244
+ function buildPrompt(input) {
245
+ const rules = [
246
+ `Write exactly one post, at most ${input.maxChars} characters. No hashtags.`,
247
+ ...input.rules ? [input.rules.trim()] : [],
248
+ "Answer with the post itself and nothing else: no quotation marks around it, no label, no explanation."
249
+ ].join("\n\n");
250
+ const recent = input.recent.slice(0, RECENT_POSTS);
251
+ const parts = [
252
+ recent.length ? `<recent_posts newest_first="true">
253
+ ${recent.map((p) => `<post>${escapeForPrompt(p)}</post>`).join("\n")}
254
+ </recent_posts>
255
+ Do not repeat yourself.` : "<recent_posts>(none yet: this is your first post)</recent_posts>",
256
+ momentBlock(input.moment, input.now),
257
+ ...input.refused ? [`Your previous attempt was refused: ${input.refused}. Write a new post.`] : []
258
+ ];
259
+ return { system: `${input.section}
260
+
261
+ ${rules}`, user: parts.join("\n\n") };
262
+ }
263
+ function postFrom(text) {
264
+ const trimmed = text.trim();
265
+ const quoted = /^(["“”'])([\s\S]*)(["“”'])$/.exec(trimmed);
266
+ return quoted ? quoted[2].trim() : trimmed;
267
+ }
268
+
269
+ // src/receipt.ts
270
+ function mindOf(lines) {
271
+ return lines.map((l) => ({
272
+ key: l.key,
273
+ label: l.label,
274
+ kind: l.kind,
275
+ words: l.text,
276
+ source: l.source,
277
+ price: l.charged.toString(),
278
+ rented: l.rented
279
+ }));
280
+ }
281
+ function lastRunOf(receipt) {
282
+ return receipt ? { lines: receipt.mind.map((m) => ({ key: m.key, text: m.words })), at: new Date(receipt.at) } : null;
283
+ }
284
+
285
+ // src/store.ts
286
+ import { appendFile, mkdir, open, readFile, rm, stat } from "fs/promises";
287
+ import path from "path";
288
+ function fileStore(dir) {
289
+ const receiptsFile = path.join(dir, "receipts.jsonl");
290
+ const deliveriesFile = path.join(dir, "deliveries.jsonl");
291
+ return {
292
+ async receipts() {
293
+ const text = await readFile(receiptsFile, "utf-8").catch((error) => {
294
+ if (error.code === "ENOENT") return "";
295
+ throw error;
296
+ });
297
+ return text.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
298
+ },
299
+ async append(receipt) {
300
+ await mkdir(dir, { recursive: true });
301
+ await appendFile(receiptsFile, `${JSON.stringify(receipt)}
302
+ `, "utf-8");
303
+ },
304
+ async delivered(entry) {
305
+ await mkdir(dir, { recursive: true });
306
+ await appendFile(deliveriesFile, `${JSON.stringify(entry)}
307
+ `, "utf-8");
308
+ }
309
+ };
310
+ }
311
+ function recentPosts(receipts, limit) {
312
+ return receipts.filter((r) => r.kind !== "failed" && r.body).slice(-limit).reverse().map((r) => r.body);
313
+ }
314
+ var STALE_MS = 10 * 60 * 1e3;
315
+ async function withLock(dir, work, now = Date.now()) {
316
+ await mkdir(dir, { recursive: true });
317
+ const file = path.join(dir, "lock");
318
+ let handle;
319
+ try {
320
+ handle = await open(file, "wx");
321
+ } catch (error) {
322
+ if (error.code !== "EEXIST") throw error;
323
+ const held = await stat(file).catch(() => null);
324
+ if (held && now - held.mtimeMs < STALE_MS) return null;
325
+ await rm(file, { force: true });
326
+ handle = await open(file, "wx");
327
+ }
328
+ try {
329
+ await handle.writeFile(String(process.pid));
330
+ await handle.close();
331
+ return { value: await work() };
332
+ } finally {
333
+ await rm(file, { force: true });
334
+ }
335
+ }
336
+
337
+ // src/run.ts
338
+ import { nextMoment, promptTokensOf } from "@websitekit/sdk/agents";
339
+ var RETRY_CHARS = 200;
340
+ async function runPass(config, deps) {
341
+ const read = await deps.source.read();
342
+ const receipts = await deps.store.receipts();
343
+ const last = receipts[receipts.length - 1] ?? null;
344
+ const now = deps.now();
345
+ const moment = nextMoment(read.mind.lines, lastRunOf(last), config.posts.everyHours * 3600, now);
346
+ if (!moment) return { kind: "not-due" };
347
+ const recent = recentPosts(receipts, RECENT_POSTS);
348
+ const promptOf = (refused) => buildPrompt({ section: read.section, recent, moment, now, maxChars: config.posts.maxChars, rules: config.posts.rules, refused });
349
+ const first = promptOf();
350
+ const brain = chooseBrain(read.mind.lines, {
351
+ provider: config.model.provider,
352
+ fallback: config.model.default,
353
+ ceiling: config.ceiling,
354
+ prices: "prices" in config.ceiling ? await deps.prices() : null,
355
+ promptTokens: promptTokensOf(first.system.length + first.user.length + RETRY_CHARS),
356
+ maxTokens: config.model.maxTokens
357
+ });
358
+ const written = await write(config, deps, brain, first, promptOf);
359
+ const receipt = {
360
+ bot: deps.source.site,
361
+ token: { collection: deps.source.collection, id: deps.source.token.toString() },
362
+ chain: deps.source.chain,
363
+ id: String(receipts.length + 1),
364
+ kind: written.ok ? moment.kind : "failed",
365
+ body: written.ok ? written.post : null,
366
+ failure: written.ok ? null : written.failure,
367
+ model: written.model,
368
+ brain: { asked: brain.model, chosen: brain.chosen, refused: brain.refused },
369
+ spec: deps.source.specCid,
370
+ block: read.mind.atBlock.toString(),
371
+ mindHash: read.mindHash,
372
+ moment,
373
+ at: now.toISOString(),
374
+ mind: mindOf(read.mind.lines)
375
+ };
376
+ await deps.store.append(receipt);
377
+ const deliveries = [];
378
+ for (const channel of deps.channels) {
379
+ const outcome = await channel.send(receipt).then(
380
+ () => ({ ok: true, error: null }),
381
+ (error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) })
382
+ );
383
+ deliveries.push({ channel: channel.name, ...outcome });
384
+ await deps.store.delivered({ id: receipt.id, channel: channel.name, ...outcome, at: (/* @__PURE__ */ new Date()).toISOString() });
385
+ }
386
+ return { kind: "written", receipt, deliveries };
387
+ }
388
+ async function write(config, deps, brain, first, promptOf) {
389
+ let prompt = first;
390
+ let failure = "";
391
+ let model = brain.model;
392
+ for (let attempt = 0; attempt < 2; attempt++) {
393
+ let answer;
394
+ try {
395
+ answer = await deps.chat({ model: brain.model, ...prompt, maxTokens: config.model.maxTokens });
396
+ } catch (error) {
397
+ if (error instanceof KeyRefused) throw error;
398
+ failure = error instanceof Error ? error.message : String(error);
399
+ continue;
400
+ }
401
+ model = answer.model;
402
+ const post = postFrom(answer.text);
403
+ const problem = !post ? "it wrote nothing" : post.length > config.posts.maxChars ? `it was ${post.length} characters, over ${config.posts.maxChars}` : await deps.check?.(post) ?? null;
404
+ if (!problem) return { ok: true, post, model };
405
+ failure = problem;
406
+ prompt = promptOf(problem);
407
+ }
408
+ return { ok: false, failure, model };
409
+ }
410
+
411
+ // src/channels.ts
412
+ import { createHmac } from "crypto";
413
+ function stdoutChannel(write2 = (text) => process.stdout.write(text)) {
414
+ return {
415
+ name: "stdout",
416
+ async send(r) {
417
+ const brain = r.brain.refused ? ` (its brain line chose ${r.brain.chosen?.model}: refused, ${r.brain.refused})` : "";
418
+ if (r.kind === "failed") write2(`#${r.id} failed on ${r.model}${brain}: ${r.failure}
419
+ `);
420
+ else write2(`#${r.id} ${r.kind}${r.moment.kind === "reaction" ? ` to ${r.moment.key}` : ""} by ${r.model}${brain}
421
+ ${r.body}
422
+ `);
423
+ }
424
+ };
425
+ }
426
+ function webhookChannel(url, secret, fetchImpl = fetch) {
427
+ return {
428
+ name: `webhook ${new URL(url).host}`,
429
+ async send(r) {
430
+ const body = JSON.stringify(r);
431
+ const headers = { "content-type": "application/json" };
432
+ if (secret) headers["x-websitekit-signature"] = `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
433
+ const response = await fetchImpl(url, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(2e4) });
434
+ if (!response.ok) throw new Error(`the webhook answered ${response.status}`);
435
+ }
436
+ };
437
+ }
438
+ function telegramChannel(token, chat2, fetchImpl = fetch) {
439
+ return {
440
+ name: `telegram ${chat2}`,
441
+ async send(r) {
442
+ if (r.kind === "failed" || !r.body) return;
443
+ const response = await fetchImpl(`https://api.telegram.org/bot${token}/sendMessage`, {
444
+ method: "POST",
445
+ headers: { "content-type": "application/json" },
446
+ body: JSON.stringify({ chat_id: chat2, text: r.body, link_preview_options: { is_disabled: true } }),
447
+ signal: AbortSignal.timeout(2e4)
448
+ });
449
+ const said = await response.json().catch(() => null);
450
+ if (!response.ok || !said?.ok) throw new Error(`Telegram refused sendMessage: ${said?.description ?? `HTTP ${response.status}`}`);
451
+ }
452
+ };
453
+ }
454
+ function channelsOf(configs, env, fetchImpl = fetch) {
455
+ return configs.map((c) => {
456
+ if (c.kind === "stdout") return stdoutChannel();
457
+ if (c.kind === "webhook") return webhookChannel(c.url, c.secretEnv ? secretFrom(env, c.secretEnv) : null, fetchImpl);
458
+ return telegramChannel(secretFrom(env, c.tokenEnv), c.chat, fetchImpl);
459
+ });
460
+ }
461
+
462
+ // src/source.ts
463
+ import { createPublicClient, http, sha256 } from "viem";
464
+ import { chainFor, contentHashToCid, deploymentFor } from "@websitekit/sdk";
465
+ import {
466
+ agentDeploymentFor,
467
+ agentMindAt,
468
+ bytesByCid,
469
+ loadSpec,
470
+ readAgent,
471
+ readTokenOfSite,
472
+ specCid
473
+ } from "@websitekit/sdk/agents";
474
+ function ipfsFetcher(gateways, fetchImpl = fetch) {
475
+ return async (cid) => {
476
+ for (const gateway of gateways) {
477
+ try {
478
+ const response = await fetchImpl(`${gateway.replace(/\/*$/, "/")}${cid}`, {
479
+ headers: { accept: "application/octet-stream, */*" },
480
+ signal: AbortSignal.timeout(2e4)
481
+ });
482
+ if (!response.ok) continue;
483
+ const bytes = new Uint8Array(await response.arrayBuffer());
484
+ if (contentHashToCid(sha256(bytes)) === cid) return bytes;
485
+ } catch {
486
+ }
487
+ }
488
+ return null;
489
+ };
490
+ }
491
+ function clientFor(chain, rpc) {
492
+ const known = chainFor(chain);
493
+ return createPublicClient({ transport: http(rpc ?? known.rpcUrl, { retryCount: 2 }) });
494
+ }
495
+ async function openBot(ref, o) {
496
+ const collection = ref.collection ?? agentDeploymentFor(ref.chain).collection;
497
+ const reader = deploymentFor(ref.chain).reader;
498
+ if (!reader) throw new Error(`no slot reader is deployed on chain ${ref.chain}`);
499
+ const token = ref.token ?? await readTokenOfSite(o.client, collection, ref.site);
500
+ if (token === 0n) throw new Error(`${ref.site} is no bot of the collection ${collection}`);
501
+ const agent = await readAgent(o.client, collection, token);
502
+ if (ref.site && agent.site.toLowerCase() !== ref.site.toLowerCase()) throw new Error(`token ${token} is not the bot at ${ref.site}`);
503
+ const spec = await loadSpec(agent.spec, o.fetchCid);
504
+ if (!spec) throw new Error(`the spec at ${specCid(agent.spec)} could not be fetched from IPFS`);
505
+ const bytes = bytesByCid(o.fetchCid);
506
+ return {
507
+ chain: ref.chain,
508
+ collection,
509
+ token,
510
+ site: agent.site,
511
+ spec,
512
+ specCid: specCid(agent.spec),
513
+ async read(block) {
514
+ const read = await agentMindAt(o.client, { collection, tokenId: token, ref: { site: agent.site, reader } }, spec, o.fetchCid, bytes, block);
515
+ return { mind: read.mind, section: read.section, mindHash: read.mindHash };
516
+ }
517
+ };
518
+ }
519
+
520
+ // src/runner.ts
521
+ import { readFile as readFile2 } from "fs/promises";
522
+ import path2 from "path";
523
+ import { MODEL_LISTS as MODEL_LISTS2, PRICE_PARSERS } from "@websitekit/sdk/agents";
524
+ async function priceList(provider, fetchImpl = fetch) {
525
+ try {
526
+ const response = await fetchImpl(MODEL_LISTS2[provider], { signal: AbortSignal.timeout(2e4) });
527
+ if (!response.ok) return null;
528
+ const prices = PRICE_PARSERS[provider](await response.json());
529
+ return prices.size ? prices : null;
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+ async function loadRunner(configPath, env, fetchImpl = fetch) {
535
+ const raw = JSON.parse(await readFile2(configPath, "utf-8"));
536
+ const parsed = parseConfig(raw);
537
+ if (!parsed.ok) throw new Error(`${configPath} is not a runner config:
538
+ - ${parsed.problems.join("\n - ")}`);
539
+ const config = parsed.config;
540
+ const apiKey = config.model.keyEnv ? secretFrom(env, config.model.keyEnv) : null;
541
+ const channels = channelsOf(config.channels, env, fetchImpl);
542
+ const stateDir = path2.resolve(path2.dirname(configPath), config.state);
543
+ const fetchCid = ipfsFetcher(config.ipfs, fetchImpl);
544
+ const source = await openBot(config.bot, { client: clientFor(config.bot.chain, rpcOf(config, env)), fetchCid });
545
+ const ceiling = config.ceiling;
546
+ return {
547
+ config,
548
+ stateDir,
549
+ deps: {
550
+ source,
551
+ store: fileStore(stateDir),
552
+ channels,
553
+ chat: (call) => chat({ endpoint: config.model.endpoint, apiKey, ...call }, fetchImpl),
554
+ prices: () => "prices" in ceiling ? priceList(ceiling.prices, fetchImpl) : Promise.resolve(null),
555
+ now: () => /* @__PURE__ */ new Date()
556
+ }
557
+ };
558
+ }
559
+
560
+ export {
561
+ checkReceipt,
562
+ DEFAULT_GATEWAYS,
563
+ parseConfig,
564
+ rpcOf,
565
+ secretsOf,
566
+ redact,
567
+ secretFrom,
568
+ KeyRefused,
569
+ chat,
570
+ brainRefusal,
571
+ chooseBrain,
572
+ RECENT_POSTS,
573
+ buildPrompt,
574
+ postFrom,
575
+ mindOf,
576
+ lastRunOf,
577
+ fileStore,
578
+ recentPosts,
579
+ withLock,
580
+ runPass,
581
+ stdoutChannel,
582
+ webhookChannel,
583
+ telegramChannel,
584
+ channelsOf,
585
+ ipfsFetcher,
586
+ clientFor,
587
+ openBot,
588
+ priceList,
589
+ loadRunner
590
+ };
591
+ //# sourceMappingURL=chunk-YFKTNVGJ.js.map