@singularity-layer/cli 0.4.0 → 0.5.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/README.md CHANGED
@@ -7,7 +7,7 @@ npm i -g @singularity-layer/cli
7
7
  singularity --help
8
8
  ```
9
9
 
10
- Requires Node 20+ and either a Solana keypair (`solana-keygen new`) or a compute API key. No
10
+ Requires Node 20+ (22+ for `sandbox connect`) and either a Solana keypair (`solana-keygen new`) or a compute API key. No
11
11
  account and no dashboard login — your wallet *is* the account.
12
12
 
13
13
  ## Processors
@@ -104,6 +104,37 @@ hard-coding the secret in their source, which is worse in every way.
104
104
 
105
105
  `singularity processors env list` shows which of yours is which.
106
106
 
107
+ ## Coding sandbox
108
+
109
+ Use your Coding sandbox (Claude Code, Codex, OpenCode or Pi on its own private computer) from your
110
+ own terminal. It is the same secure path the browser terminal uses: a single-use, 60-second ticket
111
+ and a WebSocket relayed through the sandbox's own outbound connection. No SSH, no open port.
112
+
113
+ ```bash
114
+ export SGL_API_KEY=x402c_... # see Permissions below
115
+ singularity sandbox list
116
+ singularity sandbox connect # a full shell, here. Type ~. on a new line to leave
117
+ singularity sandbox exec -- npm test # one command; exits with its exit code
118
+ singularity sandbox files # list the workspace
119
+ singularity sandbox get src/app.ts # print a file (or: get src/app.ts ./app.ts)
120
+ singularity sandbox put ./notes.md # upload a text file (up to 100 KB)
121
+ singularity sandbox key # an OpenAI-compatible key for the sandbox's agent
122
+ ```
123
+
124
+ A sleeping sandbox wakes by itself when you connect or run something. `connect` needs Node 22 or
125
+ newer (it uses the built-in WebSocket). With more than one sandbox, name it: its id, the first few
126
+ characters of the id, or its name (`singularity sandbox connect 99a7`).
127
+
128
+ **OpenAI-compatible address.** `singularity sandbox key` prints a key and a base URL like
129
+ `https://compute.x402layer.cc/pods/<id>/v1`. Point any OpenAI client at it with model `agent-pod`;
130
+ each request is one turn of the sandbox's coding agent (streaming works). The agent can run commands
131
+ on the sandbox, so treat the key like a password. `keys` lists them, `revoke-key` turns one off.
132
+
133
+ Permissions: the terminal, exec, files and keys all need a compute API key (Settings > API keys)
134
+ with the Agent Pods permission "Read and write pod files, install skills, create and restore
135
+ backups" (`pods:control:write`), or a keypair. Keys from a Google, GitHub or X login can use `connect`, `key`
136
+ and `keys`; `exec`, `files`, `get` and `put` need a key from a wallet login.
137
+
107
138
  ## Processor state
108
139
 
109
140
  A processor is a fresh isolate every run, so anything you want to keep has to go somewhere:
package/dist/cli.js CHANGED
@@ -27,9 +27,9 @@ function bs58(bytes) {
27
27
  carry = carry / 58 | 0;
28
28
  }
29
29
  }
30
- let out = "1".repeat(zeros);
31
- for (let i = digits.length - 1; i >= 0; i--) out += B58[digits[i]];
32
- return out;
30
+ let out2 = "1".repeat(zeros);
31
+ for (let i = digits.length - 1; i >= 0; i--) out2 += B58[digits[i]];
32
+ return out2;
33
33
  }
