@singularity-layer/cli 0.2.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.
package/dist/cli.js ADDED
@@ -0,0 +1,1038 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/auth.ts
4
+ import { readFileSync, existsSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { homedir } from "node:os";
7
+ import nacl from "tweetnacl";
8
+ var die = (msg) => {
9
+ console.error(`error: ${msg}`);
10
+ process.exit(1);
11
+ };
12
+ var ok = (msg = "") => console.log(msg);
13
+ var B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
14
+ function bs58(bytes) {
15
+ let zeros = 0;
16
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
17
+ const digits = [];
18
+ for (let k = zeros; k < bytes.length; k++) {
19
+ let carry = bytes[k];
20
+ for (let i = 0; i < digits.length; i++) {
21
+ carry += digits[i] << 8;
22
+ digits[i] = carry % 58;
23
+ carry = carry / 58 | 0;
24
+ }
25
+ while (carry > 0) {
26
+ digits.push(carry % 58);
27
+ carry = carry / 58 | 0;
28
+ }
29
+ }
30
+ let out = "1".repeat(zeros);
31
+ for (let i = digits.length - 1; i >= 0; i--) out += B58[digits[i]];
32
+ return out;
33
+ }
34
+ function loadKeypair(flags = {}) {
35
+ const path = String(
36
+ flags.keypair || process.env.SINGULARITY_KEYPAIR || process.env.SGLPROC_KEYPAIR || join(homedir(), ".config/solana/id.json")
37
+ );
38
+ if (!existsSync(path)) {
39
+ die(`no keypair at ${path}
40
+ pass --keypair <path>, set SINGULARITY_KEYPAIR, or create one:
41
+ solana-keygen new`);
42
+ }
43
+ let raw;
44
+ try {
45
+ raw = JSON.parse(readFileSync(path, "utf8"));
46
+ } catch {
47
+ die(`${path} is not a valid keypair file`);
48
+ }
49
+ if (!Array.isArray(raw) || raw.length !== 64 && raw.length !== 32) {
50
+ die(`${path} does not look like a Solana keypair (expected a 64-byte array)`);
51
+ }
52
+ const arr = raw;
53
+ const secret = arr.length === 64 ? Uint8Array.from(arr) : nacl.sign.keyPair.fromSeed(Uint8Array.from(arr)).secretKey;
54
+ const pair = nacl.sign.keyPair.fromSecretKey(secret);
55
+ return { secretKey: pair.secretKey, address: bs58(pair.publicKey) };
56
+ }
57
+ async function sha256Hex(input) {
58
+ const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
59
+ return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
60
+ }
61
+ async function api(base, method, path, { body, kp, bearer, query, signQuery } = {}) {
62
+ let qs = "";
63
+ if (query) {
64
+ const params = new URLSearchParams();
65
+ for (const [k, v] of Object.entries(query)) {
66
+ if (Array.isArray(v)) for (const item of v) params.append(k, String(item));
67
+ else params.append(k, String(v));
68
+ }
69
+ const encoded = params.toString();
70
+ if (encoded) qs = "?" + encoded;
71
+ }
72
+ const signedRaw = method === "GET" ? signQuery ? qs : "" : body === void 0 ? "" : JSON.stringify(body);
73
+ const sentRaw = method === "GET" ? void 0 : body === void 0 ? void 0 : signedRaw;
74
+ const headers = {};
75
+ if (sentRaw) headers["content-type"] = "application/json";
76
+ if (bearer) headers.Authorization = `Bearer ${bearer}`;
77
+ if (kp) {
78
+ const timestamp = String(Math.floor(Date.now() / 1e3));
79
+ const nonce = [...nacl.randomBytes(12)].map((b) => b.toString(16).padStart(2, "0")).join("");
80
+ const msg = `sgl-processor-auth:${method}:${path}:${await sha256Hex(signedRaw)}:${kp.address}:${timestamp}:${nonce}`;
81
+ const sig = nacl.sign.detached(new TextEncoder().encode(msg), kp.secretKey);
82
+ Object.assign(headers, {
83
+ "X-Auth-Address": kp.address,
84
+ "X-Auth-Chain": "solana",
85
+ "X-Auth-Signature": Buffer.from(sig).toString("base64"),
86
+ "X-Auth-Timestamp": timestamp,
87
+ "X-Auth-Nonce": nonce
88
+ });
89
+ }
90
+ let res;
91
+ try {
92
+ res = await fetch(`${base}${path}${qs}`, { method, headers, body: sentRaw });
93
+ } catch (e) {
94
+ return die(`could not reach ${base} \u2014 ${e instanceof Error ? e.message : String(e)}`);
95
+ }
96
+ const text = await res.text();
97
+ let parsed;
98
+ try {
99
+ parsed = text ? JSON.parse(text) : void 0;
100
+ } catch {
101
+ parsed = void 0;
102
+ }
103
+ if (!res.ok) {
104
+ const p = parsed ?? {};
105
+ return die(`${res.status} ${p.detail || p.error || text.slice(0, 300)}`);
106
+ }
107
+ return parsed;
108
+ }
109
+ var SHORT_FLAGS = {
110
+ i: "interactive",
111
+ f: "follow",
112
+ y: "yes",
113
+ j: "json"
114
+ };
115
+ function parseArgs(argv) {
116
+ const flags = {};
117
+ const words = [];
118
+ for (let i = 0; i < argv.length; i++) {
119
+ const tok = argv[i];
120
+ if (tok.startsWith("--")) {
121
+ const name = tok.slice(2);
122
+ const next = argv[i + 1];
123
+ if (next === void 0 || next.startsWith("-")) flags[name] = true;
124
+ else {
125
+ flags[name] = next;
126
+ i++;
127
+ }
128
+ continue;
129
+ }
130
+ const short = /^-([a-zA-Z])$/.exec(tok);
131
+ if (short && SHORT_FLAGS[short[1]]) {
132
+ flags[SHORT_FLAGS[short[1]]] = true;
133
+ continue;
134
+ }
135
+ words.push(tok);
136
+ }
137
+ return { words, flags };
138
+ }
139
+ var stdinRest = "";
140
+ async function prompt(question, fallback = "") {
141
+ process.stdout.write(fallback ? `${question} [${fallback}]: ` : `${question}: `);
142
+ const takeLine = () => {
143
+ const nl = stdinRest.indexOf("\n");
144
+ if (nl < 0) return null;
145
+ const line = stdinRest.slice(0, nl);
146
+ stdinRest = stdinRest.slice(nl + 1);
147
+ return line;
148
+ };
149
+ const echo = (line) => {
150
+ if (!process.stdin.isTTY) process.stdout.write(`${line}
151
+ `);
152
+ };
153
+ const buffered = takeLine();
154
+ if (buffered !== null) {
155
+ echo(buffered);
156
+ return buffered.trim() || fallback;
157
+ }
158
+ const answer = await new Promise((resolve2) => {
159
+ const onData = (chunk) => {
160
+ stdinRest += chunk.toString("utf8");
161
+ const line = takeLine();
162
+ if (line === null) return;
163
+ process.stdin.off("data", onData);
164
+ process.stdin.pause();
165
+ process.stdin.unref();
166
+ echo(line);
167
+ resolve2(line);
168
+ };
169
+ const onEnd = () => {
170
+ process.stdin.off("data", onData);
171
+ const line = stdinRest;
172
+ stdinRest = "";
173
+ resolve2(line);
174
+ };
175
+ process.stdin.once("end", onEnd);
176
+ process.stdin.resume();
177
+ process.stdin.on("data", onData);
178
+ });
179
+ return answer.trim() || fallback;
180
+ }
181
+
182
+ // src/processors.ts
183
+ import { readFileSync as readFileSync3, writeFileSync, existsSync as existsSync3, appendFileSync, mkdirSync, chmodSync } from "node:fs";
184
+ import { resolve, join as join3, dirname } from "node:path";
185
+ import { homedir as homedir2 } from "node:os";
186
+
187
+ // src/bundle.ts
188
+ import { build } from "esbuild";
189
+ import { readFileSync as readFileSync2, existsSync as existsSync2, lstatSync, realpathSync } from "node:fs";
190
+ import { join as join2, relative, isAbsolute, sep } from "node:path";
191
+ import { createHash } from "node:crypto";
192
+ var MAX_BUNDLE_BYTES = 1048576;
193
+ var UNAVAILABLE_BUILTINS = /* @__PURE__ */ new Set([
194
+ "fs",
195
+ "node:fs",
196
+ "fs/promises",
197
+ "node:fs/promises",
198
+ "child_process",
199
+ "node:child_process",
200
+ "worker_threads",
201
+ "node:worker_threads",
202
+ "net",
203
+ "node:net",
204
+ "tls",
205
+ "node:tls",
206
+ "dns",
207
+ "node:dns",
208
+ "cluster",
209
+ "node:cluster",
210
+ "os",
211
+ "node:os",
212
+ "v8",
213
+ "node:v8",
214
+ "repl",
215
+ "node:repl",
216
+ "vm",
217
+ "node:vm"
218
+ ]);
219
+ function guardBuiltins() {
220
+ return {
221
+ name: "sgl-guard-builtins",
222
+ setup(b) {
223
+ b.onResolve({ filter: /.*/ }, (args) => {
224
+ if (!UNAVAILABLE_BUILTINS.has(args.path)) return null;
225
+ return {
226
+ errors: [{
227
+ text: `"${args.path}" is not available in a processor. Processors run in a Cloudflare isolate: there is no filesystem, no child processes and no raw sockets. Outbound HTTPS to hosts you declared in egress.allow is the way out. Imported by ` + (args.importer || "your entry file") + "."
228
+ }]
229
+ };
230
+ });
231
+ }
232
+ };
233
+ }
234
+ function collectSources(dir, inputs) {
235
+ const out = {};
236
+ const root = realpathSync(dir);
237
+ for (const rel of inputs) {
238
+ if (rel.split("/").includes("node_modules")) continue;
239
+ const full = isAbsolute(rel) ? rel : join2(dir, rel);
240
+ let st;
241
+ try {
242
+ st = lstatSync(full);
243
+ } catch {
244
+ continue;
245
+ }
246
+ if (!st.isFile()) continue;
247
+ const real = realpathSync(full);
248
+ if (real !== root && !real.startsWith(root + sep)) continue;
249
+ if (st.size > 256 * 1024) continue;
250
+ out[relative(root, real)] = readFileSync2(real, "utf8");
251
+ }
252
+ return out;
253
+ }
254
+ async function bundleProcessor(opts) {
255
+ const { entry, cwd } = opts;
256
+ if (!existsSync2(entry)) {
257
+ throw new Error(`no entry file at ${entry}`);
258
+ }
259
+ let result;
260
+ try {
261
+ result = await build({
262
+ entryPoints: [entry],
263
+ absWorkingDir: cwd,
264
+ bundle: true,
265
+ write: false,
266
+ // The list of files esbuild actually read. This IS the provenance set — see
267
+ // collectSources() for why a directory walk was a wallet-key exfiltration path.
268
+ metafile: true,
269
+ format: "esm",
270
+ // The isolate's own target. `browser` would pull in DOM shims that do not exist; `node`
271
+ // would resolve Node built-ins we cannot provide.
272
+ platform: "neutral",
273
+ target: "es2022",
274
+ mainFields: ["module", "main"],
275
+ conditions: ["worker", "browser", "import", "default"],
276
+ minify: opts.minify === true,
277
+ // Keeps the publisher's own function and variable names in run errors.
278
+ keepNames: true,
279
+ plugins: [guardBuiltins()],
280
+ logLevel: "silent"
281
+ });
282
+ } catch (e) {
283
+ const msg = e instanceof Error ? e.message : String(e);
284
+ throw new Error(`bundling failed:
285
+ ${msg}`);
286
+ }
287
+ const output = result.outputFiles?.[0];
288
+ if (!output) throw new Error("bundling produced no output");
289
+ const bundle = new TextDecoder().decode(output.contents);
290
+ const bytes = new TextEncoder().encode(bundle).byteLength;
291
+ if (bytes > MAX_BUNDLE_BYTES) {
292
+ throw new Error(
293
+ `bundle is ${(bytes / 1024).toFixed(0)} KiB, over the ${MAX_BUNDLE_BYTES / 1024} KiB limit. Try --minify, or drop a heavy dependency.`
294
+ );
295
+ }
296
+ const files = collectSources(cwd, Object.keys(result.metafile?.inputs ?? {}));
297
+ const sources = {};
298
+ for (const [path, src] of Object.entries(files)) {
299
+ sources[path] = createHash("sha256").update(src).digest("hex");
300
+ }
301
+ return {
302
+ bundle,
303
+ files,
304
+ meta: {
305
+ bundler: `esbuild`,
306
+ entry: relative(cwd, entry),
307
+ bytes,
308
+ sources
309
+ },
310
+ warnings: (result.warnings ?? []).map((w) => w.text)
311
+ };
312
+ }
313
+
314
+ // src/format.ts
315
+ function usd(micro) {
316
+ const n = BigInt(micro ?? 0);
317
+ const sign = n < 0n ? "-" : "";
318
+ const a = n < 0n ? -n : n;
319
+ return `${sign}${a / 1000000n}.${String(a % 1000000n).padStart(6, "0")}`;
320
+ }
321
+ var when = (iso) => iso ? new Date(iso).toISOString().replace("T", " ").slice(0, 19) : "";
322
+ function coerce(raw, type) {
323
+ switch (type) {
324
+ case "number":
325
+ case "integer": {
326
+ const n = Number(raw);
327
+ if (!Number.isFinite(n)) return die(`"${raw}" is not a number`);
328
+ return type === "integer" ? Math.trunc(n) : n;
329
+ }
330
+ case "boolean":
331
+ if (/^(true|yes|y|1)$/i.test(raw)) return true;
332
+ if (/^(false|no|n|0)$/i.test(raw)) return false;
333
+ return die(`"${raw}" is not true or false`);
334
+ case "array":
335
+ case "object":
336
+ try {
337
+ return JSON.parse(raw);
338
+ } catch {
339
+ return die(`"${raw}" is not valid JSON`);
340
+ }
341
+ default:
342
+ return raw;
343
+ }
344
+ }
345
+
346
+ // src/processors.ts
347
+ var DEFAULT_BASE = "https://sgl-processors.ivaavimusicproductions.workers.dev";
348
+ function resolveBase(flags) {
349
+ const override = typeof flags.base === "string" && flags.base || process.env.SINGULARITY_PROCESSORS_URL;
350
+ if (override) {
351
+ process.stderr.write(`(using ${override})
352
+ `);
353
+ return String(override).replace(/\/+$/, "");
354
+ }
355
+ return DEFAULT_BASE;
356
+ }
357
+ var STATE_FILE = ".singularity.json";
358
+ var CONFIG_FILE = join3(homedir2(), ".config", "singularity", "config.json");
359
+ var HELP = `singularity processors \u2014 deploy loops we host and run
360
+
361
+ init [slug] scaffold processor.json + processor.js here
362
+ configure interactive setup: keypair, defaults
363
+ deploy create it (prints the invoke token ONCE)
364
+ update push new code or manifest
365
+ run '{"n":10}' invoke and print the output
366
+ run --get '{"n":10}' invoke over GET (for methods: ["GET"] processors)
367
+ call -i invoke interactively, prompted per input field
368
+ schema [slug] the input/output schema buyers and agents see
369
+ list your processors
370
+ search [query] the public catalogue
371
+ logs [slug] recent runs and failure rate
372
+ logs --follow stream new runs as they happen
373
+ revenue sales and compute spend across everything you own
374
+ earnings [slug] the same, for one processor
375
+ env list | unset KEY which secrets are set; clear one
376
+ secrets KEY=value ... set secret values (KEY= also clears)
377
+ pause | resume stop or restart traffic, keeping the slug
378
+ publish | unpublish list or unlist publicly (instant, no review)
379
+ rotate new invoke token, the old one stops working
380
+ delete --yes soft delete (the slug is never reusable)
381
+
382
+ --keypair <path> defaults to ~/.config/solana/id.json
383
+ --slug <slug> when not run from a processor directory
384
+ --json machine-readable output, for scripts and agents
385
+ --bundle bundle with esbuild: imports and npm packages
386
+ --entry <file> bundle entry (default: the manifest's $code)`;
387
+ var STARTER_MANIFEST = (slug) => ({
388
+ $code: "processor.js",
389
+ manifest_version: 1,
390
+ slug,
391
+ name: "My Processor",
392
+ description: "What this loop does, in one sentence buyers and agents will read.",
393
+ lane: "managed",
394
+ price_usd: "0.01",
395
+ input_schema: { type: "object" },
396
+ output_schema: { type: "object" },
397
+ limits: { timeout_ms: 12e4, cpu_ms: 1e4, subrequests: 200 },
398
+ // Exact hostnames your loop may call. Wildcards are rejected. An inference provider's host
399
+ // is added for you.
400
+ egress: { allow: [] },
401
+ secrets: []
402
+ });
403
+ var STARTER_CODE = `export default {
404
+ async fetch(request) {
405
+ const { input } = await request.json();
406
+
407
+ // Your loop goes here. Call APIs and models with fetch() \u2014 credentials for the hosts
408
+ // you declared are injected for you, so no keys belong in this file.
409
+
410
+ return Response.json({ ok: true, received: input });
411
+ }
412
+ }
413
+ `;
414
+ var readState = () => existsSync3(STATE_FILE) ? JSON.parse(readFileSync3(STATE_FILE, "utf8")) : {};
415
+ var writeState = (patch) => {
416
+ const merged = { ...readState(), ...patch };
417
+ writeFileSync(STATE_FILE, JSON.stringify(merged, null, 2) + "\n", { mode: 384 });
418
+ try {
419
+ chmodSync(STATE_FILE, 384);
420
+ } catch {
421
+ }
422
+ if (merged.invoke_token) ensureGitignored();
423
+ };
424
+ function ensureGitignored() {
425
+ try {
426
+ const gi = existsSync3(".gitignore") ? readFileSync3(".gitignore", "utf8") : "";
427
+ if (gi.split(/\r?\n/).some((line) => line.trim() === STATE_FILE)) return;
428
+ appendFileSync(".gitignore", (gi && !gi.endsWith("\n") ? "\n" : "") + `${STATE_FILE}
429
+ `);
430
+ } catch {
431
+ }
432
+ }
433
+ var readConfig = () => {
434
+ try {
435
+ return existsSync3(CONFIG_FILE) ? JSON.parse(readFileSync3(CONFIG_FILE, "utf8")) : {};
436
+ } catch {
437
+ return {};
438
+ }
439
+ };
440
+ function loadManifest(flags) {
441
+ const p = resolve(String(flags.manifest || "processor.json"));
442
+ if (!existsSync3(p)) die(`no manifest at ${p} \u2014 run \`singularity processors init\` first`);
443
+ try {
444
+ return JSON.parse(readFileSync3(p, "utf8"));
445
+ } catch {
446
+ return die(`${p} is not valid JSON`);
447
+ }
448
+ }
449
+ var clean = (m) => Object.fromEntries(Object.entries(m).filter(([k]) => !k.startsWith("$")));
450
+ function resolveSlug(flags) {
451
+ if (typeof flags.slug === "string" && flags.slug) return flags.slug;
452
+ const fromState = readState().slug;
453
+ if (fromState) return fromState;
454
+ if (existsSync3("processor.json")) return loadManifest(flags).slug;
455
+ return void 0;
456
+ }
457
+ var requireSlug = (flags) => resolveSlug(flags) || die("no slug \u2014 deploy first, pass --slug, or run from a processor directory");
458
+ var emit = (flags, value) => {
459
+ if (!flags.json) return false;
460
+ console.log(JSON.stringify(value, null, 2));
461
+ return true;
462
+ };
463
+ async function resolveSource(manifest, flags) {
464
+ const entryPath = resolve(String(flags.entry || manifest.$entry || manifest.$code || "processor.js"));
465
+ if (!existsSync3(entryPath)) die(`no code at ${entryPath}`);
466
+ const wantsBundle = (flags.bundle === true || manifest.$bundle === true) && flags["no-bundle"] !== true;
467
+ if (wantsBundle) {
468
+ process.stderr.write("bundling... ");
469
+ const built = await bundleProcessor({
470
+ entry: entryPath,
471
+ cwd: process.cwd(),
472
+ minify: flags.minify === true
473
+ });
474
+ process.stderr.write(`${(built.meta.bytes / 1024).toFixed(1)} KiB
475
+ `);
476
+ for (const w of built.warnings) process.stderr.write(` warning: ${w}
477
+ `);
478
+ return { bundle: built.bundle, files: built.files, bundle_meta: built.meta };
479
+ }
480
+ const code = readFileSync3(entryPath, "utf8");
481
+ if (/^\s*import\s+[^(]/m.test(code) || /^\s*export\s+\*\s+from/m.test(code)) {
482
+ die(`${entryPath} has imports, which need bundling.
483
+ add --bundle (or "$bundle": true in processor.json) and deploy again.`);
484
+ }
485
+ if (flags["no-bundle"] === true) return { code, bundle: null, files: {} };
486
+ return { code };
487
+ }
488
+ async function promptForSchema(schema) {
489
+ const props = schema?.properties;
490
+ if (!props || Object.keys(props).length === 0) {
491
+ const raw = await prompt("input (JSON)", "{}");
492
+ try {
493
+ return JSON.parse(raw);
494
+ } catch {
495
+ return die("input must be valid JSON");
496
+ }
497
+ }
498
+ const required = new Set(schema?.required ?? []);
499
+ const out = {};
500
+ ok("");
501
+ for (const [name, spec] of Object.entries(props)) {
502
+ const label = [
503
+ name,
504
+ spec.type ? `(${spec.type})` : "",
505
+ required.has(name) ? "*" : "",
506
+ spec.description ? `\u2014 ${spec.description}` : ""
507
+ ].filter(Boolean).join(" ");
508
+ const dflt = spec.default === void 0 ? "" : String(spec.default);
509
+ const raw = await prompt(` ${label}`, dflt);
510
+ if (raw === "") {
511
+ if (required.has(name)) {
512
+ ok(" (required)");
513
+ return promptForSchema(schema);
514
+ }
515
+ continue;
516
+ }
517
+ out[name] = coerce(raw, spec.type);
518
+ }
519
+ ok("");
520
+ return out;
521
+ }
522
+ function toQuery(input) {
523
+ if (input === void 0 || input === null) return {};
524
+ if (typeof input !== "object" || Array.isArray(input)) {
525
+ return die("--get needs a JSON object of scalar fields");
526
+ }
527
+ const out = {};
528
+ for (const [k, v] of Object.entries(input)) {
529
+ if (v === void 0 || v === null) continue;
530
+ if (Array.isArray(v)) {
531
+ if (v.some((x) => x !== null && typeof x === "object")) {
532
+ return die(`--get cannot send nested objects (field "${k}") \u2014 drop --get to POST it`);
533
+ }
534
+ out[k] = v.map((x) => typeof x === "number" ? x : String(x));
535
+ continue;
536
+ }
537
+ if (typeof v === "object") {
538
+ return die(`--get cannot send nested objects (field "${k}") \u2014 drop --get to POST it`);
539
+ }
540
+ out[k] = typeof v === "number" ? v : String(v);
541
+ }
542
+ return out;
543
+ }
544
+ async function invokeAndWait(base, slug, input, kp, token, quiet, asGet = false) {
545
+ let res = asGet ? await api(base, "GET", `/processors/${slug}/run`, {
546
+ query: toQuery(input),
547
+ kp,
548
+ bearer: token,
549
+ signQuery: true
550
+ }) : await api(base, "POST", `/processors/${slug}/run`, {
551
+ body: { input },
552
+ kp,
553
+ bearer: token
554
+ });
555
+ if (res.status !== "completed" && res.run_token && res.run_id) {
556
+ if (!quiet) process.stderr.write("running");
557
+ for (let i = 0; i < 60; i++) {
558
+ await new Promise((r) => setTimeout(r, 1500));
559
+ if (!quiet) process.stderr.write(".");
560
+ const p = await api(
561
+ base,
562
+ "GET",
563
+ `/processors/${slug}/runs/${res.run_id}`,
564
+ { bearer: res.run_token }
565
+ );
566
+ if (p.status === "completed" || p.status.startsWith("failed")) {
567
+ res = p;
568
+ break;
569
+ }
570
+ }
571
+ if (!quiet) process.stderr.write("\n");
572
+ }
573
+ return res;
574
+ }
575
+ function reportRun(res, flags) {
576
+ if (res.status === "completed") {
577
+ console.log(JSON.stringify(flags.json ? res : res.output, null, 2));
578
+ return;
579
+ }
580
+ if (flags.json) console.log(JSON.stringify(res, null, 2));
581
+ else console.error(`${res.status}: ${res.error || "no output"}`);
582
+ process.exit(1);
583
+ }
584
+ async function run(words, flags) {
585
+ const sub = words[0];
586
+ const BASE = resolveBase(flags);
587
+ const cfg = readConfig();
588
+ if (!flags.keypair && cfg.keypair) flags = { ...flags, keypair: cfg.keypair };
589
+ switch (sub) {
590
+ case "init": {
591
+ const slug = words[1] || "my-processor";
592
+ if (existsSync3("processor.json")) die("processor.json already exists");
593
+ writeFileSync("processor.json", JSON.stringify(STARTER_MANIFEST(slug), null, 2) + "\n");
594
+ if (!existsSync3("processor.js")) writeFileSync("processor.js", STARTER_CODE);
595
+ ensureGitignored();
596
+ ok("created processor.json and processor.js");
597
+ ok("edit them, then: singularity processors deploy");
598
+ break;
599
+ }
600
+ case "configure": {
601
+ ok("singularity configure \u2014 machine defaults, no secrets stored");
602
+ ok("");
603
+ const kpPath = await prompt("keypair path", cfg.keypair || join3(homedir2(), ".config/solana/id.json"));
604
+ if (!existsSync3(resolve(kpPath.replace(/^~/, homedir2())))) {
605
+ ok(` note: ${kpPath} does not exist yet \u2014 create one with: solana-keygen new`);
606
+ }
607
+ const base = await prompt("API base URL", cfg.base || DEFAULT_BASE);
608
+ const next = { keypair: kpPath };
609
+ if (base && base !== DEFAULT_BASE) next.base = base;
610
+ mkdirSync(dirname(CONFIG_FILE), { recursive: true });
611
+ writeFileSync(CONFIG_FILE, JSON.stringify(next, null, 2) + "\n", { mode: 384 });
612
+ ok("");
613
+ ok(`saved ${CONFIG_FILE}`);
614
+ try {
615
+ ok(`wallet: ${loadKeypair({ keypair: kpPath }).address}`);
616
+ } catch {
617
+ }
618
+ break;
619
+ }
620
+ case "deploy": {
621
+ const kp = loadKeypair(flags);
622
+ const manifest = loadManifest(flags);
623
+ const source = await resolveSource(manifest, flags);
624
+ const res = await api(BASE, "POST", "/processors", {
625
+ body: { manifest: clean(manifest), ...source },
626
+ kp
627
+ });
628
+ writeState({ slug: res.slug, invoke_token: res.invoke_token });
629
+ if (emit(flags, res)) break;
630
+ ok(`deployed ${res.slug}`);
631
+ ok();
632
+ ok(`invoke token (shown once, saved to ${STATE_FILE}):`);
633
+ ok(` ${res.invoke_token}`);
634
+ ok();
635
+ ok(`try it: singularity processors run '{"hello":"world"}'`);
636
+ ok("go live: singularity processors publish");
637
+ break;
638
+ }
639
+ case "update": {
640
+ const kp = loadKeypair(flags);
641
+ const manifest = loadManifest(flags);
642
+ const slug = String(flags.slug || manifest.slug || die("no slug in processor.json"));
643
+ const source = await resolveSource(manifest, flags);
644
+ const res = await api(
645
+ BASE,
646
+ "PATCH",
647
+ `/processors/${slug}`,
648
+ { body: { manifest: clean(manifest), ...source }, kp }
649
+ );
650
+ if (emit(flags, res)) break;
651
+ ok(`updated ${slug} (config_rev ${res.config_rev})`);
652
+ if (res.note) ok(res.note);
653
+ break;
654
+ }
655
+ case "run":
656
+ case "call": {
657
+ const slug = requireSlug(flags);
658
+ const token = String(flags.token || readState().invoke_token || "");
659
+ if (!token) die(`no invoke token in ${STATE_FILE} \u2014 run \`singularity processors rotate\``);
660
+ const kp = loadKeypair(flags);
661
+ let input = {};
662
+ const interactive = flags.interactive === true || sub === "call";
663
+ if (words[1]) {
664
+ try {
665
+ input = JSON.parse(words[1]);
666
+ } catch {
667
+ die("input must be valid JSON");
668
+ }
669
+ } else if (interactive) {
670
+ const d = await api(
671
+ BASE,
672
+ "GET",
673
+ `/processors/${slug}`,
674
+ { kp }
675
+ );
676
+ input = await promptForSchema(d.manifest?.input_schema ?? d.input_schema);
677
+ ok(`input: ${JSON.stringify(input)}`);
678
+ }
679
+ const res = await invokeAndWait(
680
+ BASE,
681
+ slug,
682
+ input,
683
+ kp,
684
+ token,
685
+ flags.json === true,
686
+ flags.get === true
687
+ );
688
+ reportRun(res, flags);
689
+ break;
690
+ }
691
+ case "schema": {
692
+ const slug = words[1] || requireSlug(flags);
693
+ let kp;
694
+ try {
695
+ kp = loadKeypair(flags);
696
+ } catch {
697
+ kp = void 0;
698
+ }
699
+ const d = await api(BASE, "GET", `/processors/${slug}`, kp ? { kp } : {});
700
+ const input = d.manifest?.input_schema ?? d.input_schema;
701
+ const output = d.manifest?.output_schema ?? d.output_schema;
702
+ if (emit(flags, { slug, input_schema: input, output_schema: output })) break;
703
+ ok(`${d.manifest?.name ?? d.name ?? slug}`);
704
+ if (d.manifest?.description ?? d.description) ok(`${d.manifest?.description ?? d.description}`);
705
+ const priceMicro = d.price_micro;
706
+ if (priceMicro != null) ok(`price $${usd(priceMicro)} per call`);
707
+ ok("");
708
+ ok("input:");
709
+ ok(JSON.stringify(input ?? {}, null, 2));
710
+ ok("");
711
+ ok("output:");
712
+ ok(JSON.stringify(output ?? {}, null, 2));
713
+ break;
714
+ }
715
+ case "secrets": {
716
+ const kp = loadKeypair(flags);
717
+ const slug = requireSlug(flags);
718
+ const pairs = words.slice(1);
719
+ if (!pairs.length) die("usage: singularity processors secrets KEY=value [KEY2=value2] (KEY= clears)");
720
+ const values = {};
721
+ for (const pair of pairs) {
722
+ const eq = pair.indexOf("=");
723
+ if (eq < 1) die(`bad argument "${pair}" \u2014 expected KEY=value`);
724
+ const v = pair.slice(eq + 1);
725
+ values[pair.slice(0, eq)] = v === "" ? null : v;
726
+ }
727
+ const res = await api(
728
+ BASE,
729
+ "PUT",
730
+ `/processors/${slug}/secrets`,
731
+ { body: { values }, kp }
732
+ );
733
+ if (emit(flags, res)) break;
734
+ ok(`secrets set: ${res.secrets.join(", ") || "(none)"}`);
735
+ ok("values are write-only \u2014 never returned, injected on egress");
736
+ break;
737
+ }
738
+ case "env": {
739
+ const kp = loadKeypair(flags);
740
+ const slug = requireSlug(flags);
741
+ const action = words[1] || "list";
742
+ if (action === "list") {
743
+ const d = await api(
744
+ BASE,
745
+ "GET",
746
+ `/processors/${slug}`,
747
+ { kp }
748
+ );
749
+ const declared = d.manifest?.secrets ?? [];
750
+ const set = new Set(d.secret_keys ?? []);
751
+ if (emit(flags, { declared: declared.map((s) => s.name), set: [...set] })) break;
752
+ if (!declared.length) {
753
+ ok("no secrets declared \u2014 add them to manifest.secrets, then set values");
754
+ break;
755
+ }
756
+ for (const s of declared) {
757
+ ok(`${set.has(s.name) ? "set " : "unset "} ${s.name.padEnd(28)} ${s.host ? `-> ${s.host}` : ""}`);
758
+ }
759
+ ok("");
760
+ ok("values are never readable, by you or by your code \u2014 they are injected on egress");
761
+ break;
762
+ }
763
+ if (action === "unset") {
764
+ const key = words[2];
765
+ if (!key) die("usage: singularity processors env unset KEY");
766
+ const res = await api(
767
+ BASE,
768
+ "PUT",
769
+ `/processors/${slug}/secrets`,
770
+ { body: { values: { [key]: null } }, kp }
771
+ );
772
+ if (emit(flags, res)) break;
773
+ ok(`cleared ${key}`);
774
+ ok(`still set: ${res.secrets.join(", ") || "(none)"}`);
775
+ break;
776
+ }
777
+ die("usage: singularity processors env [list | unset KEY]");
778
+ break;
779
+ }
780
+ case "list": {
781
+ const kp = loadKeypair(flags);
782
+ const res = await api(BASE, "GET", "/processors", { kp });
783
+ if (emit(flags, res)) break;
784
+ if (!res.processors.length) {
785
+ ok("no processors yet \u2014 singularity processors init");
786
+ break;
787
+ }
788
+ for (const p of res.processors) {
789
+ const state = p.status === "suspended" ? "SUSPENDED" : p.paused_at ? "paused" : p.publicly_invocable ? "public" : "private";
790
+ ok(`${state.padEnd(10)} ${p.slug.padEnd(28)} ${String(p.run_count).padStart(6)} runs $${usd(p.sales_micro)} sales $${usd(p.runtime_spent_micro)} compute`);
791
+ }
792
+ break;
793
+ }
794
+ case "search": {
795
+ const q = (words.slice(1).join(" ") || "").toLowerCase();
796
+ const res = await api(
797
+ BASE,
798
+ "GET",
799
+ "/processors",
800
+ { query: { limit: 100 } }
801
+ );
802
+ if (!res.listing_enabled) {
803
+ ok("the public catalogue is not open yet");
804
+ break;
805
+ }
806
+ const hit = (p) => !q || [p.slug, p.name, p.description, p.listing_category, ...p.listing_tags ?? []].filter(Boolean).some((f) => String(f).toLowerCase().includes(q));
807
+ const found = res.processors.filter(hit);
808
+ if (emit(flags, { query: q, processors: found })) break;
809
+ if (!found.length) {
810
+ ok(q ? `nothing matching "${q}"` : "the catalogue is empty");
811
+ break;
812
+ }
813
+ for (const p of found) {
814
+ ok(`${p.slug.padEnd(28)} $${usd(p.price_micro)} ${String(p.run_count ?? 0).padStart(6)} runs ${p.failure_rate_30d != null ? (Number(p.failure_rate_30d) * 100).toFixed(1) + "% fail" : ""}`);
815
+ if (p.description) ok(` ${String(p.description).slice(0, 96)}`);
816
+ }
817
+ ok("");
818
+ ok(`${found.length} of ${res.processors.length} run one with: singularity processors schema <slug>`);
819
+ break;
820
+ }
821
+ case "logs": {
822
+ const kp = loadKeypair(flags);
823
+ const slug = words[1] || requireSlug(flags);
824
+ const limit = Number(flags.limit || 30);
825
+ if (flags.follow === true) {
826
+ await followLogs(BASE, slug, kp, limit);
827
+ break;
828
+ }
829
+ const res = await api(
830
+ BASE,
831
+ "GET",
832
+ `/processors/${slug}/runs`,
833
+ { kp, query: { limit, ...typeof flags.logs === "string" ? { logs: flags.logs } : {} } }
834
+ );
835
+ if (emit(flags, res)) break;
836
+ printRunsPage(res);
837
+ if (res.logs) {
838
+ ok("");
839
+ for (const l of res.logs) {
840
+ ok(` ${String(l.time_offset_ms).padStart(6)}ms ${l.level.padEnd(5)} ${l.message}` + (l.truncated ? " \u2026(truncated)" : ""));
841
+ }
842
+ }
843
+ break;
844
+ }
845
+ case "revenue": {
846
+ const kp = loadKeypair(flags);
847
+ const res = await api(BASE, "GET", "/processors", { kp });
848
+ let sales = 0n, salesCount = 0n, spent = 0n, held = 0n;
849
+ for (const p of res.processors) {
850
+ sales += BigInt(p.sales_micro ?? 0);
851
+ salesCount += BigInt(p.sales_count ?? 0);
852
+ spent += BigInt(p.runtime_spent_micro ?? 0);
853
+ held += BigInt(p.runtime_held_open_micro ?? 0);
854
+ }
855
+ if (emit(flags, {
856
+ owner: res.owner,
857
+ sales_micro: String(sales),
858
+ sales_count: String(salesCount),
859
+ runtime_spent_micro: String(spent),
860
+ runtime_held_open_micro: String(held),
861
+ processors: res.processors.length
862
+ })) break;
863
+ ok(`wallet ${res.owner}`);
864
+ ok("");
865
+ ok(`Sales $${usd(sales)} ${salesCount} paid runs, sent directly to your wallet`);
866
+ ok(`Compute $${usd(spent)} spent from your credit balance`);
867
+ if (held > 0n) ok(`Held $${usd(held)} reserved against runs still in flight`);
868
+ ok("");
869
+ for (const p of [...res.processors].sort((a, b) => Number(b.sales_micro ?? 0) - Number(a.sales_micro ?? 0))) {
870
+ if (!p.sales_micro && !p.runtime_spent_micro) continue;
871
+ ok(` ${p.slug.padEnd(28)} +$${usd(p.sales_micro)} -$${usd(p.runtime_spent_micro)}`);
872
+ }
873
+ break;
874
+ }
875
+ case "earnings": {
876
+ const kp = loadKeypair(flags);
877
+ const slug = words[1] || requireSlug(flags);
878
+ const res = await api(BASE, "GET", `/processors/${slug}/earnings`, { kp });
879
+ if (emit(flags, res)) break;
880
+ ok(`Sales $${usd(res.sales.total_micro)} (${res.sales.count} paid runs, sent to ${res.sales.paid_to})`);
881
+ ok(`Compute $${usd(res.runtime.spent_micro)} spent from your credit balance`);
882
+ if (res.runtime.held_open_micro > 0) {
883
+ ok(`Held $${usd(res.runtime.held_open_micro)} reserved for runs still in flight`);
884
+ }
885
+ if (res.sales.recent?.length) {
886
+ ok();
887
+ for (const e of res.sales.recent.slice(0, 20)) {
888
+ ok(`${when(e.created_at)} +$${usd(e.price_micro)} ${e.settle_tx ? e.settle_tx.slice(0, 16) + "..." : ""}`);
889
+ }
890
+ }
891
+ break;
892
+ }
893
+ case "pause":
894
+ case "resume": {
895
+ const kp = loadKeypair(flags);
896
+ const slug = requireSlug(flags);
897
+ const paused = sub === "pause";
898
+ const res = await api(
899
+ BASE,
900
+ "PUT",
901
+ `/processors/${slug}/pause`,
902
+ { body: { paused }, kp }
903
+ );
904
+ if (emit(flags, res)) break;
905
+ ok(`${slug}: ${res.paused ? "paused" : "running"}`);
906
+ if (res.note) ok(res.note);
907
+ break;
908
+ }
909
+ case "publish":
910
+ case "unpublish": {
911
+ const kp = loadKeypair(flags);
912
+ const slug = requireSlug(flags);
913
+ const listed = sub === "publish";
914
+ const res = await api(
915
+ BASE,
916
+ "PUT",
917
+ `/processors/${slug}/listing`,
918
+ { body: { listed }, kp }
919
+ );
920
+ if (emit(flags, res)) break;
921
+ ok(res.note || (listed ? "published" : "unpublished"));
922
+ break;
923
+ }
924
+ case "rotate": {
925
+ const kp = loadKeypair(flags);
926
+ const slug = requireSlug(flags);
927
+ const res = await api(
928
+ BASE,
929
+ "POST",
930
+ `/processors/${slug}/rotate-token`,
931
+ { kp }
932
+ );
933
+ writeState({ slug, invoke_token: res.invoke_token });
934
+ if (emit(flags, res)) break;
935
+ ok(`new invoke token (saved to ${STATE_FILE}):`);
936
+ ok(` ${res.invoke_token}`);
937
+ ok("the previous token no longer works");
938
+ break;
939
+ }
940
+ case "delete": {
941
+ const kp = loadKeypair(flags);
942
+ const slug = requireSlug(flags);
943
+ if (!flags.yes) {
944
+ die(`this cannot be undone and the slug "${slug}" can NEVER be reused.
945
+ to stop traffic without losing the slug: singularity processors pause
946
+ to really delete it, re-run with --yes`);
947
+ }
948
+ await api(BASE, "DELETE", `/processors/${slug}`, { kp });
949
+ ok(`deleted ${slug} (the slug stays reserved)`);
950
+ break;
951
+ }
952
+ default:
953
+ ok(HELP);
954
+ process.exit(sub ? 1 : 0);
955
+ }
956
+ }
957
+ function printRunsPage(res) {
958
+ const s = res.stats;
959
+ ok(`${s.total} runs failure rate ${s.failure_rate == null ? "n/a" : (s.failure_rate * 100).toFixed(1) + "%"} platform faults ${s.platform_failures}`);
960
+ ok();
961
+ for (const r of res.runs) {
962
+ ok(`${when(r.created_at)} ${r.status.padEnd(16)} ${String(r.run_ms ?? "").padStart(6)}ms ${r.error ? r.error.slice(0, 60) : ""}`);
963
+ }
964
+ }
965
+ async function followLogs(base, slug, kp, limit) {
966
+ const seen = /* @__PURE__ */ new Set();
967
+ let first = true;
968
+ ok(`following ${slug} \u2014 ctrl-c to stop`);
969
+ for (; ; ) {
970
+ const res = await api(base, "GET", `/processors/${slug}/runs`, { kp, query: { limit } });
971
+ for (const r of [...res.runs].reverse()) {
972
+ const key = r.id ?? `${r.created_at}:${r.status}:${r.run_ms}`;
973
+ if (seen.has(key)) continue;
974
+ seen.add(key);
975
+ ok(`${when(r.created_at)} ${r.status.padEnd(16)} ${String(r.run_ms ?? "").padStart(6)}ms ${r.error ? r.error.slice(0, 60) : ""}`);
976
+ }
977
+ if (first) {
978
+ ok("\u2500".repeat(58) + " live");
979
+ first = false;
980
+ }
981
+ if (seen.size > 5e3) {
982
+ for (const k of [...seen].slice(0, seen.size - 1e3)) seen.delete(k);
983
+ }
984
+ await new Promise((r) => setTimeout(r, 5e3));
985
+ }
986
+ }
987
+
988
+ // src/version.ts
989
+ var VERSION = "0.2.0";
990
+
991
+ // src/cli.ts
992
+ var COMMANDS = {
993
+ processors: { run, blurb: "deploy loops we host and run on demand" }
994
+ };
995
+ var HELP2 = `singularity ${VERSION} \u2014 build on the Singularity Cloud Network
996
+
997
+ usage: singularity <command> [subcommand] [options]
998
+
999
+ commands:
1000
+ ${Object.entries(COMMANDS).map(([k, v]) => ` ${k.padEnd(14)} ${v.blurb}`).join("\n")}
1001
+ whoami print the wallet address your keypair resolves to
1002
+
1003
+ singularity <command> show that command's subcommands
1004
+ --keypair <path> defaults to ~/.config/solana/id.json
1005
+ --json machine-readable output, for scripts and agents
1006
+
1007
+ Other Singularity CLIs, deliberately separate:
1008
+ sgl run a compute node and earn (node operators)
1009
+ sglcode agentic coding on the grid (npm i -g sglcode)`;
1010
+ async function main() {
1011
+ const { words, flags } = parseArgs(process.argv.slice(2));
1012
+ const cmd = words[0];
1013
+ if (flags.version || cmd === "version") {
1014
+ ok(VERSION);
1015
+ return;
1016
+ }
1017
+ if (!cmd || flags.help || cmd === "help") {
1018
+ ok(HELP2);
1019
+ process.exit(cmd && cmd !== "help" ? 1 : 0);
1020
+ }
1021
+ if (cmd === "whoami") {
1022
+ const kp = loadKeypair(flags);
1023
+ ok(flags.json ? JSON.stringify({ address: kp.address, chain: "solana" }) : kp.address);
1024
+ return;
1025
+ }
1026
+ const entry = COMMANDS[cmd];
1027
+ if (!entry) {
1028
+ console.error(`error: unknown command "${cmd}"
1029
+ `);
1030
+ ok(HELP2);
1031
+ process.exit(1);
1032
+ }
1033
+ await entry.run(words.slice(1), flags);
1034
+ }
1035
+ main().catch((e) => {
1036
+ console.error(`error: ${e instanceof Error ? e.message : String(e)}`);
1037
+ process.exit(1);
1038
+ });