@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,412 @@
1
+ import { Address, Hex, PublicClient } from 'viem';
2
+ import { PricedProvider, ModelRef, ModelPrices, MindLine, Moment, BotSpec, Mind } from '@websitekit/sdk/agents';
3
+
4
+ /**
5
+ * A runner's configuration: which bot, which chain, which model endpoint and key, what the brain
6
+ * seat may cost, how often to post, where posts go and where receipts are kept. Read from one JSON
7
+ * file and parsed strictly, as a bot's spec is: an unknown field is refused, so a typo is an error
8
+ * rather than a setting silently ignored.
9
+ *
10
+ * **Secrets are never in the file.** It names the environment variable that holds each one
11
+ * (`keyEnv`, `tokenEnv`, `secretEnv`), so the file can be committed and shared.
12
+ *
13
+ * **The ceiling has no default.** A bot's brain seat lets whoever holds that line choose the model
14
+ * this runner pays for; a runner that did not say what it will pay would pay whatever they chose.
15
+ */
16
+ /** What the brain seat may cost this runner. */
17
+ type Ceiling =
18
+ /** Any model on the runner's provider costing at most this per post, priced from that provider's own list. */
19
+ {
20
+ usdPerPost: number;
21
+ prices: PricedProvider;
22
+ }
23
+ /** Only these models, by the provider's id: for a provider with no price list, or a local model. */
24
+ | {
25
+ models: string[];
26
+ };
27
+ type ChannelConfig = {
28
+ kind: 'stdout';
29
+ }
30
+ /** Each receipt, POSTed as JSON; signed when a secret is named. */
31
+ | {
32
+ kind: 'webhook';
33
+ url: string;
34
+ secretEnv: string | null;
35
+ }
36
+ /** Each post, sent by the runner's own Telegram bot to a chat or channel it can post in. */
37
+ | {
38
+ kind: 'telegram';
39
+ tokenEnv: string;
40
+ chat: string;
41
+ };
42
+ interface RunnerConfig {
43
+ bot: {
44
+ chain: number;
45
+ /** Its token in the Agents collection, or its lines' address: exactly one. */
46
+ token: bigint | null;
47
+ site: Address | null;
48
+ /** The collection; the chain's own when absent. */
49
+ collection: Address | null;
50
+ };
51
+ /** A JSON-RPC endpoint for the chain; the chain's public one when absent. */
52
+ rpc: string | null;
53
+ /**
54
+ * Instead, the variable holding it: a keyed endpoint is a secret. `check` on an older receipt needs
55
+ * one that answers for old blocks (an archive node); a public endpoint may not.
56
+ */
57
+ rpcEnv: string | null;
58
+ /** IPFS gateways, tried in order. Every byte is checked against its address whichever answers. */
59
+ ipfs: string[];
60
+ model: {
61
+ /** An OpenAI-shaped API's base, e.g. `https://openrouter.ai/api/v1`; `/chat/completions` is added. */
62
+ endpoint: string;
63
+ /** The variable holding the API key; null for an endpoint that needs none (a local model). */
64
+ keyEnv: string | null;
65
+ /** The provider a brain seat must name for this runner to run its model, e.g. `openrouter`. */
66
+ provider: string;
67
+ /** The runner's own model: what writes when the brain seat names nothing this runner will pay for. */
68
+ default: string;
69
+ /** The longest answer asked for. Also what a post is priced at. */
70
+ maxTokens: number;
71
+ };
72
+ ceiling: Ceiling;
73
+ posts: {
74
+ everyHours: number;
75
+ maxChars: number;
76
+ /** The runner's own rules, added after the mind section and the length. */
77
+ rules: string | null;
78
+ };
79
+ channels: ChannelConfig[];
80
+ /** Where receipts are kept. Relative to the config file. They are also the runner's memory. */
81
+ state: string;
82
+ }
83
+ declare const DEFAULT_GATEWAYS: string[];
84
+ type Parsed = {
85
+ ok: true;
86
+ config: RunnerConfig;
87
+ } | {
88
+ ok: false;
89
+ problems: string[];
90
+ };
91
+ declare function parseConfig(raw: unknown): Parsed;
92
+ /** A named secret from the environment, or a refusal that names the variable and never a value. */
93
+ declare function secretFrom(env: Record<string, string | undefined>, name: string): string;
94
+
95
+ /**
96
+ * Which model writes: the one the bot's brain seat names, when this runner will pay for it, and
97
+ * otherwise the runner's own (`AGENT-SPEC.md`, the brain seat). Pure.
98
+ *
99
+ * **The seat is honoured under a ceiling the runner sets.** Whoever holds the brain line chooses a
100
+ * model that somebody else pays for, so a brain this runner cannot price, or that costs more per
101
+ * post than its ceiling, falls back to the runner's own model, and the receipt says why. The
102
+ * runner's own model is never measured: it is the runner's own choice of what to spend.
103
+ */
104
+ interface BrainChoice {
105
+ /** The model asked to write, on the runner's provider. */
106
+ model: string;
107
+ /** What the brain seat named, or null when the bot has no brain seat. */
108
+ chosen: ModelRef | null;
109
+ /** Why `chosen` is not what writes; null when it is, or when nothing was chosen. */
110
+ refused: string | null;
111
+ }
112
+ interface BrainTerms {
113
+ provider: string;
114
+ fallback: string;
115
+ ceiling: Ceiling;
116
+ /** The provider's price list; null when it could not be read, which refuses every priced brain. */
117
+ prices: ModelPrices | null;
118
+ /** The prompt about to be sent, in tokens (`promptTokensOf`), and the longest answer asked for. */
119
+ promptTokens: number;
120
+ maxTokens: number;
121
+ }
122
+ /** Why this runner will not pay for `chosen`, or null when it will. */
123
+ declare function brainRefusal(chosen: ModelRef, t: BrainTerms): string | null;
124
+ declare function chooseBrain(lines: readonly MindLine[], t: BrainTerms): BrainChoice;
125
+
126
+ /**
127
+ * This runner's prompt around a bot's mind. The mind section is the protocol's and comes first,
128
+ * unchanged, so its hash is what anyone can rebuild; everything here comes after it and is this
129
+ * runner's own: the length, the runner's rules, recent posts and the moment. Pure.
130
+ *
131
+ * Holders' words only appear inside the mind section and the moment's escaped blocks, never spliced
132
+ * into a sentence of the runner's.
133
+ */
134
+ /** How many recent posts go into the prompt, so the bot does not repeat itself. */
135
+ declare const RECENT_POSTS = 10;
136
+ interface Prompt {
137
+ system: string;
138
+ user: string;
139
+ }
140
+ declare function buildPrompt(input: {
141
+ /** The mind section, exactly as built from the chain (`mindSection`). */
142
+ section: string;
143
+ /** Newest first. */
144
+ recent: string[];
145
+ moment: Moment;
146
+ now: Date;
147
+ maxChars: number;
148
+ rules: string | null;
149
+ /** Why the previous attempt was refused, on a retry. */
150
+ refused?: string;
151
+ }): Prompt;
152
+ /** What a model wrote, as a post: trimmed, and one pair of wrapping quotation marks taken off. */
153
+ declare function postFrom(text: string): string;
154
+
155
+ /**
156
+ * One call to an OpenAI-shaped chat endpoint (OpenRouter, Venice, a local server), with the runner's
157
+ * own key. Plain `fetch`, no SDK of any provider's.
158
+ */
159
+ interface ChatAnswer {
160
+ text: string;
161
+ /** The model that answered, as the endpoint says; the one asked for when it does not say. */
162
+ model: string;
163
+ usage: {
164
+ promptTokens: number | null;
165
+ completionTokens: number | null;
166
+ costUsd: number | null;
167
+ };
168
+ }
169
+ /** The key was refused (401, 402, 403): nothing a retry or another prompt fixes. The runner stops. */
170
+ declare class KeyRefused extends Error {
171
+ }
172
+ interface ChatCall {
173
+ endpoint: string;
174
+ apiKey: string | null;
175
+ model: string;
176
+ system: string;
177
+ user: string;
178
+ maxTokens: number;
179
+ }
180
+ declare function chat(call: ChatCall, fetchImpl?: typeof fetch): Promise<ChatAnswer>;
181
+
182
+ /**
183
+ * A receipt: what the runner read and what it wrote, one per output. Its `mindHash` is checkable by
184
+ * anyone from the chain at `block` and IPFS (`checkReceipt`); its body is the runner's word.
185
+ *
186
+ * **The same shape as the receipts a site serving bots publishes** (`/v1/minds/<bot>/outputs/<id>`) — `bot`,
187
+ * `token`, `block`, `spec`, `mindHash`, `mind` — so one checker reads both. What a runner adds is
188
+ * after: the chain, which brain the seat chose and why it was refused, why an attempt failed.
189
+ * Names no holder: a line is owned or rented, never by whom.
190
+ */
191
+ interface Receipt {
192
+ /** The site the bot's lines are. */
193
+ bot: Address;
194
+ token: {
195
+ collection: Address;
196
+ id: string;
197
+ };
198
+ chain: number;
199
+ /** The runner's own count, from 1. */
200
+ id: string;
201
+ kind: 'scheduled' | 'reaction' | 'failed';
202
+ /** The post; null when the attempt failed. */
203
+ body: string | null;
204
+ failure: string | null;
205
+ /** The model that answered, as its endpoint says. */
206
+ model: string;
207
+ brain: {
208
+ asked: string;
209
+ chosen: ModelRef | null;
210
+ refused: string | null;
211
+ };
212
+ /** The spec's IPFS address. */
213
+ spec: string;
214
+ block: string;
215
+ mindHash: Hex;
216
+ moment: Moment;
217
+ at: string;
218
+ /** The mind as read, most expensive first: brain and face included. */
219
+ mind: Array<{
220
+ key: string;
221
+ label: string;
222
+ kind: string;
223
+ words: string | null;
224
+ source: 'chain' | 'default';
225
+ price: string;
226
+ rented: boolean;
227
+ }>;
228
+ }
229
+ declare function mindOf(lines: readonly MindLine[]): Receipt['mind'];
230
+ /** The receipt's lines as the SDK's schedule reads a last run. */
231
+ declare function lastRunOf(receipt: Pick<Receipt, 'mind' | 'at'> | null): {
232
+ lines: {
233
+ key: string;
234
+ text: string | null;
235
+ }[];
236
+ at: Date;
237
+ } | null;
238
+
239
+ /**
240
+ * Where a run's output goes. Each is an adapter with one method; the runner sends every receipt to
241
+ * every channel, and each decides what of it to say: standard output says everything, a webhook gets
242
+ * the whole receipt, Telegram gets the post alone and nothing for a failed attempt.
243
+ */
244
+ interface Channel {
245
+ name: string;
246
+ send(receipt: Receipt): Promise<void>;
247
+ }
248
+ declare function stdoutChannel(write?: (text: string) => void): Channel;
249
+ /**
250
+ * Each receipt POSTed as JSON. With a secret, signed: `x-websitekit-signature: sha256=<hex>` over the
251
+ * exact body, so the receiver can tell it came from this runner.
252
+ */
253
+ declare function webhookChannel(url: string, secret: string | null, fetchImpl?: typeof fetch): Channel;
254
+ /**
255
+ * The post, sent by the runner's own Telegram bot (made with @BotFather, free) to a chat or channel
256
+ * it can post in. The token is in every Bot API address, so a failure names Telegram's words only.
257
+ */
258
+ declare function telegramChannel(token: string, chat: string, fetchImpl?: typeof fetch): Channel;
259
+ /** The configured channels, with their secrets read from the environment now. */
260
+ declare function channelsOf(configs: readonly ChannelConfig[], env: Record<string, string | undefined>, fetchImpl?: typeof fetch): Channel[];
261
+
262
+ /**
263
+ * Where a runner keeps its receipts, which are also its memory: the newest is what the next run
264
+ * compares the mind against, and the recent posts go back into the prompt. One JSON line per
265
+ * receipt, appended, never rewritten.
266
+ */
267
+ interface Store {
268
+ receipts(): Promise<Receipt[]>;
269
+ append(receipt: Receipt): Promise<void>;
270
+ /** A delivery's outcome, kept apart so a receipt stays what was read and what was written. */
271
+ delivered(entry: {
272
+ id: string;
273
+ channel: string;
274
+ ok: boolean;
275
+ error: string | null;
276
+ at: string;
277
+ }): Promise<void>;
278
+ }
279
+ declare function fileStore(dir: string): Store;
280
+ /** Newest first, posts only: a failed attempt said nothing. */
281
+ declare function recentPosts(receipts: readonly Receipt[], limit: number): string[];
282
+ /**
283
+ * One pass at a time per state directory, so a cron that overlaps a slow run skips it rather than
284
+ * posting twice. Null when another run holds the lock.
285
+ */
286
+ declare function withLock<T>(dir: string, work: () => Promise<T>, now?: number): Promise<{
287
+ value: T;
288
+ } | null>;
289
+
290
+ /**
291
+ * A bot read from the chain and IPFS alone, the way any runner reads one: its token in the Agents
292
+ * collection, its spec by the digest the collection records, and its mind at a block. Nothing from
293
+ * any site, so a runner keeps working whatever a site does.
294
+ */
295
+ interface BotRef {
296
+ chain: number;
297
+ token: bigint | null;
298
+ site: Address | null;
299
+ collection: Address | null;
300
+ }
301
+ interface MindRead {
302
+ mind: Mind;
303
+ section: string;
304
+ mindHash: Hex;
305
+ }
306
+ interface BotSource {
307
+ chain: number;
308
+ collection: Address;
309
+ token: bigint;
310
+ site: Address;
311
+ spec: BotSpec;
312
+ specCid: string;
313
+ /** The mind at `block`, or at the head when absent. */
314
+ read(block?: bigint): Promise<MindRead>;
315
+ }
316
+ /**
317
+ * An IPFS fetch that returns bytes only when they hash to the address asked for, from the first
318
+ * gateway that serves them so. A gateway is never trusted: a wrong byte is the next gateway's turn.
319
+ */
320
+ declare function ipfsFetcher(gateways: readonly string[], fetchImpl?: typeof fetch): (cid: string) => Promise<Uint8Array | null>;
321
+ declare function clientFor(chain: number, rpc: string | null): PublicClient;
322
+ declare function openBot(ref: BotRef, o: {
323
+ client: PublicClient;
324
+ fetchCid: (cid: string) => Promise<Uint8Array | null>;
325
+ }): Promise<BotSource>;
326
+
327
+ /**
328
+ * One pass of the runner: read the mind at the head, decide whether a post is due (the SDK's
329
+ * `nextMoment`, the rule every runner shares), choose the brain under the ceiling, write,
330
+ * keep the receipt, then send it to every channel.
331
+ *
332
+ * A model that cannot write a post twice is recorded as a `failed` receipt, which moves the schedule
333
+ * as a post does, so the same change is not retried every pass. A refused KEY records nothing and
334
+ * stops the pass: no prompt fixes it, and a failed receipt would swallow the change it was for.
335
+ */
336
+ interface PassDeps {
337
+ source: BotSource;
338
+ store: Store;
339
+ channels: Channel[];
340
+ /** The runner's model call, with its key already in hand. */
341
+ chat: (call: {
342
+ model: string;
343
+ system: string;
344
+ user: string;
345
+ maxTokens: number;
346
+ }) => Promise<ChatAnswer>;
347
+ /** The provider's price list, or null when it cannot be read. Asked only when a ceiling prices. */
348
+ prices: () => Promise<ModelPrices | null>;
349
+ now: () => Date;
350
+ /**
351
+ * The runner's own check on what was written, after the length: a reason to refuse it, or null.
352
+ * Optional. Code, a list of words, a classifier: the runner's rules, never the protocol's.
353
+ */
354
+ check?: (post: string) => string | null | Promise<string | null>;
355
+ }
356
+ type PassResult = {
357
+ kind: 'not-due';
358
+ } | {
359
+ kind: 'written';
360
+ receipt: Receipt;
361
+ deliveries: Array<{
362
+ channel: string;
363
+ ok: boolean;
364
+ error: string | null;
365
+ }>;
366
+ };
367
+ declare function runPass(config: RunnerConfig, deps: PassDeps): Promise<PassResult>;
368
+
369
+ /**
370
+ * A receipt checked against the chain: its mind rebuilt at its block from the chain and IPFS, and
371
+ * the hash compared with the one it records. Equal means the output was written from exactly the
372
+ * mind it says. It says nothing about the output itself, which is the runner's word.
373
+ *
374
+ * Works on this runner's receipts and on the ones a site serving bots may publish
375
+ * (`/v1/minds/<bot>/outputs/<id>`):
376
+ * both carry `bot`, `token`, `block`, `spec` and `mindHash`.
377
+ */
378
+ interface Checkable {
379
+ id?: string;
380
+ bot: Address;
381
+ token: {
382
+ collection: Address;
383
+ id: string;
384
+ };
385
+ block: string;
386
+ spec: string;
387
+ mindHash: Hex;
388
+ }
389
+ interface CheckOutcome {
390
+ id: string | null;
391
+ block: string;
392
+ ok: boolean;
393
+ /** Why it does not match; null when it does. */
394
+ problem: string | null;
395
+ }
396
+ declare function checkReceipt(receipt: Checkable, source: BotSource): Promise<CheckOutcome>;
397
+
398
+ /** A provider's price list, read now; null when it cannot be read or reads as empty. */
399
+ declare function priceList(provider: PricedProvider, fetchImpl?: typeof fetch): Promise<ModelPrices | null>;
400
+ interface Runner {
401
+ config: RunnerConfig;
402
+ /** The state directory, resolved against the config file. */
403
+ stateDir: string;
404
+ deps: PassDeps;
405
+ }
406
+ /**
407
+ * Everything a pass needs, from a config file and the environment: the file parsed strictly, every
408
+ * named secret read now (a missing one stops here, before the chain is read), the bot opened.
409
+ */
410
+ declare function loadRunner(configPath: string, env: Record<string, string | undefined>, fetchImpl?: typeof fetch): Promise<Runner>;
411
+
412
+ export { type BotRef, type BotSource, type BrainChoice, type BrainTerms, type Ceiling, type Channel, type ChannelConfig, type ChatAnswer, type ChatCall, type CheckOutcome, type Checkable, DEFAULT_GATEWAYS, KeyRefused, type MindRead, type PassDeps, type PassResult, type Prompt, RECENT_POSTS, type Receipt, type Runner, type RunnerConfig, type Store, brainRefusal, buildPrompt, channelsOf, chat, checkReceipt, chooseBrain, clientFor, fileStore, ipfsFetcher, lastRunOf, loadRunner, mindOf, openBot, parseConfig, postFrom, priceList, recentPosts, runPass, secretFrom, stdoutChannel, telegramChannel, webhookChannel, withLock };
package/dist/index.js ADDED
@@ -0,0 +1,57 @@
1
+ import {
2
+ DEFAULT_GATEWAYS,
3
+ KeyRefused,
4
+ RECENT_POSTS,
5
+ brainRefusal,
6
+ buildPrompt,
7
+ channelsOf,
8
+ chat,
9
+ checkReceipt,
10
+ chooseBrain,
11
+ clientFor,
12
+ fileStore,
13
+ ipfsFetcher,
14
+ lastRunOf,
15
+ loadRunner,
16
+ mindOf,
17
+ openBot,
18
+ parseConfig,
19
+ postFrom,
20
+ priceList,
21
+ recentPosts,
22
+ runPass,
23
+ secretFrom,
24
+ stdoutChannel,
25
+ telegramChannel,
26
+ webhookChannel,
27
+ withLock
28
+ } from "./chunk-YFKTNVGJ.js";
29
+ export {
30
+ DEFAULT_GATEWAYS,
31
+ KeyRefused,
32
+ RECENT_POSTS,
33
+ brainRefusal,
34
+ buildPrompt,
35
+ channelsOf,
36
+ chat,
37
+ checkReceipt,
38
+ chooseBrain,
39
+ clientFor,
40
+ fileStore,
41
+ ipfsFetcher,
42
+ lastRunOf,
43
+ loadRunner,
44
+ mindOf,
45
+ openBot,
46
+ parseConfig,
47
+ postFrom,
48
+ priceList,
49
+ recentPosts,
50
+ runPass,
51
+ secretFrom,
52
+ stdoutChannel,
53
+ telegramChannel,
54
+ webhookChannel,
55
+ withLock
56
+ };
57
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@websitekit/runner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Run a websitekit bot yourself: read its mind from the chain and IPFS, write its posts with your own model key, keep a receipt of each.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/vibecodermaxi/websitekit.git",
9
+ "directory": "packages/websitekit-runner"
10
+ },
11
+ "homepage": "https://websitekit.org",
12
+ "bugs": {
13
+ "url": "https://github.com/vibecodermaxi/websitekit/issues"
14
+ },
15
+ "keywords": [
16
+ "bot",
17
+ "agent",
18
+ "llm",
19
+ "onchain",
20
+ "websitekit"
21
+ ],
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "main": "./dist/index.js",
25
+ "types": "./dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "import": "./dist/index.js"
30
+ }
31
+ },
32
+ "bin": {
33
+ "websitekit-run": "./dist/cli.js"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md",
38
+ "LICENSE"
39
+ ],
40
+ "publishConfig": {
41
+ "access": "public"
42
+ },
43
+ "engines": {
44
+ "node": ">=20"
45
+ },
46
+ "dependencies": {
47
+ "viem": "2.55.8",
48
+ "@websitekit/sdk": "^0.7.0"
49
+ },
50
+ "devDependencies": {
51
+ "@types/node": "26.1.1"
52
+ },
53
+ "scripts": {
54
+ "build": "tsup",
55
+ "test": "vitest run --passWithNoTests",
56
+ "lint": "tsc --noEmit"
57
+ }
6
58
  }