irida 0.0.0-stage → 0.1.1

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.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Irida
4
+ Copyright (c) 2026 Chronark Labs
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # irida
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sandboxes for agents, with a gate. Code runs in a sealed Irida sandbox, billed per second in USDG, with one way out:
4
+
5
+ - **Allowlist.** HTTPS only to the hosts you name. Names that resolve to private or local addresses are refused. Everything else gets a 403, and the refusal is logged.
6
+ - **Broker.** API keys stay on your machine and are added at the gate, outside the sandbox. Code calls `$IRIDA_GATE/<name>/<path>`. The key is never in the sandbox's environment, files, output or receipt.
7
+ - **Receipt.** When a session closes, the node signs one ed25519 receipt with the commands, seconds, money, an output hash and the gate log: host, method, path, status and bytes for every request.
8
+ - **Anchor.** Every hour, receipts are sealed into a merkle batch. Each batch head chains to the one before it and is posted to Robinhood Chain.
9
+
10
+ ```sh
11
+ npx irida run --cloud --allow pypi.org,files.pythonhosted.org -- pip download requests
12
+ ```
13
+
14
+ Try it with no key at all: `curl -XPOST https://api.irida.run/v1/try -d '{"worker":"python","cmd":"python3 -c \"print(2**64)\""}'` returns the output and its signed receipt.
15
+
16
+ A new account gets 0.02 USDG of cloud time on its first request, once. There is no signup: your account is an ed25519 key in `~/.irida`.
17
+
18
+ ## Keys through the broker
19
+
20
+ ```sh
21
+ echo "$OPENAI_API_KEY" | irida secret add openai https://api.openai.com --only "POST /v1/responses" --max 20
22
+ irida run --cloud --worker python --secret openai -- python ask.py
23
+ ```
24
+
25
+ `--only` limits the calls the key may be used for (method and path, `*` one segment, `**` any) and `--max` how many per session. The gate checks both, adds the key outside the sandbox, and strips the key from anything the API sends back.
26
+
27
+ ```python
28
+ # ask.py
29
+ import os, requests
30
+ r = requests.post(os.environ["IRIDA_GATE"] + "/openai/v1/responses", json={"model": "gpt-5", "input": "hi"})
31
+ ```
32
+
33
+ ## Agents (MCP)
34
+
35
+ ```sh
36
+ claude mcp add irida -- npx -y irida mcp --allow pypi.org,files.pythonhosted.org,api.github.com
37
+ ```
38
+
39
+ `--allow` sets the most an agent can open the gate to. An agent can ask for fewer hosts, never others. It uses your stored keys by name and never sees the values.
40
+
41
+ Tools: `irida_run`, `irida_session_open`, `irida_exec`, `irida_session_close`, `irida_account`, `irida_quote`, `irida_verify`, `irida_receipts`, `irida_prove`.
42
+
43
+ ## Verify
44
+
45
+ ```sh
46
+ irida verify <receipt.json | session id | receipt URL> [--log] [--offline] [--rpc <chain rpc>]
47
+ ```
48
+
49
+ This checks the signature, prints the gate summary, checks the receipt's merkle path to its batch, then reads the anchoring transaction from Robinhood Chain itself and checks the contract holds that head.
50
+
51
+ ## Prove the node
52
+
53
+ ```sh
54
+ npx irida prove
55
+ ```
56
+
57
+ Checks the node end to end with no key and no wallet. It runs a probe in a real sandbox through `POST /v1/try` and judges it from the signed receipt: signature, output hash, per-second billing, the gate refusing an unlisted host and the cloud metadata address (both in the signed gate log), the allowlisted host reached, and no network outside the gate. Then it compares the public copy of the receipt, reads the node's own half-hourly self-check (`/v1/canary`), checks the signed manifest (`/v1/manifest`) and walks one anchored receipt down to the chain.
58
+
59
+ Docs: https://irida.run/docs · Playground: https://irida.run/play · Scan: https://irida.run/scan · X: https://x.com/irida_rh
60
+
61
+ MIT. Based on the MIT-licensed Chronark engine.
package/bin/irida.js ADDED
@@ -0,0 +1,355 @@
1
+ #!/usr/bin/env node
2
+ // irida: wrap any command, meter it by the second, get a signed receipt.
3
+ import { readFileSync } from "node:fs";
4
+ import { basename } from "node:path";
5
+ import { constants } from "node:os";
6
+ import { open, quote, receipts, verifyReceipt, whoami, cloud, DEFAULT_RATE, DEFAULT_CLOUD, scanUrl } from "../src/index.js";
7
+ import { addSecret, removeSecret, listSecrets, resolveSecrets } from "../src/secrets.js";
8
+ import { checkProof, checkChain, DEFAULT_RPC } from "../src/proof.js";
9
+ import { prove } from "../src/prove.js";
10
+
11
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
12
+ const tty = process.stderr.isTTY && !process.env.NO_COLOR;
13
+ const c = (n) => (s) => (tty ? `\x1b[${n}m${s}\x1b[0m` : String(s));
14
+ const dim = c("90"), ok = c("36"), warm = c("33"), bold = c("1"), red = c("31");
15
+ const short = (h) => h.slice(0, 6) + "…" + h.slice(-4);
16
+ const err = (...a) => process.stderr.write(a.join(" ") + "\n");
17
+
18
+ const HELP = `${bold("irida")} ${pkg.version} · sandboxes for agents, with a gate: internet by allowlist, keys that never enter, every request on the receipt
19
+
20
+ ${bold("Usage")}
21
+ irida run [--budget 2.00] [--rate ${DEFAULT_RATE}] [--worker name] -- <command> [args...]
22
+ irida run --cloud [url] [--budget 0.24] [--worker shell|python|node] -- <command> [args...]
23
+ irida run --cloud --allow api.github.com,pypi.org,files.pythonhosted.org --secret openai -- <command>
24
+ irida secret add <name> <https origin> [--header authorization] [--only "GET /repos/*,POST /v1/**"] [--max 50]
25
+ ${dim("# value from stdin, kept in ~/.irida; --only and --max are enforced at the gate")}
26
+ irida secret ls | irida secret rm <name>
27
+ irida account [--cloud [url]]
28
+ irida quote <seconds> [--rate ${DEFAULT_RATE}]
29
+ irida receipts [--json]
30
+ irida verify <receipt.json | session id | receipt URL> [--rpc <chain rpc>] ${dim("# signature, merkle proof, and the head read from the chain")}
31
+ irida prove [url] [--json] [--no-chain] ${dim("# check a node end to end: no key, no wallet, no trust needed")}
32
+ irida whoami
33
+ irida mcp [--cloud url] [--max-budget 0.10] [--allow hosts] ${dim("# MCP server: agents rent the sandbox themselves")}
34
+ irida mcp setup ${dim("# print the config for Claude Code, Claude Desktop, Cursor")}
35
+
36
+ ${bold("Examples")}
37
+ irida run --budget 2.00 -- python scraper.py
38
+ irida run --budget 0.01 -- sleep 60 ${dim("# stopped at 25 s when the budget runs out")}
39
+ echo "$OPENAI_API_KEY" | irida secret add openai https://api.openai.com
40
+ irida run --cloud --worker python --secret openai -- python ask.py ${dim("# ask.py calls $IRIDA_GATE/openai/v1/…")}
41
+ irida verify ~/.irida/receipts/0x….json
42
+
43
+ Money is in USDG, billed per started second.
44
+ Local mode (default): your machine is the worker, receipts are signed by a
45
+ local key and no funds move (settlement: local).
46
+ Cloud sandboxes have no network unless you open the gate: --allow lists the
47
+ hosts HTTPS may reach (port 443, public addresses only), --secret names keys
48
+ from your local keychain that code uses through $IRIDA_GATE/<name>/<path>.
49
+ The key is added at the gate, outside the sandbox. The receipt lists every
50
+ request: host, method, path, bytes, status and a hash of each brokered reply.
51
+
52
+ Cloud mode (--cloud, --cloud <url> or IRIDA_CLOUD; bare --cloud uses IRIDA_CLOUD,\nelse ${DEFAULT_CLOUD}): the command runs in a sandbox
53
+ on an Irida node, paid from your balance there (settlement: ledger). Your
54
+ account is your local key; \`irida account\` prints its id for funding.
55
+ State lives in ~/.irida (IRIDA_HOME).`;
56
+
57
+ function flags(argv) {
58
+ const f = {}, rest = [];
59
+ for (let i = 0; i < argv.length; i++) {
60
+ const a = argv[i];
61
+ if (a === "--") { rest.push(...argv.slice(i + 1)); f["--"] = true; break; }
62
+ if (a.startsWith("--")) {
63
+ const [k, v] = a.slice(2).split("=");
64
+ if (["json", "help", "version", "local", "log", "offline", "quiet"].includes(k)) f[k] = true;
65
+ else if (k === "cloud" && v === undefined && (i + 1 >= argv.length || argv[i + 1].startsWith("--"))) f[k] = process.env.IRIDA_CLOUD || DEFAULT_CLOUD; // bare --cloud: your IRIDA_CLOUD, else the public node
66
+ else f[k] = v ?? argv[++i];
67
+ } else rest.push(a);
68
+ }
69
+ return { f, rest };
70
+ }
71
+
72
+ async function run(f, cmd) {
73
+ if (!cmd.length) { err(red("✗"), "nothing to run. Put the command after --, e.g. irida run -- python main.py"); return 2; }
74
+ const url = f.local ? null : (f.cloud ?? process.env.IRIDA_CLOUD);
75
+ if (url) return runCloud(f, cmd, url);
76
+ const worker = f.worker || basename(cmd[0]);
77
+ const bar = (n, max) => { const w = 12, k = Math.min(w, Math.round((n / max) * w)); return ok("█".repeat(k)) + dim("░".repeat(w - k)); };
78
+ let line = "", last = { seconds: 0, cost: "0.0000" };
79
+ const draw = () => { if (tty) process.stderr.write("\r\x1b[2K" + line); };
80
+ const clear = () => { if (tty && line) process.stderr.write("\r\x1b[2K"); };
81
+
82
+ const s = await open({ worker, budget: f.budget ?? "2.00", rate: f.rate ?? DEFAULT_RATE, onTick: (t) => {
83
+ last = t;
84
+ line = `${warm("⧗")} metering ${String(t.seconds).padStart(4)}s ${bar(t.seconds, t.max)} ${t.cost} USDG`;
85
+ draw();
86
+ } });
87
+ err(`${ok("✓")} session opened ${dim(short(s.id))}`);
88
+ err(` rate ${s.rate.replace(/0+$/, "")} USDG/s · budget ${s.budget.replace(/0{1,4}$/, "")} USDG · worker ${worker} · ${dim("local node " + short(s.node))}`);
89
+
90
+ const onSig = () => {}; // let the child receive Ctrl-C; we still sign what was used
91
+ process.on("SIGINT", onSig);
92
+ let res;
93
+ try {
94
+ res = await s.exec(cmd, { stdio: "tee", onData: (k, b) => { clear(); (k === "stdout" ? process.stdout : process.stderr).write(b); draw(); } });
95
+ } catch (e) {
96
+ clear(); err(red("✗"), `could not start ${cmd[0]}: ${e.message}`);
97
+ res = { code: 127 };
98
+ }
99
+ process.off("SIGINT", onSig);
100
+ const r = await s.stop();
101
+ clear();
102
+ err(`${warm("⧗")} metered ${String(r.seconds).padStart(4)}s ${bar(r.seconds, s.maxSeconds)} ${s.cost(r.seconds)} USDG`);
103
+ if (r.status === "budget_exhausted") err(`${red("■")} budget exhausted, command stopped after ${r.seconds}s`);
104
+ err(`${ok("✓")} receipt signed ${dim(r.file.replace(process.env.HOME || "~", "~"))}`);
105
+ err(`${ok("✓")} settled ${warm(r.paid.replace(/(\.\d{4})\d+/, "$1"))} · refund ${r.refund.replace(/(\.\d{4})\d+/, "$1")} ${dim("(local run: metered and signed, no funds moved · add --cloud for a paid sandbox)")}`);
106
+ if (r.status === "budget_exhausted") return 124;
107
+ return res.code ?? (res.signal ? 128 + (constants.signals[res.signal] ?? 0) : 1); // 130 after Ctrl-C, like a shell
108
+ }
109
+
110
+ async function runCloud(f, cmd, url) {
111
+ const c = cloud(url);
112
+ const bar = (n, max) => { const w = 12, k = Math.min(w, Math.round((n / max) * w)); return ok("█".repeat(k)) + dim("░".repeat(w - k)); };
113
+ let line = "";
114
+ const draw = () => { if (tty) process.stderr.write("\r\x1b[2K" + line); };
115
+ const clear = () => { if (tty && line) process.stderr.write("\r\x1b[2K"); };
116
+ const worker = f.worker || "shell";
117
+ let s, net;
118
+ try {
119
+ const allow = String(f.allow ?? "").split(",").map((x) => x.trim()).filter(Boolean);
120
+ const secrets = resolveSecrets(String(f.secret ?? "").split(",").map((x) => x.trim()).filter(Boolean));
121
+ net = allow.length || secrets.length ? { allow, secrets } : undefined;
122
+ s = await c.open({ worker, budget: f.budget ?? "0.24", fit: f.budget == null, net, onTick: (t) => { line = `${warm("⧗")} metering ${String(t.seconds).padStart(4)}s ${bar(t.seconds, t.max)} ${t.cost}`; draw(); } });
123
+ } catch (e) {
124
+ err(red("✗"), e.message);
125
+ if (e.status === 402) err(dim(` fund your account first: irida account --cloud ${c.url}`));
126
+ return e.status === 402 ? 3 : 1;
127
+ }
128
+ err(`${ok("✓")} session opened ${dim(short(s.id))} ${dim(c.url)}`);
129
+ const cur = s.currency || "USDG";
130
+ err(` rate ${s.rate.replace(/0+$/, "")} ${cur}/s · budget ${s.budget.replace(/0{1,4}$/, "")} ${cur} · worker ${worker} (${s.image}) · ${dim("node " + short(s.node))}`);
131
+ err(s.net ? ` gate ${ok("open")} · allow ${s.net.allow.join(", ") || "-"}${s.net.secrets.length ? " · keys " + s.net.secrets.join(", ") + dim(" (via $IRIDA_GATE)") : ""}` : ` gate ${dim("closed · no network")}`);
132
+ const gateLine = (e) => e.k === "deny" ? `${red("⊘")} ${dim("gate")} refused ${e.host}${e.path ?? ""} ${dim("(" + e.why + ")")}`
133
+ : e.k === "broker" ? `${ok("⇄")} ${dim("gate")} ${e.method} ${e.secret}${e.path} → ${e.status} ${dim(fmtB(e.up) + " up · " + fmtB(e.down) + " down · key added at the gate")}`
134
+ : e.open ? `${ok("⇄")} ${dim("gate")} https ${e.host} ${dim("tunnel open")}`
135
+ : `${ok("⇄")} ${dim("gate")} ${e.k === "tls" ? "https" : e.method} ${e.host}${e.path ?? ""}${e.status ? " → " + e.status : ""} ${dim(fmtB(e.up) + " up · " + fmtB(e.down) + " down")}`;
136
+ let res = { code: 1 };
137
+ let interrupted = false;
138
+ const onSig = () => { interrupted = true; s.stop().catch(() => {}); };
139
+ process.once("SIGINT", onSig);
140
+ try { res = await s.exec(cmd, { onData: (k, b) => { clear(); (k === "stdout" ? process.stdout : process.stderr).write(b); draw(); }, onGate: f.quiet ? null : (e) => { clear(); err(gateLine(e)); draw(); } }); }
141
+ catch (e) { clear(); err(red("✗"), e.message); }
142
+ process.off("SIGINT", onSig);
143
+ const r = await s.stop();
144
+ clear();
145
+ err(`${warm("⧗")} metered ${String(r.seconds).padStart(4)}s ${bar(r.seconds, s.maxSeconds)} ${r.paid.replace(/(\.\d{4})\d+/, "$1")}`);
146
+ if (r.status === "budget_exhausted") err(`${red("■")} budget exhausted, the sandbox was stopped after ${r.seconds}s`);
147
+ err(`${ok("✓")} receipt signed ${dim(r.file.replace(process.env.HOME || "~", "~"))}`);
148
+ err(`${ok("✓")} settled ${warm(r.paid.replace(/(\.\d{4})\d+/, "$1"))} · refund ${r.refund.replace(/(\.\d{4})\d+/, "$1")} ${dim("(ledger)")}`);
149
+ if (r.net) err(`${ok("✓")} gate on receipt ${r.net.requests} request${r.net.requests === 1 ? "" : "s"} · ${r.net.denied} refused · ${fmtB(r.net.up)} up · ${fmtB(r.net.down)} down`);
150
+ const scan = scanUrl(c.url, r.session);
151
+ if (scan) err(`${ok("✓")} public proof ${scan}`);
152
+ if (r.status === "budget_exhausted") return 124;
153
+ if (interrupted) return 130;
154
+ return res.code ?? (res.signal ? 128 + (constants.signals[res.signal] ?? 0) : 1); // 130 after Ctrl-C, like a shell
155
+ }
156
+
157
+ /** Finds a receipt from anything the CLI prints or a user might paste: a file path (with ~), a full or shortened
158
+ * session id (0x2a9b…03d1), a public receipt URL, a receipts list, or a node reply that wraps the receipt. */
159
+ async function load(arg) {
160
+ const home = process.env.HOME || "";
161
+ const unwrap = (j) => {
162
+ if (Array.isArray(j)) { if (j.length === 1) j = j[0]; else throw new Error(`that file holds ${j.length} receipts; pass one session id instead`); }
163
+ if (j && !j.sig && j.receipt && typeof j.receipt === "object") j = j.receipt;
164
+ if (j && typeof j === "object") delete j.file;
165
+ return j;
166
+ };
167
+ const byId = (id) => {
168
+ const [a, b] = id.split(/…|\.\.\./);
169
+ const hit = receipts().filter((r) => r.session.startsWith(a) && (!b || r.session.endsWith(b)));
170
+ if (hit.length !== 1) throw new Error(hit.length ? "more than one receipt matches that id" : `no receipt with session ${id} in ${home ? "~/.irida/receipts" : "the receipts folder"}`);
171
+ const { file, ...r } = hit[0]; return r;
172
+ };
173
+ if (/^https?:\/\//.test(arg)) {
174
+ const res = await fetch(arg).catch((e) => { throw new Error(`could not fetch ${arg}: ${e.message}`); });
175
+ if (!res.ok) throw new Error(`${arg} answered ${res.status}`);
176
+ return unwrap(await res.json());
177
+ }
178
+ if (/^0x[0-9a-f]{4,}((…|\.\.\.)[0-9a-f]{2,})?$/i.test(arg)) return byId(arg);
179
+ let path = arg.replace(/^~(?=\/|$)/, home), text;
180
+ try { text = readFileSync(path, "utf8"); }
181
+ catch (e) {
182
+ if (e.code === "EISDIR") throw new Error(`${arg} is a folder; pass one receipt file or a session id (see irida receipts)`);
183
+ if (e.code !== "ENOENT") throw e;
184
+ const m = arg.match(/0x[0-9a-f]{64}/i);
185
+ if (m) return byId(m[0].toLowerCase());
186
+ throw new Error(`no file at ${arg}`);
187
+ }
188
+ try { return unwrap(JSON.parse(text)); }
189
+ catch (e) {
190
+ const m = text.match(/0x[0-9a-f]{64}/i);
191
+ if (m) return byId(m[0].toLowerCase());
192
+ throw new Error(`${arg} is not a receipt (it is not JSON). Pass the .json file the CLI printed, or the session id`);
193
+ }
194
+ }
195
+
196
+ const fmtB = (n) => (n < 1024 ? n + " B" : n < 1048576 ? (n / 1024).toFixed(1) + " KB" : (n / 1048576).toFixed(1) + " MB");
197
+
198
+ async function readStdin() {
199
+ if (process.stdin.isTTY) {
200
+ process.stderr.write("paste the key, then Enter (it is not shown): ");
201
+ process.stdin.setRawMode(true);
202
+ return new Promise((ok) => { let v = ""; process.stdin.on("data", (b) => { const s = b.toString(); if (/[\r\n]/.test(s)) { process.stdin.setRawMode(false); process.stdin.pause(); process.stderr.write("\n"); ok(v + s.split(/[\r\n]/)[0]); } else if (s === "\u0003") process.exit(130); else v += s; }); });
203
+ }
204
+ const parts = []; for await (const b of process.stdin) parts.push(b); return Buffer.concat(parts).toString().trim();
205
+ }
206
+
207
+ async function main() {
208
+ const [cmd, ...argv] = process.argv.slice(2);
209
+ const { f, rest } = flags(argv);
210
+ if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h" || f.help) { console.log(HELP); return 0; }
211
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") { console.log(pkg.version); return 0; }
212
+
213
+ if (cmd === "run") return run(f, rest);
214
+
215
+ if (cmd === "secret") {
216
+ const [sub, name, origin] = rest;
217
+ if (sub === "ls" || sub === "list" || !sub) {
218
+ const l = listSecrets();
219
+ if (!l.length) { console.log(`No keys yet. Add one: echo "$OPENAI_API_KEY" | irida secret add openai https://api.openai.com`); return 0; }
220
+ for (const x of l) console.log(`${x.name.padEnd(14)} ${x.origin} ${dim("header " + x.header)}${x.rules.length ? " only " + x.rules.join(", ") : dim(" any path")}${x.max ? ` max ${x.max}/session` : ""}`);
221
+ return 0;
222
+ }
223
+ if (sub === "add") {
224
+ if (!name || !origin) { err(red("✗"), "usage: irida secret add <name> <https origin> [--header authorization] [--only \"GET /path/*\"] [--max N]"); return 2; }
225
+ const v = await readStdin();
226
+ let s;
227
+ try { s = addSecret(name, origin, v, { header: f.header ?? "authorization", rules: f.only ? String(f.only).split(",") : [], max: f.max ?? null }); }
228
+ catch (e) { err(red("✗"), e.message); return 2; }
229
+ console.log(`${ok("✓")} ${s.name} stored · goes only to ${s.origin} as ${s.header}${s.rules.length ? ` · only ${s.rules.join(", ")}` : ""}${s.max ? ` · up to ${s.max} requests per session` : ""} · code calls $IRIDA_GATE/${s.name}/…`);
230
+ if (!s.rules.length) console.log(dim(` tip: limit what an agent can do with it, e.g. --only "GET /repos/*"`));
231
+ return 0;
232
+ }
233
+ if (sub === "rm" || sub === "remove") { console.log(removeSecret(name) ? `${ok("✓")} removed ${name}` : `no secret named ${name}`); return 0; }
234
+ err(red("✗"), "irida secret add | ls | rm"); return 2;
235
+ }
236
+
237
+ if (cmd === "prove") {
238
+ const node = rest[0] ?? (typeof f.cloud === "string" ? f.cloud : null) ?? process.env.IRIDA_CLOUD ?? DEFAULT_CLOUD;
239
+ const mark = (x) => (x === true ? ok("✓") : x === false ? red("✗") : dim("·"));
240
+ let group = "";
241
+ const names = { node: "Node", run: "A real run, judged by its receipt", canary: "Self-check", anchor: "On chain" };
242
+ if (!f.json) console.log(`${bold("irida prove")} ${dim(node)}\n`);
243
+ const res = await prove(node, { rpc: f.rpc ?? DEFAULT_RPC, chain: !f["no-chain"], onCheck: (c) => {
244
+ if (f.json) return;
245
+ if (c.group !== group) { group = c.group; console.log(` ${bold(names[group] ?? group)}`); }
246
+ console.log(` ${mark(c.ok)} ${c.label}${c.detail ? dim(" " + c.detail) : ""}`);
247
+ } });
248
+ if (f.json) { console.log(JSON.stringify(res, null, 2)); return res.ok ? 0 : 1; }
249
+ console.log(`\n ${res.ok ? ok("✓ proven") : red("✗ not proven")} · ${res.passed} passed${res.failed ? ` · ${res.failed} failed` : ""}${res.skipped ? ` · ${res.skipped} not applicable yet` : ""}`);
250
+ return res.ok ? 0 : 1;
251
+ }
252
+
253
+ if (cmd === "quote") {
254
+ const n = Number(rest[0]);
255
+ if (!Number.isInteger(n) || n < 1) { err(red("✗"), "give a whole number of seconds, e.g. irida quote 600"); return 2; }
256
+ console.log(`${n}s at ${f.rate ?? DEFAULT_RATE} USDG/s = ${quote(n, f.rate ?? DEFAULT_RATE)} USDG`);
257
+ return 0;
258
+ }
259
+
260
+ if (cmd === "receipts") {
261
+ const list = receipts();
262
+ if (f.json) { console.log(JSON.stringify(list, null, 2)); return 0; }
263
+ if (!list.length) { console.log("No receipts yet. Run something: irida run -- echo hello"); return 0; }
264
+ for (const r of list)
265
+ console.log(`${dim(r.closed.slice(0, 19).replace("T", " "))} ${short(r.session)} ${String(r.seconds).padStart(5)}s ${r.paid.padStart(14)} ${r.worker}${r.status === "completed" ? "" : " " + red(r.status)}`);
266
+ return 0;
267
+ }
268
+
269
+ if (cmd === "verify") {
270
+ if (!rest[0]) { err(red("✗"), "give a receipt file or a session id"); return 2; }
271
+ let r;
272
+ try { r = await load(rest[0]); } catch (e) { err(red("✗"), e.message); return 2; }
273
+ const v = verifyReceipt(r);
274
+ if (v.ok) console.log(`${ok("✓")} valid · session ${short(r.session)} · ${r.seconds}s · paid ${r.paid} · signed by node ${short(r.node.id)}`);
275
+ else { console.log(`${red("✗")} invalid · ${v.reason}`); return 1; }
276
+ if (r.net) {
277
+ console.log(`${ok("✓")} gate · ${r.net.requests} requests · ${r.net.denied} refused · allow ${r.net.allow.join(", ") || "-"}${r.net.secrets.length ? " · keys " + r.net.secrets.map((x) => `${x.name} → ${x.origin}`).join(", ") : ""}`);
278
+ if (f.log) for (const e of r.net.log) console.log(dim(` ${String(e.t).padStart(7)}ms ${e.k.padEnd(6)} ${e.method ?? ""} ${e.host}${e.path ?? ""} ${e.status ?? e.why ?? ""} ${e.up ?? ""}/${e.down ?? ""}`));
279
+ } else if (r.v >= 2) console.log(`${ok("✓")} gate closed · this sandbox had no network`);
280
+ // anchoring: ask the node that signed it for the merkle proof, unless --offline
281
+ const node = f.cloud ?? process.env.IRIDA_CLOUD ?? DEFAULT_CLOUD;
282
+ if (r.mode === "cloud" && !f.offline) {
283
+ let p, res, every = 3600;
284
+ try {
285
+ res = await fetch(`${new URL(node).origin}/v1/receipts/${r.session}/proof`);
286
+ if (res.status === 404) { const n = await fetch(`${new URL(node).origin}/v1/node`).then((x) => x.json()).catch(() => null); every = n?.anchor?.every ?? (r.anchor ? 3600 : 0); }
287
+ else if (res.ok) p = await res.json();
288
+ } catch { console.log(dim("· could not reach the node for the anchor proof")); return 0; }
289
+ if (!p) {
290
+ // a receipt that should have been sealed long ago but is still outside every batch: the node is holding it back
291
+ const age = (Date.now() - Date.parse(r.closed)) / 1000;
292
+ if (every && age > every * 2 + 600) { console.log(`${red("✗")} not anchored · closed ${Math.round(age / 3600)} h ago, batches close every ${Math.round(every / 60)} min: the node has left this receipt out`); return 1; }
293
+ console.log(dim(every ? `· not anchored yet (batches close every ${Math.round(every / 60)} min)` : "· this node does not anchor receipts"));
294
+ return 0;
295
+ }
296
+ const c = checkProof(r, p);
297
+ if (!c.ok) { console.log(`${red("✗")} anchor proof fails · ${c.reason}`); return 1; }
298
+ console.log(`${ok("✓")} in batch #${p.batch} of ${p.count} · merkle path checked · head ${short(p.head)}`);
299
+ if (!p.tx) { console.log(dim("· head sealed, not posted on chain yet")); return 0; }
300
+ const rpc = f.rpc ?? process.env.IRIDA_CHAIN_RPC ?? DEFAULT_RPC;
301
+ try {
302
+ const ch = await checkChain(r, p, { rpc });
303
+ if (!ch.ok) { console.log(`${red("✗")} chain check fails · ${ch.reason}`); return 1; }
304
+ console.log(`${ok("✓")} on chain · read from ${new URL(rpc).host}: contract ${short(ch.contract)} holds this head in block ${ch.block} · tx ${short(p.tx)}`);
305
+ } catch (e) { console.log(dim(`· could not read the chain at ${new URL(rpc).host} (${e.cause?.code || e.message}); try --rpc <url>`)); }
306
+ }
307
+ return 0;
308
+ }
309
+
310
+ if (cmd === "account") {
311
+ const url = f.cloud ?? process.env.IRIDA_CLOUD;
312
+ const w = whoami();
313
+ if (!url) { console.log(`account ${w.id}\n${dim("add --cloud to see your balance on the Irida node (new accounts get a small free trial there)")}`); return 0; }
314
+ const c = cloud(url);
315
+ const [a, n] = await Promise.all([c.balance(), c.node()]);
316
+ if (f.json) { console.log(JSON.stringify({ ...a, node: n }, null, 2)); return 0; }
317
+ const cur = a.currency || "USDG";
318
+ console.log(`account ${a.account}\nnode ${n.node.id} · ${c.url}\nbalance ${a.balance} ${cur}${a.held !== "0.000000" ? ` (${a.held} held by open sessions)` : ""}\nrate ${n.rate} ${cur}/s · workers ${n.workers.join(", ")}`);
319
+ if (a.trial) console.log(ok(`trial ${a.trial} ${cur} of free time added to this new account (once). Try: irida run --cloud -- echo hello`));
320
+ if (n.deposit) console.log(`fund send ${cur} to vault ${n.deposit.vault} on chain ${n.deposit.chainId}: ${n.deposit.method} with account ${a.account}` + (n.deposit.fundUrl ? `\n or open ${n.deposit.fundUrl}?account=${a.account}` : ""));
321
+ for (const d of a.deposits || []) console.log(dim(` + ${d.amount} ${cur} ${d.at.slice(0, 19).replace("T", " ")} tx ${short(d.tx)}`));
322
+ for (const x of a.sessions) console.log(dim(` ${new Date(x.opened).toISOString().slice(0, 19).replace("T", " ")} ${short(x.id)} ${String(x.seconds ?? "-").padStart(5)}s ${(x.paid ?? "-").padStart(9)} ${x.worker} ${x.status}`));
323
+ return 0;
324
+ }
325
+
326
+ if (cmd === "mcp") {
327
+ const url = f.cloud ?? process.env.IRIDA_CLOUD ?? DEFAULT_CLOUD;
328
+ const max = f["max-budget"] ?? process.env.IRIDA_MAX_BUDGET ?? "0.10";
329
+ if (rest[0] === "setup") {
330
+ const args = ["-y", "irida", "mcp", ...(f["max-budget"] ? ["--max-budget", max] : [])];
331
+ console.log(`${bold("Claude Code")}\n claude mcp add irida -- npx ${args.join(" ")}\n`);
332
+ console.log(`${bold("Claude Desktop")} ${dim("(claude_desktop_config.json)")} · ${bold("Cursor")} ${dim("(.cursor/mcp.json)")}`);
333
+ console.log(JSON.stringify({ mcpServers: { irida: { command: "npx", args } } }, null, 2));
334
+ console.log(`\n${dim(`account ${whoami().id} · node ${url} · cap ${max} USDG per run`)}`);
335
+ return 0;
336
+ }
337
+ const { serve } = await import("../src/mcp.js");
338
+ if (process.stdin.isTTY) err(`${ok("✓")} irida MCP server on stdio · node ${url} · cap ${max} USDG per run\n ${dim("this is meant to be started by an MCP client. To add it: irida mcp setup")}`);
339
+ const { DEFAULT_CEILING } = await import("../src/mcp.js");
340
+ const ceiling = f.allow ? String(f.allow).split(",").map((x) => x.trim().toLowerCase()).filter(Boolean) : (process.env.IRIDA_MCP_ALLOW ? process.env.IRIDA_MCP_ALLOW.split(",") : DEFAULT_CEILING);
341
+ await serve({ url, maxBudget: max, ceiling });
342
+ return 0;
343
+ }
344
+
345
+ if (cmd === "whoami") {
346
+ const w = whoami();
347
+ console.log(`node ${w.id}\npub ${w.pub}\nhome ${w.home}`);
348
+ return 0;
349
+ }
350
+
351
+ err(red("✗"), `unknown command "${cmd}". Run irida --help`);
352
+ return 2;
353
+ }
354
+
355
+ main().then((code) => process.exit(code), (e) => { err(red("✗"), e.message); process.exit(1); });
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "irida",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Per-second compute for agents: run any command locally or in a Irida Cloud sandbox, pay for the seconds it ran, get a signed receipt.",
5
+ "homepage": "https://irida.run",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/keeplife-rh/irida.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/keeplife-rh/irida/issues"
12
+ },
13
+ "type": "module",
14
+ "bin": {
15
+ "irida": "bin/irida.js"
16
+ },
17
+ "exports": {
18
+ ".": "./src/index.js"
19
+ },
20
+ "files": [
21
+ "bin",
22
+ "src",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "engines": {
27
+ "node": ">=18.17"
28
+ },
29
+ "scripts": {
30
+ "test": "node --test --test-concurrency=1 test/*.test.js"
31
+ },
32
+ "keywords": [
33
+ "agents",
34
+ "compute",
35
+ "sandbox",
36
+ "metering",
37
+ "receipts",
38
+ "ed25519",
39
+ "usdg",
40
+ "robinhood-chain",
41
+ "cli",
42
+ "mcp",
43
+ "mcp-server"
44
+ ],
45
+ "author": "Irida",
46
+ "license": "MIT"
47
+ }
package/src/auth.js ADDED
@@ -0,0 +1,35 @@
1
+ // Request signing. Every API call is signed by the caller's ed25519 key; the key is the account, no API keys.
2
+ // message = METHOD \n PATH \n TS \n NONCE \n sha256(body)
3
+ // headers: x-irida-key (spki, base64), x-irida-ts (ms), x-irida-nonce (hex), x-irida-sig (base64)
4
+ import { createPublicKey, verify, sign, createHash, randomBytes } from "node:crypto";
5
+ import { nodeId } from "./receipt.js";
6
+
7
+ export const sha256 = (b) => createHash("sha256").update(b).digest("hex");
8
+ export const message = (method, path, ts, nonce, body) => [method.toUpperCase(), path, ts, nonce, sha256(body ?? "")].join("\n");
9
+
10
+ export function signRequest(key, method, path, body = "") {
11
+ const ts = String(Date.now()), nonce = randomBytes(12).toString("hex");
12
+ const sig = sign(null, Buffer.from(message(method, path, ts, nonce, body)), key.priv).toString("base64");
13
+ return { "x-irida-key": key.pub, "x-irida-ts": ts, "x-irida-nonce": nonce, "x-irida-sig": sig };
14
+ }
15
+
16
+ export function makeVerifier({ windowMs = 60_000 } = {}) {
17
+ const seen = new Map(); // nonce -> expiry
18
+ setInterval(() => { const now = Date.now(); for (const [k, t] of seen) if (t < now) seen.delete(k); }, windowMs).unref();
19
+ return function check(req, body) {
20
+ const h = req.headers, pub = h["x-irida-key"], ts = h["x-irida-ts"], nonce = h["x-irida-nonce"], sig = h["x-irida-sig"];
21
+ if (!pub || !ts || !nonce || !sig) return { error: "unsigned request" };
22
+ if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > windowMs) return { error: "request timestamp is too old or in the future" };
23
+ if (!/^[0-9a-f]{16,64}$/.test(nonce)) return { error: "bad nonce" };
24
+ if (seen.has(nonce)) return { error: "replayed request" };
25
+ let key;
26
+ try {
27
+ key = createPublicKey({ key: Buffer.from(pub, "base64"), format: "der", type: "spki" });
28
+ if (key.asymmetricKeyType !== "ed25519") return { error: "account key must be ed25519" };
29
+ } catch { return { error: "bad account key" }; }
30
+ const ok = verify(null, Buffer.from(message(req.method, req.url, ts, nonce, body)), key, Buffer.from(sig, "base64"));
31
+ if (!ok) return { error: "bad signature" };
32
+ seen.set(nonce, Date.now() + windowMs * 2);
33
+ return { account: nodeId(pub), pub };
34
+ };
35
+ }
package/src/cloud.js ADDED
@@ -0,0 +1,97 @@
1
+ // Irida Cloud client: every request is signed with your local ed25519 key (~/.irida/node.key).
2
+ // That key is your account; there are no API keys. Fund it by giving the node operator your account id.
3
+ import { mkdirSync, writeFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { nodeKey, home, verifyReceipt } from "./receipt.js";
6
+ import { signRequest } from "./auth.js";
7
+
8
+ // Used when you pass a bare --cloud and IRIDA_CLOUD is not set: the public node at irida.run. Pass --cloud <url> for any other node.
9
+ export const DEFAULT_CLOUD = "https://api.irida.run";
10
+ // Public explorer for the default node: every closed session, its receipt checked in the browser.
11
+ export const SCAN = "https://irida.run/scan";
12
+ export const scanUrl = (nodeUrl, session) => (new URL(nodeUrl).origin === DEFAULT_CLOUD ? `${SCAN}#${session}` : null);
13
+
14
+ export function client(url = process.env.IRIDA_CLOUD, { dir = home() } = {}) {
15
+ if (!url) throw new Error("no cloud node given: pass --cloud <url> or set IRIDA_CLOUD");
16
+ const u = new URL(url);
17
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
18
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) throw new Error("cloud nodes must use https (plain http is allowed for localhost only)");
19
+ const base = u.origin;
20
+ const key = nodeKey(dir);
21
+ async function call(method, path, body) {
22
+ const raw = body === undefined ? "" : JSON.stringify(body);
23
+ const res = await fetch(base + path, {
24
+ method, body: raw || undefined,
25
+ headers: { ...(raw ? { "content-type": "application/json" } : {}), ...signRequest(key, method, path, raw) },
26
+ }).catch((e) => { throw new Error(`cannot reach ${base}: ${e.cause?.code || e.message}`); });
27
+ return res;
28
+ }
29
+ async function jsonCall(method, path, body) {
30
+ const res = await call(method, path, body);
31
+ const out = await res.json().catch(() => ({}));
32
+ if (!res.ok) throw Object.assign(new Error(out.error || `HTTP ${res.status}`), { status: res.status });
33
+ return out;
34
+ }
35
+ return {
36
+ url: base, account: key.id,
37
+ node: async () => (await fetch(base + "/v1/node").catch((e) => { throw new Error(`cannot reach ${base}: ${e.cause?.code || e.message}`); })).json(),
38
+ balance: () => jsonCall("GET", "/v1/account"),
39
+ // net: { allow: ["api.github.com"], secrets: [{ name, origin, header, value }] } opens the session with a gate
40
+ // fit: the budget was a default, not the user's choice, so it shrinks to what the account holds (a new account's
41
+ // trial is smaller than the default budget); an amount the user asked for is never lowered
42
+ async open({ worker = "shell", budget, seconds, net, onTick, fit = false } = {}) {
43
+ if (fit && budget != null) {
44
+ const a = await jsonCall("GET", "/v1/account").catch(() => null);
45
+ const micro = (x) => { const [i, f = ""] = String(x).split("."); return BigInt(i || 0) * 1000000n + BigInt((f + "000000").slice(0, 6)); };
46
+ if (a && micro(a.balance) > 0n && micro(a.balance) < micro(budget)) { const b = micro(a.balance); budget = `${b / 1000000n}.${String(b % 1000000n).padStart(6, "0")}`; }
47
+ }
48
+ const s = await jsonCall("POST", "/v1/sessions", { worker, ...(budget != null ? { budget: String(budget) } : {}), ...(seconds != null ? { seconds } : {}), ...(net ? { net } : {}) });
49
+ const opened = Date.parse(s.opened);
50
+ const tick = onTick && setInterval(() => {
51
+ const sec = Math.min(Math.max(1, Math.ceil((Date.now() - opened) / 1000)), s.maxSeconds);
52
+ onTick({ seconds: sec, max: s.maxSeconds, cost: (sec * Number(s.rate)).toFixed(4) });
53
+ }, 250);
54
+ let receipt = null;
55
+ return {
56
+ ...s, id: s.session,
57
+ // Resolves with { code, signal, stdout, stderr, gate }. onData(stream, Buffer) sees output as it arrives, onGate(entry) each gate log line.
58
+ async exec(cmd, { onData, onGate } = {}) {
59
+ const command = Array.isArray(cmd) ? cmd.map(shq).join(" ") : cmd;
60
+ const res = await call("POST", `/v1/sessions/${s.session}/exec`, { cmd: command });
61
+ if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || `HTTP ${res.status}`); }
62
+ const out = { stdout: [], stderr: [] }, gate = []; let exit = { code: null, signal: null }, buf = "";
63
+ const dec = new TextDecoder();
64
+ for await (const chunk of res.body) {
65
+ buf += dec.decode(chunk, { stream: true });
66
+ let i;
67
+ while ((i = buf.indexOf("\n")) >= 0) {
68
+ const line = buf.slice(0, i); buf = buf.slice(i + 1);
69
+ if (!line) continue;
70
+ const m = JSON.parse(line);
71
+ if (m.t === "exit") exit = m;
72
+ else if (m.t === "gate") { gate.push(m.e); onGate?.(m.e); }
73
+ else { const b = Buffer.from(m.d, "base64"); out[m.t]?.push(b); onData?.(m.t, b); }
74
+ }
75
+ }
76
+ return { code: exit.code, signal: exit.signal, closed: !!exit.closed, stdout: Buffer.concat(out.stdout).toString(), stderr: Buffer.concat(out.stderr).toString(), gate };
77
+ },
78
+ // Takes hosts or keys away from the running session at once: { hosts: ["pypi.org"], secrets: ["openai"] }.
79
+ revoke: ({ hosts = [], secrets = [] } = {}) => jsonCall("POST", `/v1/sessions/${s.session}/net`, { revoke: { hosts, secrets } }),
80
+ async stop() {
81
+ if (receipt) return receipt;
82
+ clearInterval(tick);
83
+ const { receipt: r } = await jsonCall("POST", `/v1/sessions/${s.session}/stop`);
84
+ if (!verifyReceipt(r).ok) throw new Error("the node returned a receipt that does not verify");
85
+ if (r.node.id !== s.node) throw new Error("the receipt was signed by a different node than the one that opened the session");
86
+ const rdir = join(dir, "receipts"); mkdirSync(rdir, { recursive: true });
87
+ const file = join(rdir, r.session + ".json");
88
+ writeFileSync(file, JSON.stringify(r, null, 2) + "\n");
89
+ receipt = { ...r, file };
90
+ return receipt;
91
+ },
92
+ };
93
+ },
94
+ };
95
+ }
96
+
97
+ const shq = (a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : "'" + String(a).replace(/'/g, "'\\''") + "'");