34
34
  function loadKeypair(flags = {}) {
35
35
  const path = String(
@@ -148,6 +148,11 @@ function parseArgs(argv) {
148
148
  const words = [];
149
149
  for (let i = 0; i < argv.length; i++) {
150
150
  const tok = argv[i];
151
+ if (tok === "--") {
152
+ flags["--"] = String(words.length);
153
+ for (const rest of argv.slice(i + 1)) words.push(rest);
154
+ break;
155
+ }
151
156
  if (tok.startsWith("--")) {
152
157
  const name = tok.slice(2);
153
158
  const next = argv[i + 1];
@@ -263,7 +268,7 @@ function guardBuiltins() {
263
268
  };
264
269
  }
265
270
  function collectSources(dir, inputs) {
266
- const out = {};
271
+ const out2 = {};
267
272
  const root = realpathSync(dir);
268
273
  for (const rel of inputs) {
269
274
  if (rel.split("/").includes("node_modules")) continue;
@@ -278,9 +283,9 @@ function collectSources(dir, inputs) {
278
283
  const real = realpathSync(full);
279
284
  if (real !== root && !real.startsWith(root + sep)) continue;
280
285
  if (st.size > 256 * 1024) continue;
281
- out[relative(root, real)] = readFileSync2(real, "utf8");
286
+ out2[relative(root, real)] = readFileSync2(real, "utf8");
282
287
  }
283
- return out;
288
+ return out2;
284
289
  }
285
290
  async function bundleProcessor(opts) {
286
291
  const { entry, cwd } = opts;
@@ -582,7 +587,7 @@ async function promptForSchema(schema) {
582
587
  }
583
588
  }
584
589
  const required = new Set(schema?.required ?? []);
585
- const out = {};
590
+ const out2 = {};
586
591
  ok("");
587
592
  for (const [name, spec] of Object.entries(props)) {
588
593
  const label = [
@@ -600,32 +605,32 @@ async function promptForSchema(schema) {
600
605
  }
601
606
  continue;
602
607
  }
603
- out[name] = coerce(raw, spec.type);
608
+ out2[name] = coerce(raw, spec.type);
604
609
  }
605
610
  ok("");
606
- return out;
611
+ return out2;
607
612
  }
608
613
  function toQuery(input) {
609
614
  if (input === void 0 || input === null) return {};
610
615
  if (typeof input !== "object" || Array.isArray(input)) {
611
616
  return die("--get needs a JSON object of scalar fields");
612
617
  }
613
- const out = {};
618
+ const out2 = {};
614
619
  for (const [k, v] of Object.entries(input)) {
615
620
  if (v === void 0 || v === null) continue;
616
621
  if (Array.isArray(v)) {
617
622
  if (v.some((x) => x !== null && typeof x === "object")) {
618
623
  return die(`--get cannot send nested objects (field "${k}") \u2014 drop --get to POST it`);
619
624
  }
620
- out[k] = v.map((x) => typeof x === "number" ? x : String(x));
625
+ out2[k] = v.map((x) => typeof x === "number" ? x : String(x));
621
626
  continue;
622
627
  }
623
628
  if (typeof v === "object") {
624
629
  return die(`--get cannot send nested objects (field "${k}") \u2014 drop --get to POST it`);
625
630
  }
626
- out[k] = typeof v === "number" ? v : String(v);
631
+ out2[k] = typeof v === "number" ? v : String(v);
627
632
  }
628
- return out;
633
+ return out2;
629
634
  }
630
635
  async function invokeAndWait(base, slug, input, creds, token, quiet, asGet = false) {
631
636
  let res = asGet ? await api(base, "GET", `/processors/${slug}/run`, {
@@ -1081,14 +1086,544 @@ async function followLogs(base, slug, creds, limit) {
1081
1086
  }
1082
1087
  }
1083
1088
 
1089
+ // src/sandbox.ts
1090
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync2, existsSync as existsSync4, statSync } from "node:fs";
1091
+ import { createHash as createHash2, randomBytes } from "node:crypto";
1092
+ import nacl2 from "tweetnacl";
1093
+ var DEFAULT_COMPUTE = "https://compute.x402layer.cc";
1094
+ var MAX_PUT_BYTES = 100 * 1024;
1095
+ var HELP2 = `singularity sandbox: use your Coding sandbox from your own terminal
1096
+
1097
+ usage: singularity sandbox <subcommand> [sandbox] [options]
1098
+
1099
+ list your Coding sandboxes
1100
+ status [sandbox] state, harness, awake hours this month
1101
+ connect [sandbox] open the sandbox's terminal here (a full shell)
1102
+ type ~. at the start of a line to disconnect
1103
+ exec [sandbox] -- <command> run one command, print its output, exit with its code
1104
+ --timeout <seconds> 1 to 300 (default 60)
1105
+ files [sandbox] list the files in the workspace
1106
+ get [sandbox] <path> [local] print a workspace file, or save it to <local>
1107
+ put [sandbox] <local> [path] upload a text file (up to 100 KB) into the workspace
1108
+ wake [sandbox] | sleep [sandbox]
1109
+ key [sandbox] [--name <n>] create an OpenAI-compatible key for the sandbox's coding agent
1110
+ keys [sandbox] list those keys
1111
+ revoke-key [sandbox] <key-id>
1112
+
1113
+ [sandbox] is the sandbox id, the start of it, or its name (or pass --sandbox <it>).
1114
+ Leave it out if you have only one.
1115
+
1116
+ auth: SGL_API_KEY=x402c_... a compute API key from Settings > API keys. connect, exec, files
1117
+ and key need the Agent Pods permission "Read and write pod
1118
+ files, install skills, create and restore backups"
1119
+ (pods:control:write).
1120
+ --keypair <path> or sign with a Solana keypair (default ~/.config/solana/id.json)
1121
+ --compute-url <url> another API base (default ${DEFAULT_COMPUTE})
1122
+ --json machine-readable output
1123
+
1124
+ OpenAI-compatible address: after 'key', point any OpenAI client at the printed base URL with
1125
+ model "agent-pod". Each request is one turn of the sandbox's coding agent.`;
1126
+ function computeBase(flags) {
1127
+ const override = typeof flags["compute-url"] === "string" && flags["compute-url"] || process.env.SINGULARITY_COMPUTE_URL;
1128
+ if (override) {
1129
+ let u;
1130
+ try {
1131
+ u = new URL(String(override));
1132
+ } catch {
1133
+ return die(`--compute-url is not a URL: ${override}`);
1134
+ }
1135
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
1136
+ if (u.protocol !== "https:" && !(local && u.protocol === "http:")) die("--compute-url must be https (http only for localhost)");
1137
+ process.stderr.write(`(using ${override})
1138
+ `);
1139
+ return String(override).replace(/\/+$/, "");
1140
+ }
1141
+ return DEFAULT_COMPUTE;
1142
+ }
1143
+ var sha256Hex2 = (s) => createHash2("sha256").update(s, "utf8").digest("hex");
1144
+ function computeAuthHeaders(creds, method, pathAndQuery, bodyText, now = Date.now(), nonce = randomBytes(16).toString("hex")) {
1145
+ if (creds.apiKey) return { "X-API-Key": creds.apiKey };
1146
+ const kp = creds.kp;
1147
+ if (!kp) return die("no credential");
1148
+ const message = ["X402-COMPUTE-AUTH", "v1", "solana", kp.address, method.toUpperCase(), pathAndQuery, sha256Hex2(bodyText), String(now), nonce].join("\n");
1149
+ const sig = nacl2.sign.detached(new TextEncoder().encode(message), kp.secretKey);
1150
+ return {
1151
+ "X-Auth-Address": kp.address,
1152
+ "X-Auth-Chain": "solana",
1153
+ "X-Auth-Signature": Buffer.from(sig).toString("base64"),
1154
+ "X-Auth-Sig-Encoding": "base64",
1155
+ "X-Auth-Timestamp": String(now),
1156
+ "X-Auth-Nonce": nonce
1157
+ };
1158
+ }
1159
+ var ApiError = class extends Error {
1160
+ constructor(status, message, code, details) {
1161
+ super(message);
1162
+ this.status = status;
1163
+ this.code = code;
1164
+ this.details = details;
1165
+ }
1166
+ get retryAfter() {
1167
+ return Number(this.details.retry_after_seconds) || 0;
1168
+ }
1169
+ };
1170
+ function parseApiError(status, text) {
1171
+ let p;
1172
+ try {
1173
+ p = JSON.parse(text);
1174
+ } catch {
1175
+ p = null;
1176
+ }
1177
+ if (p && typeof p.error === "object" && p.error) {
1178
+ const details = p.error.details && typeof p.error.details === "object" ? p.error.details : {};
1179
+ return new ApiError(status, String(p.error.message || p.error.code || `HTTP ${status}`), String(details.code || details.reason || p.error.code || ""), details);
1180
+ }
1181
+ if (p && typeof p === "object") {
1182
+ const details = p.details && typeof p.details === "object" ? { ...p, ...p.details } : p;
1183
+ return new ApiError(status, String(p.error || p.message || `HTTP ${status}`), String(p.code || details.code || ""), details);
1184
+ }
1185
+ return new ApiError(status, text.slice(0, 300) || `HTTP ${status}`, "", {});
1186
+ }
1187
+ async function call(ctx, method, path, body) {
1188
+ const bodyText = body === void 0 ? "" : JSON.stringify(body);
1189
+ const headers = computeAuthHeaders(ctx.creds, method, path, bodyText);
1190
+ if (body !== void 0) headers["content-type"] = "application/json";
1191
+ let res;
1192
+ try {
1193
+ res = await fetch(ctx.base + path, { method, headers, body: body === void 0 ? void 0 : bodyText });
1194
+ } catch (e) {
1195
+ throw new ApiError(0, `could not reach ${ctx.base}: ${e instanceof Error ? e.message : String(e)}`, "network", {});
1196
+ }
1197
+ const text = await res.text();
1198
+ if (!res.ok) throw parseApiError(res.status, text);
1199
+ try {
1200
+ return text ? JSON.parse(text) : {};
1201
+ } catch {
1202
+ return {};
1203
+ }
1204
+ }
1205
+ var sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
1206
+ function explain(e) {
1207
+ if (!(e instanceof ApiError)) return e instanceof Error ? e.message : String(e);
1208
+ if (e.status === 401) return `${e.message}. Check SGL_API_KEY (or your keypair).`;
1209
+ if (e.status === 403 && /pods:control:write/.test(e.message + JSON.stringify(e.details))) {
1210
+ return `${e.message}
1211
+ Create a key in Settings > API keys and tick, under Agent Pods, "Read and write pod files,
1212
+ install skills, create and restore backups" (pods:control:write). Use it as SGL_API_KEY.`;
1213
+ }
1214
+ if (e.status === 403 && (e.code === "wallet_required" || /needs a wallet/i.test(e.message))) {
1215
+ return `${e.message}
1216
+ exec, files and keys go through the pod API, which needs a key from a wallet login. 'singularity sandbox connect' works with any key.`;
1217
+ }
1218
+ return e.message;
1219
+ }
1220
+ function fail(e) {
1221
+ return die(explain(e));
1222
+ }
1223
+ async function listSandboxes(ctx) {
1224
+ const r = await call(ctx, "GET", "/pods");
1225
+ return (r.pods || []).filter((p) => p && p.agent_id === "coding" && !["destroyed", "deleted", "failed"].includes(String(p.status))).map((p) => ({ id: String(p.id), name: p.name ?? null, status: String(p.status), model: p.model ?? null, ai_mode: p.ai_mode }));
1226
+ }
1227
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1228
+ function pickSandbox(rows, ref) {
1229
+ if (!ref) {
1230
+ if (rows.length === 1) return { id: rows[0].id };
1231
+ if (!rows.length) return { error: "you have no Coding sandbox. Create one in Studio or Cloud first." };
1232
+ return { error: `you have ${rows.length} sandboxes; name one:
1233
+ ` + rows.map((r) => ` ${r.id} ${r.name || ""}`).join("\n") };
1234
+ }
1235
+ const exact = rows.filter((r) => r.id === ref.toLowerCase() || r.name === ref);
1236
+ if (exact.length === 1) return { id: exact[0].id };
1237
+ const pre = rows.filter((r) => r.id.startsWith(ref.toLowerCase()));
1238
+ if (pre.length === 1) return { id: pre[0].id };
1239
+ if (exact.length + pre.length > 1) return { error: `"${ref}" matches more than one sandbox; use more of the id` };
1240
+ return { error: `no Coding sandbox matches "${ref}"` };
1241
+ }
1242
+ async function resolveId(ctx, ref) {
1243
+ if (ref && UUID.test(ref)) return ref.toLowerCase();
1244
+ const rows = await listSandboxes(ctx).catch(fail);
1245
+ const p = pickSandbox(rows, ref);
1246
+ if ("error" in p) return die(p.error);
1247
+ return p.id;
1248
+ }
1249
+ var isAsleepError = (e) => e instanceof ApiError && (e.code === "waking" || e.details.reason === "waking" || e.status === 409 && /offline|waking|start it/i.test(e.message));
1250
+ async function withWake(ctx, id, fn) {
1251
+ let asked = false;
1252
+ for (let i = 0; ; i++) {
1253
+ try {
1254
+ return await fn();
1255
+ } catch (e) {
1256
+ if (!isAsleepError(e) || i >= 15) throw e;
1257
+ if (i === 0) process.stderr.write("Waking your sandbox...\n");
1258
+ if (!asked) {
1259
+ asked = true;
1260
+ await call(ctx, "POST", `/pods/${id}/coding/wake`).catch(() => void 0);
1261
+ }
1262
+ await sleepMs(Math.max(2, e.retryAfter || 4) * 1e3);
1263
+ }
1264
+ }
1265
+ }
1266
+ async function openTerminalUrl(ctx, id) {
1267
+ for (let i = 0; ; i++) {
1268
+ try {
1269
+ const r = await call(ctx, "POST", `/pods/${id}/coding/terminal`);
1270
+ const path = r.path || (r.ticket ? `/pods/screen/${encodeURIComponent(r.ticket)}` : "");
1271
+ if (!path.startsWith("/pods/screen/")) throw new ApiError(502, "the server did not return a terminal link", "", {});
1272
+ return ctx.base.replace(/^http/, "ws") + path;
1273
+ } catch (e) {
1274
+ if (!(e instanceof ApiError && e.code === "waking") || i >= 15) throw e;
1275
+ if (i === 0) process.stderr.write("Waking your sandbox...\n");
1276
+ await sleepMs(Math.max(2, e.retryAfter || 4) * 1e3);
1277
+ }
1278
+ }
1279
+ }
1280
+ function makeEscapeFilter() {
1281
+ let lineStart = true;
1282
+ let held = false;
1283
+ return (chunk) => {
1284
+ const out2 = [];
1285
+ for (const b of chunk) {
1286
+ if (held) {
1287
+ held = false;
1288
+ if (b === 46) return { send: Uint8Array.from(out2), disconnect: true };
1289
+ if (b === 126) {
1290
+ out2.push(126);
1291
+ lineStart = false;
1292
+ continue;
1293
+ }
1294
+ out2.push(126);
1295
+ } else if (lineStart && b === 126) {
1296
+ held = true;
1297
+ continue;
1298
+ }
1299
+ out2.push(b);
1300
+ lineStart = b === 13 || b === 10;
1301
+ }
1302
+ return { send: Uint8Array.from(out2), disconnect: false };
1303
+ };
1304
+ }
1305
+ function closeMessage(code, reason) {
1306
+ if (code === 1e3 || code === 1005) return { text: "Connection closed.", exit: 0 };
1307
+ if (code === 4006) return { text: "Closed after 10 idle minutes.", exit: 0 };
1308
+ if (code === 1006) return { text: "The terminal connection dropped.", exit: 1 };
1309
+ return { text: `The terminal closed${reason ? ": " + reason : ""} (${code}).`, exit: 1 };
1310
+ }
1311
+ async function connect(ctx, id) {
1312
+ const WS = globalThis.WebSocket;
1313
+ if (!WS) die("connect needs Node.js 22 or newer (it uses the built-in WebSocket). Run: node --version");
1314
+ const url = await openTerminalUrl(ctx, id).catch(fail);
1315
+ const stdin = process.stdin;
1316
+ const tty = !!stdin.isTTY;
1317
+ const ws = new WS(url);
1318
+ ws.binaryType = "arraybuffer";
1319
+ const filter = makeEscapeFilter();
1320
+ let opened = false;
1321
+ let restored = false;
1322
+ const restore = () => {
1323
+ if (restored) return;
1324
+ restored = true;
1325
+ if (tty) {
1326
+ try {
1327
+ stdin.setRawMode(false);
1328
+ } catch {
1329
+ }
1330
+ }
1331
+ stdin.pause();
1332
+ stdin.unref();
1333
+ };
1334
+ process.on("exit", restore);
1335
+ const sendSize = () => {
1336
+ if (ws.readyState === 1) ws.send(JSON.stringify({ cols: process.stdout.columns || 80, rows: process.stdout.rows || 24 }));
1337
+ };
1338
+ const onData = (buf) => {
1339
+ const { send, disconnect } = tty ? filter(buf) : { send: new Uint8Array(buf), disconnect: false };
1340
+ if (send.length && ws.readyState === 1) ws.send(send);
1341
+ if (disconnect) {
1342
+ process.stderr.write("\r\nDisconnected.\r\n");
1343
+ try {
1344
+ ws.close(1e3);
1345
+ } catch {
1346
+ }
1347
+ }
1348
+ };
1349
+ const onEnd = () => {
1350
+ if (!tty && ws.readyState === 1) ws.send(new Uint8Array([4]));
1351
+ };
1352
+ const done = new Promise((resolve2) => {
1353
+ ws.onopen = () => {
1354
+ opened = true;
1355
+ if (tty) {
1356
+ stdin.setRawMode(true);
1357
+ process.stderr.write("Connected. Type ~. at the start of a line to disconnect.\r\n");
1358
+ }
1359
+ stdin.on("data", onData);
1360
+ stdin.on("end", onEnd);
1361
+ stdin.resume();
1362
+ sendSize();
1363
+ if (process.stdout.isTTY) process.stdout.on("resize", sendSize);
1364
+ };
1365
+ ws.onmessage = (e) => {
1366
+ if (e.data instanceof ArrayBuffer) process.stdout.write(Buffer.from(e.data));
1367
+ };
1368
+ ws.onerror = () => {
1369
+ };
1370
+ ws.onclose = (e) => {
1371
+ restore();
1372
+ process.stdout.off("resize", sendSize);
1373
+ stdin.off("data", onData);
1374
+ stdin.off("end", onEnd);
1375
+ if (!opened) {
1376
+ process.stderr.write("Could not open the terminal (the link is single use and lasts 60 seconds). Try again.\n");
1377
+ process.exitCode = 1;
1378
+ } else {
1379
+ const m = closeMessage(e.code, e.reason);
1380
+ process.stderr.write(`\r
1381
+ ${m.text}
1382
+ `);
1383
+ process.exitCode = m.exit;
1384
+ }
1385
+ resolve2();
1386
+ };
1387
+ });
1388
+ const bye = () => {
1389
+ try {
1390
+ ws.close(1e3);
1391
+ } catch {
1392
+ }
1393
+ };
1394
+ for (const sig of ["SIGTERM", "SIGHUP", "SIGINT", "SIGQUIT"]) process.once(sig, bye);
1395
+ await done;
1396
+ }
1397
+ async function mintKey(ctx, id, name) {
1398
+ try {
1399
+ const r = await call(ctx, "POST", `/pods/v1/pods/${id}/keys`, { name });
1400
+ return { id: r.key.id, secret: r.key.secret, base_url: r.endpoint.base_url, model: r.endpoint.model || "agent-pod" };
1401
+ } catch (e) {
1402
+ if (!(e instanceof ApiError && e.status === 403 && (e.code === "wallet_required" || /needs a wallet/i.test(e.message)))) throw e;
1403
+ const r = await call(ctx, "POST", `/pods/${id}/api-keys`, { name });
1404
+ return { id: r.row?.id, secret: r.key, base_url: r.base_url, model: "agent-pod" };
1405
+ }
1406
+ }
1407
+ async function listKeys(ctx, id) {
1408
+ try {
1409
+ return (await call(ctx, "GET", `/pods/v1/pods/${id}/keys`)).keys || [];
1410
+ } catch (e) {
1411
+ if (!(e instanceof ApiError && e.status === 403 && (e.code === "wallet_required" || /needs a wallet/i.test(e.message)))) throw e;
1412
+ return ((await call(ctx, "GET", `/pods/${id}/api-keys`)).keys || []).map((k) => ({ ...k, revoked: Boolean(k.revoked_at) }));
1413
+ }
1414
+ }
1415
+ async function revokeKey(ctx, id, keyId) {
1416
+ try {
1417
+ await call(ctx, "DELETE", `/pods/v1/pods/${id}/keys/${keyId}`);
1418
+ } catch (e) {
1419
+ if (!(e instanceof ApiError && e.status === 403 && (e.code === "wallet_required" || /needs a wallet/i.test(e.message)))) throw e;
1420
+ await call(ctx, "DELETE", `/pods/${id}/api-keys/${keyId}`);
1421
+ }
1422
+ }
1423
+ function checkUpload(buf) {
1424
+ if (buf.length > MAX_PUT_BYTES) return `that file is ${Math.ceil(buf.length / 1024)} KB; put takes text files up to ${MAX_PUT_BYTES / 1024} KB. Use git or the terminal for bigger files.`;
1425
+ if (buf.includes(0)) return "that looks like a binary file; put takes text files. Use git or the terminal for binaries.";
1426
+ if (Buffer.from(buf.toString("utf8"), "utf8").compare(buf) !== 0) return "that file is not UTF-8 text; put takes text files.";
1427
+ return null;
1428
+ }
1429
+ var out = (ctx, human, data) => ok(ctx.json ? JSON.stringify(data) : human);
1430
+ async function run2(words, flags) {
1431
+ const sub = words[0];
1432
+ if (!sub || flags.help) {
1433
+ ok(HELP2);
1434
+ if (!sub) process.exit(1);
1435
+ return;
1436
+ }
1437
+ const ctx = { base: computeBase(flags), creds: loadCreds(flags), json: !!flags.json };
1438
+ const args = words.slice(1);
1439
+ const sref = typeof flags.sandbox === "string" ? flags.sandbox : void 0;
1440
+ switch (sub) {
1441
+ case "list":
1442
+ case "ls": {
1443
+ const rows = await listSandboxes(ctx).catch(fail);
1444
+ if (ctx.json) {
1445
+ ok(JSON.stringify(rows));
1446
+ break;
1447
+ }
1448
+ if (!rows.length) {
1449
+ ok("No Coding sandboxes yet. Create one in Studio or Cloud.");
1450
+ break;
1451
+ }
1452
+ for (const r of rows) ok(`${r.id} ${(r.name || "").padEnd(20)} ${r.status}`);
1453
+ break;
1454
+ }
1455
+ case "status": {
1456
+ const id = await resolveId(ctx, sref || args[0]);
1457
+ const r = await call(ctx, "GET", `/pods/${id}/coding`).catch(fail);
1458
+ const c = r.coding || r;
1459
+ out(ctx, [
1460
+ `${id} ${c.harness_name || c.harness || ""}`,
1461
+ `state ${c.state}${c.busy ? " (working)" : ""}`,
1462
+ `awake hours ${c.awake_hours} of ${c.included_hours} included this month`,
1463
+ `sleeps after ${c.idle_sleep_minutes} idle minutes`
1464
+ ].join("\n"), c);
1465
+ break;
1466
+ }
1467
+ case "connect":
1468
+ case "shell":
1469
+ case "ssh": {
1470
+ const id = await resolveId(ctx, sref || args[0]);
1471
+ await connect(ctx, id);
1472
+ break;
1473
+ }
1474
+ case "exec": {
1475
+ const sep2 = typeof flags["--"] === "string" ? Number(flags["--"]) - 2 : -1;
1476
+ let ref;
1477
+ let rest;
1478
+ if (sep2 >= 0) {
1479
+ ref = sref || (sep2 > 0 ? args[0] : void 0);
1480
+ rest = args.slice(sep2);
1481
+ } else {
1482
+ [ref, rest] = splitRef(args, Infinity, sref);
1483
+ }
1484
+ const command = rest.join(" ").trim();
1485
+ if (!command) die("usage: singularity sandbox exec [sandbox] -- <command>");
1486
+ const id = await resolveId(ctx, ref);
1487
+ const timeout = flags.timeout ? Number(flags.timeout) : 60;
1488
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > 300) die("--timeout must be 1 to 300 seconds");
1489
+ const r = await withWake(ctx, id, () => call(ctx, "POST", `/pods/v1/pods/${id}/exec`, { command, timeout_seconds: timeout })).catch(fail);
1490
+ const x = r.exec || {};
1491
+ if (ctx.json) {
1492
+ ok(JSON.stringify(x));
1493
+ break;
1494
+ }
1495
+ if (x.stdout) process.stdout.write(x.stdout);
1496
+ if (x.stderr) process.stderr.write(x.stderr);
1497
+ if (x.truncated) process.stderr.write("\n(output was cut short)\n");
1498
+ if (x.timed_out) {
1499
+ process.stderr.write(`
1500
+ (timed out after ${timeout}s)
1501
+ `);
1502
+ process.exitCode = 124;
1503
+ break;
1504
+ }
1505
+ process.exitCode = typeof x.exit_code === "number" ? x.exit_code : 1;
1506
+ break;
1507
+ }
1508
+ case "files": {
1509
+ const id = await resolveId(ctx, sref || args[0]);
1510
+ const r = await withWake(ctx, id, () => call(ctx, "GET", `/pods/v1/pods/${id}/files`)).catch(fail);
1511
+ if (ctx.json) {
1512
+ ok(JSON.stringify(r));
1513
+ break;
1514
+ }
1515
+ const files = r.files || [];
1516
+ if (!files.length) {
1517
+ ok("(the workspace is empty)");
1518
+ break;
1519
+ }
1520
+ for (const f of files) ok(`${String(f.size).padStart(9)} ${f.path}`);
1521
+ break;
1522
+ }
1523
+ case "get":
1524
+ case "cat": {
1525
+ const [ref, rest] = splitRef(args, 2, sref);
1526
+ const [remote, local] = rest;
1527
+ if (!remote) die("usage: singularity sandbox get [sandbox] <path> [local-file]");
1528
+ const id = await resolveId(ctx, ref);
1529
+ const r = await withWake(ctx, id, () => call(ctx, "GET", `/pods/v1/pods/${id}/files?path=${encodeURIComponent(remote)}`)).catch(fail);
1530
+ const content = String(r.file?.content ?? "");
1531
+ if (local && local !== "-") {
1532
+ writeFileSync2(local, content);
1533
+ out(ctx, `saved ${local}`, { path: r.file?.path, saved: local });
1534
+ } else process.stdout.write(content);
1535
+ break;
1536
+ }
1537
+ case "put": {
1538
+ const [ref, rest] = splitRef(args, 2, sref);
1539
+ const [local, remote] = rest;
1540
+ if (!local) die("usage: singularity sandbox put [sandbox] <local-file> [path]");
1541
+ if (!existsSync4(local) || !statSync(local).isFile()) die(`no file at ${local}`);
1542
+ const buf = readFileSync4(local);
1543
+ const bad = checkUpload(buf);
1544
+ if (bad) die(bad);
1545
+ const path = remote || local.split(/[\\/]/).pop();
1546
+ const id = await resolveId(ctx, ref);
1547
+ const r = await withWake(ctx, id, () => call(ctx, "PUT", `/pods/v1/pods/${id}/files`, { path, content: buf.toString("utf8") })).catch(fail);
1548
+ out(ctx, `uploaded ${r.file?.path ?? path} (${r.file?.size ?? buf.length} bytes)`, r.file);
1549
+ break;
1550
+ }
1551
+ case "wake":
1552
+ case "sleep": {
1553
+ const id = await resolveId(ctx, sref || args[0]);
1554
+ await call(ctx, "POST", `/pods/${id}/coding/${sub}`).catch(fail);
1555
+ out(ctx, sub === "wake" ? "Awake." : "Asleep. It wakes again when you connect or send it work.", { ok: true });
1556
+ break;
1557
+ }
1558
+ case "key": {
1559
+ const id = await resolveId(ctx, sref || args[0]);
1560
+ const name = typeof flags.name === "string" ? flags.name : "CLI key";
1561
+ const k = await mintKey(ctx, id, name).catch(fail);
1562
+ if (ctx.json) {
1563
+ ok(JSON.stringify(k));
1564
+ break;
1565
+ }
1566
+ ok(`key ${k.secret}`);
1567
+ ok(`base URL ${k.base_url}`);
1568
+ ok(`model ${k.model}`);
1569
+ ok("");
1570
+ ok("Shown once: store it now. Anyone with it can give your sandbox's coding agent work,");
1571
+ ok(`and the agent can run commands there. Revoke it with: singularity sandbox revoke-key ${id.slice(0, 8)} ${k.id}`);
1572
+ ok("");
1573
+ ok(`curl ${k.base_url}/chat/completions \\`);
1574
+ ok(' -H "Authorization: Bearer $KEY" -H "content-type: application/json" \\');
1575
+ ok(` -d '{"model":"${k.model}","stream":true,"messages":[{"role":"user","content":"hello"}]}'`);
1576
+ break;
1577
+ }
1578
+ case "keys": {
1579
+ const id = await resolveId(ctx, sref || args[0]);
1580
+ const keys = await listKeys(ctx, id).catch(fail);
1581
+ if (ctx.json) {
1582
+ ok(JSON.stringify(keys));
1583
+ break;
1584
+ }
1585
+ if (!keys.length) {
1586
+ ok("No keys. Create one with: singularity sandbox key");
1587
+ break;
1588
+ }
1589
+ for (const k of keys) ok(`${k.id} ${k.prefix || ""}...${k.last4 || ""} ${(k.name || "").padEnd(16)} ${k.revoked ? "revoked" : "active"}`);
1590
+ break;
1591
+ }
1592
+ case "revoke-key": {
1593
+ const [ref, rest] = splitRef(args, 1, sref);
1594
+ const keyId = rest[0];
1595
+ if (!keyId || !UUID.test(keyId)) die("usage: singularity sandbox revoke-key [sandbox] <key-id>");
1596
+ const id = await resolveId(ctx, ref);
1597
+ await revokeKey(ctx, id, keyId).catch(fail);
1598
+ out(ctx, "Revoked.", { ok: true });
1599
+ break;
1600
+ }
1601
+ default:
1602
+ console.error(`error: unknown sandbox subcommand "${sub}"
1603
+ `);
1604
+ ok(HELP2);
1605
+ process.exit(1);
1606
+ }
1607
+ }
1608
+ function splitRef(args, maxOwn, flagRef) {
1609
+ if (flagRef) return [flagRef, args];
1610
+ if (args.length > maxOwn) return [args[0], args.slice(1)];
1611
+ if (args.length > 1 && (UUID.test(args[0]) || looksLikeRef(args[0]))) return [args[0], args.slice(1)];
1612
+ return [void 0, args];
1613
+ }
1614
+ function looksLikeRef(s) {
1615
+ return /^[0-9a-f]{4,}(-[0-9a-f-]*)?$/i.test(s) && !s.includes(".") && !s.includes("/");
1616
+ }
1617
+
1084
1618
  // src/version.ts
1085
- var VERSION = "0.4.0";
1619
+ var VERSION = "0.5.0";
1086
1620
 
1087
1621
  // src/cli.ts
1088
1622
  var COMMANDS = {
1089
- processors: { run, blurb: "deploy loops we host and run on demand" }
1623
+ processors: { run, blurb: "deploy loops we host and run on demand" },
1624
+ sandbox: { run: run2, blurb: "use your Coding sandbox: terminal, exec, files, OpenAI-compatible key" }
1090
1625
  };
1091
- var HELP2 = `singularity ${VERSION} \u2014 build on the Singularity Cloud Network
1626
+ var HELP3 = `singularity ${VERSION} \u2014 build on the Singularity Cloud Network
1092
1627
 
1093
1628
  usage: singularity <command> [subcommand] [options]
1094
1629
 
@@ -1121,7 +1656,7 @@ async function main() {
1121
1656
  return;
1122
1657
  }
1123
1658
  if (!cmd || flags.help || cmd === "help") {
1124
- ok(HELP2);
1659
+ ok(HELP3);
1125
1660
  process.exit(cmd && cmd !== "help" ? 1 : 0);
1126
1661
  }
1127
1662
  if (cmd === "whoami") {
@@ -1142,7 +1677,7 @@ async function main() {
1142
1677
  if (!entry) {
1143
1678
  console.error(`error: unknown command "${cmd}"
1144
1679
  `);
1145
- ok(HELP2);
1680
+ ok(HELP3);
1146
1681
  process.exit(1);
1147
1682
  }
1148
1683
  await entry.run(words.slice(1), flags);
package/dist/index.js CHANGED
@@ -121,6 +121,11 @@ function parseArgs(argv) {
121
121
  const words = [];
122
122
  for (let i = 0; i < argv.length; i++) {
123
123
  const tok = argv[i];
124
+ if (tok === "--") {
125
+ flags["--"] = String(words.length);
126
+ for (const rest of argv.slice(i + 1)) words.push(rest);
127
+ break;
128
+ }
124
129
  if (tok.startsWith("--")) {
125
130
  const name = tok.slice(2);
126
131
  const next = argv[i + 1];
@@ -301,7 +306,7 @@ function coerce(raw, type) {
301
306
  }
302
307
 
303
308
  // src/version.ts
304
- var VERSION = "0.4.0";
309
+ var VERSION = "0.5.0";
305
310
  export {
306
311
  MAX_BUNDLE_BYTES,
307
312
  VERSION,
@@ -0,0 +1,87 @@
1
+ /**
2
+ * `singularity sandbox`: use a Coding sandbox from your own terminal.
3
+ *
4
+ * Every command here is the SAME API the browser uses, nothing new is exposed:
5
+ * connect POST /pods/<id>/coding/terminal gives a single-use, 60-second ticket; the terminal is
6
+ * a WebSocket to /pods/screen/<ticket>, relayed by the sandbox's own outbound tunnel.
7
+ * No SSH, no open port. Text frame {cols, rows} = resize, binary = keystrokes/output.
8
+ * exec POST /pods/v1/pods/<id>/exec
9
+ * files GET/PUT /pods/v1/pods/<id>/files
10
+ * key an OpenAI-compatible key for https://compute.x402layer.cc/pods/<id>/v1
11
+ *
12
+ * Auth: a compute API key (SGL_API_KEY) or a Solana keypair, signed per request with the compute
13
+ * scheme (not the processors one: the two services verify different messages). The terminal, exec
14
+ * and files need a key with the pods:control:write permission, because each one is a shell.
15
+ */
16
+ import { type Flags, type Creds } from './auth.js';
17
+ /** The sandbox file API takes text up to this size (the request body cap is 128 KiB, JSON-escaped). */
18
+ export declare const MAX_PUT_BYTES: number;
19
+ export declare const HELP = "singularity sandbox: use your Coding sandbox from your own terminal\n\nusage: singularity sandbox <subcommand> [sandbox] [options]\n\n list your Coding sandboxes\n status [sandbox] state, harness, awake hours this month\n connect [sandbox] open the sandbox's terminal here (a full shell)\n type ~. at the start of a line to disconnect\n exec [sandbox] -- <command> run one command, print its output, exit with its code\n --timeout <seconds> 1 to 300 (default 60)\n files [sandbox] list the files in the workspace\n get [sandbox] <path> [local] print a workspace file, or save it to <local>\n put [sandbox] <local> [path] upload a text file (up to 100 KB) into the workspace\n wake [sandbox] | sleep [sandbox]\n key [sandbox] [--name <n>] create an OpenAI-compatible key for the sandbox's coding agent\n keys [sandbox] list those keys\n revoke-key [sandbox] <key-id>\n\n[sandbox] is the sandbox id, the start of it, or its name (or pass --sandbox <it>).\nLeave it out if you have only one.\n\nauth: SGL_API_KEY=x402c_... a compute API key from Settings > API keys. connect, exec, files\n and key need the Agent Pods permission \"Read and write pod\n files, install skills, create and restore backups\"\n (pods:control:write).\n --keypair <path> or sign with a Solana keypair (default ~/.config/solana/id.json)\n --compute-url <url> another API base (default https://compute.x402layer.cc)\n --json machine-readable output\n\nOpenAI-compatible address: after 'key', point any OpenAI client at the printed base URL with\nmodel \"agent-pod\". Each request is one turn of the sandbox's coding agent.";
20
+ export declare function computeBase(flags: Flags): string;
21
+ /**
22
+ * Auth headers for one compute request.
23
+ *
24
+ * A key is sent as X-API-Key. A keypair signs the compute message: prefix, version, chain, address,
25
+ * METHOD, path WITH its query string, sha256 of the exact body text, timestamp in ms, nonce. Any
26
+ * byte off gives a bare 401, so the body string signed here is the one sent.
27
+ */
28
+ export declare function computeAuthHeaders(creds: Creds, method: string, pathAndQuery: string, bodyText: string, now?: number, nonce?: string): Record<string, string>;
29
+ export declare class ApiError extends Error {
30
+ status: number;
31
+ code: string;
32
+ details: Record<string, unknown>;
33
+ constructor(status: number, message: string, code: string, details: Record<string, unknown>);
34
+ get retryAfter(): number;
35
+ }
36
+ /**
37
+ * The compute API answers errors in two shapes: `{ error: "text", code }` (dashboard routes) and
38
+ * `{ error: { code, message, details } }` (the /pods/v1 partner API). Both become one ApiError.
39
+ */
40
+ export declare function parseApiError(status: number, text: string): ApiError;
41
+ export interface Ctx {
42
+ base: string;
43
+ creds: Creds;
44
+ json: boolean;
45
+ }
46
+ export declare function call<T = any>(ctx: Ctx, method: string, path: string, body?: unknown): Promise<T>;
47
+ /** Say what to do about the common refusals instead of echoing a status code. */
48
+ export declare function explain(e: unknown): string;
49
+ export interface SandboxRow {
50
+ id: string;
51
+ name: string | null;
52
+ status: string;
53
+ model?: string | null;
54
+ ai_mode?: string;
55
+ }
56
+ export declare function listSandboxes(ctx: Ctx): Promise<SandboxRow[]>;
57
+ /** Pick one sandbox from an id, an id prefix or a name. Pure, so the ambiguity rules are tested. */
58
+ export declare function pickSandbox(rows: SandboxRow[], ref: string | undefined): {
59
+ id: string;
60
+ } | {
61
+ error: string;
62
+ };
63
+ /** A single-use terminal socket URL (60 s). Waits while the sandbox wakes. */
64
+ export declare function openTerminalUrl(ctx: Ctx, id: string): Promise<string>;
65
+ /**
66
+ * ssh-style escape: "~." at the start of a line disconnects, "~~" sends one "~". Anything else after a
67
+ * held "~" sends both. Pure and stateful per session, so it is tested without a socket.
68
+ */
69
+ export declare function makeEscapeFilter(): (chunk: Uint8Array) => {
70
+ send: Uint8Array;
71
+ disconnect: boolean;
72
+ };
73
+ export declare function closeMessage(code: number, reason: string): {
74
+ text: string;
75
+ exit: number;
76
+ };
77
+ /** Upload content must be text the file API can carry: valid UTF-8, no NUL bytes, under the cap. */
78
+ export declare function checkUpload(buf: Buffer): string | null;
79
+ export declare function run(words: string[], flags: Flags): Promise<void>;
80
+ /**
81
+ * Split an optional leading sandbox reference from a command's own arguments. `--sandbox <ref>`
82
+ * always wins. Otherwise the first word is the sandbox when there are more words than the command
83
+ * takes, or when it plainly is one (a full id, or a hex id prefix of 4+ characters that is not a
84
+ * path). With one sandbox on the account it can always be left out.
85
+ */
86
+ export declare function splitRef(args: string[], maxOwn: number, flagRef?: string): [string | undefined, string[]];
87
+ export declare function looksLikeRef(s: string): boolean;
package/dist/version.d.ts CHANGED
@@ -8,4 +8,4 @@
8
8
  *
9
9
  * Kept in sync with package.json by the release workflow, which is the only thing that bumps either.
10
10
  */
11
- export declare const VERSION = "0.4.0";
11
+ export declare const VERSION = "0.5.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@singularity-layer/cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Singularity developer CLI \u2014 deploy paid endpoints (Processors) on the Singularity Cloud Network",
5
5
  "type": "module",
6
6
  "bin": {