frutebox 0.0.1 → 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/CHANGELOG.md +69 -0
- package/README.md +174 -23
- package/account.d.ts +125 -0
- package/account.mjs +413 -0
- package/bin/frutebox.mjs +608 -0
- package/errors.mjs +100 -0
- package/index.d.ts +211 -30
- package/index.mjs +461 -63
- package/package.json +28 -2
- package/spec.mjs +42 -0
package/bin/frutebox.mjs
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* The `frutebox` command, shipped with the npm package.
|
|
4
|
+
*
|
|
5
|
+
* IT IS THE SAME CLI AS THE PYTHON PACKAGE'S, NOT A SECOND ONE. It reads and writes the SAME
|
|
6
|
+
* config directory (`$FRUTEBOX_CONFIG_DIR`, else `~/.config/frutebox`), the same mode-600
|
|
7
|
+
* `session` and `node-credential` files, and the same `node.pid`. So `frutebox login` from npm and
|
|
8
|
+
* `frutebox node status` from pip are one tool with two front doors, which is the whole point —
|
|
9
|
+
* two stores would drift, and this repo has paid for that before.
|
|
10
|
+
*
|
|
11
|
+
* ONE THING IT DEFERS, DELIBERATELY AND LOUDLY. The node agent is Python
|
|
12
|
+
* (`frutebox/provider.py`); Node cannot run it. So `node contribute` here does the server half —
|
|
13
|
+
* registers the machine, stores the credential mode 600 — and then prints the exact command to
|
|
14
|
+
* start the agent. It does not pretend to have started one.
|
|
15
|
+
*
|
|
16
|
+
* AUTHENTICATION IS A SESSION TOKEN, NOT AN API KEY. The node endpoints authenticate with the
|
|
17
|
+
* account session (cookie, or the same JWT as `Authorization: Bearer` for native clients, which is
|
|
18
|
+
* how the desktop app calls them). An `sk_live_…` key gets a 401 there.
|
|
19
|
+
*
|
|
20
|
+
* SECRETS NEVER TOUCH ARGV: `login` reads stdin, and the credential is passed to the agent by file.
|
|
21
|
+
*/
|
|
22
|
+
import { createRequire } from "node:module";
|
|
23
|
+
import { readFileSync, writeFileSync, mkdirSync, chmodSync, statSync, unlinkSync, openSync, closeSync, writeSync } from "node:fs";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
27
|
+
|
|
28
|
+
const require_ = createRequire(import.meta.url);
|
|
29
|
+
const { version } = require_("../package.json");
|
|
30
|
+
|
|
31
|
+
const SESSION_ENV = "FRUTEBOX_SESSION_TOKEN";
|
|
32
|
+
const CONFIG_DIR_ENV = "FRUTEBOX_CONFIG_DIR";
|
|
33
|
+
const BASE_URL_ENV = "FRUTEBOX_BASE_URL";
|
|
34
|
+
const DEFAULT_BASE_URL = "https://frutebox.com";
|
|
35
|
+
|
|
36
|
+
function configDir() {
|
|
37
|
+
const dir = process.env[CONFIG_DIR_ENV] || join(homedir(), ".config", "frutebox");
|
|
38
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
39
|
+
try { chmodSync(dir, 0o700); } catch { /* an existing dir keeps its mode; tighten, do not trust */ }
|
|
40
|
+
return dir;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Mode is on the `open` call: writing first and chmod-ing after leaves a readable gap. */
|
|
44
|
+
function writeSecret(name, value) {
|
|
45
|
+
const path = join(configDir(), name);
|
|
46
|
+
const fd = openSync(path, "w", 0o600);
|
|
47
|
+
try { writeSync(fd, value); } finally { closeSync(fd); }
|
|
48
|
+
chmodSync(path, 0o600);
|
|
49
|
+
return path;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function readSecret(name) {
|
|
53
|
+
try { return readFileSync(join(configDir(), name), "utf8").trim() || null; } catch { return null; }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const baseUrl = () => (process.env[BASE_URL_ENV] || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
57
|
+
const sessionToken = () => process.env[SESSION_ENV] || readSecret("session");
|
|
58
|
+
/** For logs. Presence and length, never content. */
|
|
59
|
+
const mask = (v) => (v ? `present (${v.length} chars)` : "ABSENT");
|
|
60
|
+
|
|
61
|
+
function requireToken() {
|
|
62
|
+
const token = sessionToken();
|
|
63
|
+
if (!token) {
|
|
64
|
+
process.stderr.write(
|
|
65
|
+
"frutebox: no session token.\n"
|
|
66
|
+
+ ` Set $${SESSION_ENV}, or run \`frutebox login\` to store one.\n`
|
|
67
|
+
+ " NOTE: the node commands need a SESSION token, not an sk_live_ API key — the node\n"
|
|
68
|
+
+ " endpoints authenticate the account, and an API key gets a 401 there.\n",
|
|
69
|
+
);
|
|
70
|
+
process.exit(1);
|
|
71
|
+
}
|
|
72
|
+
return token;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function api(method, path, token, body) {
|
|
76
|
+
const url = `${baseUrl()}${path}`;
|
|
77
|
+
const headers = { authorization: `Bearer ${token}`, accept: "application/json" };
|
|
78
|
+
if (body !== undefined) headers["content-type"] = "application/json";
|
|
79
|
+
let res;
|
|
80
|
+
try {
|
|
81
|
+
res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
82
|
+
} catch (err) {
|
|
83
|
+
// Only the NAME: a fetch failure can carry the request, and the request carries the header.
|
|
84
|
+
process.stderr.write(`frutebox: cannot reach ${baseUrl()} (${err?.name ?? "network error"}).\n`);
|
|
85
|
+
process.exit(1);
|
|
86
|
+
}
|
|
87
|
+
let parsed;
|
|
88
|
+
try { parsed = await res.json(); } catch {
|
|
89
|
+
// Not JSON. Reading a CDN's HTML error page as `{}` is how "not deployed" becomes "worked".
|
|
90
|
+
parsed = { _raw: "(non-JSON response)" };
|
|
91
|
+
}
|
|
92
|
+
return { status: res.status, body: parsed };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function failOnError(status, body, what) {
|
|
96
|
+
if (status >= 200 && status < 300) return body;
|
|
97
|
+
if (status === 401) {
|
|
98
|
+
process.stderr.write(`frutebox: ${what} was refused (401). The session token is missing, expired or revoked.\n`);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
}
|
|
101
|
+
const err = body?.error;
|
|
102
|
+
const message = typeof err === "string" ? err : err?.message;
|
|
103
|
+
process.stderr.write(`frutebox: ${what} failed (${status}): ${message ?? JSON.stringify(body)}\n`);
|
|
104
|
+
process.exit(1);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// --- limits: when this machine will and will not take work ----------------------------------
|
|
108
|
+
const LIMITS_FILE = "limits.json";
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* What the HEADLESS agent actually enforces, with the provider flag each becomes.
|
|
112
|
+
* `maxConcurrentJobs` is spelled as the desktop app spells it (`NodeLimits.maxConcurrentJobs`), so
|
|
113
|
+
* the front doors share one vocabulary. Same table as the Python CLI's `AGENT_LIMITS`.
|
|
114
|
+
*/
|
|
115
|
+
const AGENT_LIMITS = { maxConcurrentJobs: "--concurrency", jobTimeoutSeconds: "--job-timeout-s" };
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Limits the DESKTOP app offers that the headless agent cannot honour. Its `NodeLimits` docstring
|
|
119
|
+
* says every field is "enforced in the main process (see nodeGovernor.ts)" — that governor is part
|
|
120
|
+
* of the Electron app. `frutebox/provider.py` has no battery, thermal, quiet-hours or in-use
|
|
121
|
+
* detection. So these are NAMED AND REFUSED rather than stored: writing them to a file nothing
|
|
122
|
+
* reads would let an operator believe a server will stop for a battery it does not have.
|
|
123
|
+
*/
|
|
124
|
+
const DESKTOP_ONLY_LIMITS = [
|
|
125
|
+
"maxThreads", "minFreeRamGb", "keepModelsLoaded", "pauseOnBattery",
|
|
126
|
+
"pauseWhenInUse", "idleSeconds", "quietHours", "pauseWhenHot", "minBatteryPercent",
|
|
127
|
+
];
|
|
128
|
+
|
|
129
|
+
function readLimits() {
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(readFileSync(join(configDir(), LIMITS_FILE), "utf8"));
|
|
132
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
133
|
+
} catch {
|
|
134
|
+
// Unreadable or malformed reads as "nothing stored" ONLY because the agent's own defaults are
|
|
135
|
+
// the safe ones; nothing here grants permission to take more work.
|
|
136
|
+
return {};
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function writeLimits(limits) {
|
|
141
|
+
const path = join(configDir(), LIMITS_FILE);
|
|
142
|
+
writeFileSync(path, `${JSON.stringify(limits, Object.keys(limits).sort(), 2)}\n`);
|
|
143
|
+
return path;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// --- the shared pidfile, written by whichever front door started the agent -------------------
|
|
147
|
+
const PIDFILE = "node.pid";
|
|
148
|
+
function readPid() {
|
|
149
|
+
const raw = readSecret(PIDFILE);
|
|
150
|
+
const n = raw ? Number(raw) : NaN;
|
|
151
|
+
return Number.isInteger(n) ? n : null;
|
|
152
|
+
}
|
|
153
|
+
function pidAlive(pid) {
|
|
154
|
+
try { process.kill(pid, 0); return true; }
|
|
155
|
+
catch (err) { return err.code === "EPERM"; } // EPERM: exists, someone else's. Not "gone".
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// --- commands --------------------------------------------------------------------------------
|
|
159
|
+
async function cmdLogin() {
|
|
160
|
+
if (process.stdin.isTTY) {
|
|
161
|
+
process.stderr.write(
|
|
162
|
+
"frutebox login reads the session token from stdin, so it never appears in argv or\n"
|
|
163
|
+
+ "shell history. Pipe it in:\n"
|
|
164
|
+
+ " pbpaste | frutebox login # macOS\n"
|
|
165
|
+
+ " frutebox login < token.txt\n",
|
|
166
|
+
);
|
|
167
|
+
return 2;
|
|
168
|
+
}
|
|
169
|
+
const chunks = [];
|
|
170
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
171
|
+
const token = Buffer.concat(chunks).toString("utf8").trim();
|
|
172
|
+
if (!token) { process.stderr.write("frutebox: nothing on stdin.\n"); return 2; }
|
|
173
|
+
|
|
174
|
+
const { status, body } = await api("GET", "/api/me", token);
|
|
175
|
+
if (status === 401) { process.stderr.write("frutebox: that token was refused (401). Nothing stored.\n"); return 1; }
|
|
176
|
+
failOnError(status, body, "checking the token");
|
|
177
|
+
|
|
178
|
+
const path = writeSecret("session", token);
|
|
179
|
+
console.log(`Stored a session token at ${path} (mode 600).`);
|
|
180
|
+
if (body?.email) console.log(`Signed in as ${body.email}.`);
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function cmdLogout() {
|
|
185
|
+
const path = join(configDir(), "session");
|
|
186
|
+
try {
|
|
187
|
+
const size = statSync(path).size;
|
|
188
|
+
// Overwritten before unlinking: a plain remove leaves the bytes on disk.
|
|
189
|
+
writeFileSync(path, "\0".repeat(size));
|
|
190
|
+
unlinkSync(path);
|
|
191
|
+
console.log("Session token removed.");
|
|
192
|
+
} catch { console.log("No stored session token."); }
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async function cmdNodeContribute(flags) {
|
|
197
|
+
const token = requireToken();
|
|
198
|
+
const pid = readPid();
|
|
199
|
+
if (pid && pidAlive(pid)) {
|
|
200
|
+
console.log(`This machine is already contributing (node agent pid ${pid}).`);
|
|
201
|
+
console.log("Run `frutebox node pause` to stop it first.");
|
|
202
|
+
return 0;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const body = { agentKind: "stevai-node" };
|
|
206
|
+
for (const [flag, key] of [["--region", "region"], ["--name", "name"], ["--compute-type", "computeType"]]) {
|
|
207
|
+
if (flags[flag]) body[key] = flags[flag];
|
|
208
|
+
}
|
|
209
|
+
for (const [flag, key] of [["--cpu-cores", "cpuCores"], ["--ram-gb", "ramGb"]]) {
|
|
210
|
+
if (flags[flag]) body[key] = Number(flags[flag]);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const { status, body: reply } = await api("POST", "/api/nodes/self", token, body);
|
|
214
|
+
failOnError(status, reply, "registering this machine");
|
|
215
|
+
if (!reply?.nodeId) {
|
|
216
|
+
process.stderr.write(`frutebox: the server accepted the request but returned no nodeId.\n`);
|
|
217
|
+
return 1;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const { nodeId, region = "", gatewayWs = "", credential } = reply;
|
|
221
|
+
console.log(`Registered: node ${nodeId}${region ? ` in ${region}` : ""}`);
|
|
222
|
+
console.log(` gateway: ${gatewayWs || "(none returned)"}`);
|
|
223
|
+
console.log(` credential: ${mask(credential)}`);
|
|
224
|
+
let credFile = null;
|
|
225
|
+
if (credential) {
|
|
226
|
+
credFile = writeSecret("node-credential", credential);
|
|
227
|
+
console.log(` stored at: ${credFile} (mode 600)`);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// THE AGENT IS PYTHON. Node cannot run it, so the command is printed rather than faked.
|
|
231
|
+
console.log("");
|
|
232
|
+
console.log("THE MACHINE IS REGISTERED. The node agent itself is Python, so start it with:");
|
|
233
|
+
console.log(` python -m frutebox.provider --id ${nodeId} --region ${region || "<region>"} \\`);
|
|
234
|
+
console.log(` --gateway-url ${gatewayWs || "<ws url>"} \\`);
|
|
235
|
+
if (credFile) console.log(` --credential-file ${credFile} \\`);
|
|
236
|
+
// The stored limits, so the printed command is the one that honours them.
|
|
237
|
+
const stored = readLimits();
|
|
238
|
+
for (const [key, flag] of Object.entries(AGENT_LIMITS)) {
|
|
239
|
+
if (stored[key] !== undefined) console.log(` ${flag} ${stored[key]} \\`);
|
|
240
|
+
}
|
|
241
|
+
console.log("");
|
|
242
|
+
console.log(" (--credential-file, never --credential: argv is visible to every user on the box.)");
|
|
243
|
+
console.log(" `pip install frutebox` gives you `frutebox node contribute`, which starts it for you.");
|
|
244
|
+
return 3;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async function cmdNodeStatus() {
|
|
248
|
+
const token = requireToken();
|
|
249
|
+
const pid = readPid();
|
|
250
|
+
if (pid && pidAlive(pid)) console.log(`Local node agent: RUNNING (pid ${pid})`);
|
|
251
|
+
else if (pid) console.log(`Local node agent: NOT running (stale pid ${pid})`);
|
|
252
|
+
else console.log("Local node agent: not started from this machine's CLI");
|
|
253
|
+
|
|
254
|
+
const nodes = await api("GET", "/api/nodes", token);
|
|
255
|
+
failOnError(nodes.status, nodes.body, "listing nodes");
|
|
256
|
+
const rows = Array.isArray(nodes.body) ? nodes.body : nodes.body?.nodes;
|
|
257
|
+
if (Array.isArray(rows) && rows.length) {
|
|
258
|
+
console.log(`\nNodes on this account (${rows.length}):`);
|
|
259
|
+
for (const n of rows) {
|
|
260
|
+
const bits = [String(n?.id ?? "?")];
|
|
261
|
+
for (const f of ["name", "region", "status", "computeType"]) if (n?.[f]) bits.push(`${f}=${n[f]}`);
|
|
262
|
+
console.log(" " + bits.join(" "));
|
|
263
|
+
}
|
|
264
|
+
} else {
|
|
265
|
+
console.log("\nNo nodes registered on this account.");
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
const earn = await api("GET", "/api/nodes/earnings", token);
|
|
269
|
+
if (earn.status >= 200 && earn.status < 300 && earn.body && typeof earn.body === "object") {
|
|
270
|
+
console.log("\nEarnings:");
|
|
271
|
+
for (const k of ["total", "totalEur", "pending", "paid", "currency"]) {
|
|
272
|
+
if (k in earn.body) console.log(` ${k}: ${earn.body[k]}`);
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
// Not fatal, and NOT reported as zero: claiming zero earnings would be a lie.
|
|
276
|
+
console.log(`\nEarnings: unavailable (HTTP ${earn.status}) — not reported as zero.`);
|
|
277
|
+
}
|
|
278
|
+
return 0;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function cmdNodePause() {
|
|
282
|
+
const pid = readPid();
|
|
283
|
+
if (!pid) { console.log("No node agent was started from this CLI, so there is nothing to pause."); return 0; }
|
|
284
|
+
if (!pidAlive(pid)) {
|
|
285
|
+
console.log(`Node agent (pid ${pid}) is not running. Clearing the stale pidfile.`);
|
|
286
|
+
try { unlinkSync(join(configDir(), PIDFILE)); } catch { /* already gone */ }
|
|
287
|
+
return 0;
|
|
288
|
+
}
|
|
289
|
+
process.kill(pid, "SIGTERM");
|
|
290
|
+
// Asked, then verified: "the command returned success" and "the thing stopped" differ.
|
|
291
|
+
const deadline = Date.now() + 5000;
|
|
292
|
+
while (Date.now() < deadline && pidAlive(pid)) await sleep(100);
|
|
293
|
+
if (pidAlive(pid)) {
|
|
294
|
+
console.log(`Node agent (pid ${pid}) did not stop within 5s. It was asked to; it is still running.`);
|
|
295
|
+
return 1;
|
|
296
|
+
}
|
|
297
|
+
try { unlinkSync(join(configDir(), PIDFILE)); } catch { /* already gone */ }
|
|
298
|
+
console.log(`Node agent (pid ${pid}) stopped. This machine is no longer taking work.`);
|
|
299
|
+
return 0;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function cmdLimits(flags) {
|
|
303
|
+
const stored = readLimits();
|
|
304
|
+
const changed = {};
|
|
305
|
+
if (flags["--max-concurrent-jobs"] !== undefined) {
|
|
306
|
+
const n = Number(flags["--max-concurrent-jobs"]);
|
|
307
|
+
if (!Number.isFinite(n) || n < 0) { process.stderr.write("frutebox: --max-concurrent-jobs must be a non-negative number.\n"); return 1; }
|
|
308
|
+
changed.maxConcurrentJobs = Math.trunc(n);
|
|
309
|
+
}
|
|
310
|
+
if (flags["--job-timeout-seconds"] !== undefined) {
|
|
311
|
+
const n = Number(flags["--job-timeout-seconds"]);
|
|
312
|
+
if (!Number.isFinite(n) || n < 0) { process.stderr.write("frutebox: --job-timeout-seconds must be a non-negative number.\n"); return 1; }
|
|
313
|
+
changed.jobTimeoutSeconds = n;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (Object.keys(changed).length) {
|
|
317
|
+
const path = writeLimits({ ...stored, ...changed });
|
|
318
|
+
console.log(`Updated ${path}:`);
|
|
319
|
+
for (const k of Object.keys(changed).sort()) console.log(` ${k} = ${changed[k]}`);
|
|
320
|
+
const pid = readPid();
|
|
321
|
+
if (pid && pidAlive(pid)) {
|
|
322
|
+
// Said plainly rather than implied: the agent read its flags at start-up.
|
|
323
|
+
console.log("");
|
|
324
|
+
console.log(" The node agent is RUNNING and already took its limits at start-up.");
|
|
325
|
+
console.log(" `frutebox share --leave` then `--join` to apply these.");
|
|
326
|
+
}
|
|
327
|
+
return 0;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
console.log("Limits this machine takes work under");
|
|
331
|
+
console.log("");
|
|
332
|
+
console.log(" Enforced by the node agent:");
|
|
333
|
+
for (const k of Object.keys(AGENT_LIMITS).sort()) {
|
|
334
|
+
const v = stored[k];
|
|
335
|
+
console.log(` ${k.padEnd(22)} ${v === undefined ? "(the agent's own default)" : v}`);
|
|
336
|
+
}
|
|
337
|
+
console.log("");
|
|
338
|
+
console.log(" Set with: frutebox share --limits --max-concurrent-jobs 2 --job-timeout-seconds 900");
|
|
339
|
+
console.log("");
|
|
340
|
+
console.log(" NOT settable here — the desktop app enforces these in its own governor, and the");
|
|
341
|
+
console.log(" headless agent has no battery, thermal, quiet-hours or in-use detection:");
|
|
342
|
+
console.log(` ${DESKTOP_ONLY_LIMITS.join(", ")}`);
|
|
343
|
+
console.log("");
|
|
344
|
+
console.log(" Set those in the desktop app's Infra pane, on a machine running it.");
|
|
345
|
+
return 0;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// --- agents: Standby Agents, wired the day the spec published them -------------------------
|
|
349
|
+
//
|
|
350
|
+
// THIS COMMAND USED TO REFUSE with exit 69, because the endpoints did not exist and writing it
|
|
351
|
+
// would have meant inventing their shapes. The spec published nine `/standby/runs` paths on
|
|
352
|
+
// 2026-10-15, so it is built against the document.
|
|
353
|
+
//: The actions `frutebox agents` accepts. ONE list, read by the help and the fall-through
|
|
354
|
+
//: message, because the Python CLI shipped `results` in its parser with no handler behind it.
|
|
355
|
+
const AGENTS_ACTIONS = ["create", "list", "show", "logs", "results", "stop", "pause", "resume", "answer"];
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* The step-up code, from the environment or stdin — NEVER from argv.
|
|
359
|
+
*
|
|
360
|
+
* `ps` shows argv to every user on the machine, and a non-zero exit serialises the whole command
|
|
361
|
+
* line into the error. A TOTP is single-use and expires in seconds, and it is live during
|
|
362
|
+
* exactly the window in which it is worth stealing.
|
|
363
|
+
*
|
|
364
|
+
* Returns undefined when none was supplied: this client does not guess which steps are effects,
|
|
365
|
+
* so it sends what it has and lets the server refuse.
|
|
366
|
+
*/
|
|
367
|
+
async function readTotp(flags) {
|
|
368
|
+
const env = (process.env.FRUTEBOX_TOTP ?? "").trim();
|
|
369
|
+
if (env) return env;
|
|
370
|
+
if (!flags["--totp-stdin"]) return undefined;
|
|
371
|
+
if (process.stdin.isTTY) {
|
|
372
|
+
process.stderr.write(
|
|
373
|
+
"frutebox agents: --totp-stdin reads the code from stdin so it never reaches argv.\n" +
|
|
374
|
+
" echo 123456 | frutebox agents answer ... --totp-stdin\n" +
|
|
375
|
+
" Or set FRUTEBOX_TOTP in the environment.\n");
|
|
376
|
+
process.exit(2);
|
|
377
|
+
}
|
|
378
|
+
const chunks = [];
|
|
379
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
380
|
+
const code = Buffer.concat(chunks).toString("utf8").trim();
|
|
381
|
+
if (!code) { process.stderr.write("frutebox agents: nothing on stdin for the step-up code.\n"); process.exit(2); }
|
|
382
|
+
return code;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function cmdAgents(positional, flags) {
|
|
386
|
+
const token = requireToken();
|
|
387
|
+
const { FruteboxAccount } = await import("../account.mjs");
|
|
388
|
+
const me = new FruteboxAccount({ sessionToken: token, baseUrl: baseUrl() });
|
|
389
|
+
const action = positional[1];
|
|
390
|
+
const runId = positional[2];
|
|
391
|
+
|
|
392
|
+
const parseStep = (raw) => {
|
|
393
|
+
const i = String(raw).indexOf(":"); // FIRST colon only; a detail may contain one
|
|
394
|
+
const kind = i < 0 ? "" : raw.slice(0, i).trim().toLowerCase();
|
|
395
|
+
const detail = i < 0 ? "" : raw.slice(i + 1).trim();
|
|
396
|
+
if (!kind || !detail) {
|
|
397
|
+
process.stderr.write(`frutebox agents: --step wants KIND:DETAIL, got ${JSON.stringify(raw)}.\n`);
|
|
398
|
+
process.exit(2);
|
|
399
|
+
}
|
|
400
|
+
return { kind, detail };
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
try {
|
|
404
|
+
switch (action) {
|
|
405
|
+
case "create": {
|
|
406
|
+
const raw = flags["--step"];
|
|
407
|
+
const steps = (Array.isArray(raw) ? raw : raw ? [raw] : []).map(parseStep);
|
|
408
|
+
if (!flags["--goal"]) { process.stderr.write("frutebox agents create: --goal is required.\n"); return 2; }
|
|
409
|
+
if (!steps.length) { process.stderr.write("frutebox agents create: at least one --step is required.\n"); return 2; }
|
|
410
|
+
const run = await me.standby.create({
|
|
411
|
+
goal: flags["--goal"], steps,
|
|
412
|
+
workspace: flags["--workspace"],
|
|
413
|
+
replicas: flags["--replicas"] ? Number(flags["--replicas"]) : undefined,
|
|
414
|
+
stepBudget: flags["--step-budget"] ? Number(flags["--step-budget"]) : undefined,
|
|
415
|
+
});
|
|
416
|
+
console.log(`Queued run ${run.id}`);
|
|
417
|
+
console.log(` started: ${run.started} held: ${run.held}`);
|
|
418
|
+
if (run.held) console.log(" A held step is waiting on you — `frutebox agents logs <id>`.");
|
|
419
|
+
return 0;
|
|
420
|
+
}
|
|
421
|
+
case "list": {
|
|
422
|
+
const out = await me.standby.list(flags["--limit"] ? { limit: Number(flags["--limit"]) } : {});
|
|
423
|
+
const runs = out?.runs ?? [];
|
|
424
|
+
if (!runs.length) { console.log("No standby runs on this account."); return 0; }
|
|
425
|
+
console.log(`${runs.length} run(s), newest first:`);
|
|
426
|
+
for (const r of runs) console.log(` ${String(r.id ?? "?").padEnd(24)} ${String(r.state ?? "?").padEnd(12)} ${String(r.goal ?? "").slice(0, 48)}`);
|
|
427
|
+
return 0;
|
|
428
|
+
}
|
|
429
|
+
case "logs": {
|
|
430
|
+
if (!runId) { process.stderr.write("frutebox agents logs: a run id is required.\n"); return 2; }
|
|
431
|
+
const out = await me.standby.logs(runId);
|
|
432
|
+
console.log(`run ${out.id} state=${out.state}`);
|
|
433
|
+
const trail = out.trail ?? [];
|
|
434
|
+
if (!trail.length) console.log(" (no steps have run yet)");
|
|
435
|
+
for (const e of trail) console.log(` ${String(e.kind ?? "?").padEnd(8)} ${String(e.state ?? "?").padEnd(10)} ${String(e.detail ?? "").slice(0, 56)}`);
|
|
436
|
+
return 0;
|
|
437
|
+
}
|
|
438
|
+
case "results": {
|
|
439
|
+
if (!runId) { process.stderr.write("frutebox agents results: a run id is required.\n"); return 2; }
|
|
440
|
+
const out = await me.standby.results(runId);
|
|
441
|
+
// 31-C6, delivery on return: this is what the user came back FOR.
|
|
442
|
+
console.log(`run ${out.id ?? runId} state=${out.state}`);
|
|
443
|
+
if (out.error) console.log(` error: ${out.error}`);
|
|
444
|
+
console.log(" result:");
|
|
445
|
+
console.log(" " + (out.result ? String(out.result).split("\n").join("\n ")
|
|
446
|
+
: "(nothing yet — the run has not produced one)"));
|
|
447
|
+
const done = out.steps ?? [];
|
|
448
|
+
if (done.length) {
|
|
449
|
+
console.log(` ${done.length} completed step(s):`);
|
|
450
|
+
for (const st of done) console.log(` ${st.seq}. ${String(st.kind ?? "?").padEnd(8)} ${String(st.result ?? "").slice(0, 56)}`);
|
|
451
|
+
}
|
|
452
|
+
const held = out.held ?? [];
|
|
453
|
+
for (const h of held) console.log(` HELD step ${h.stepId} (${h.kind}): ${String(h.detail ?? "").slice(0, 56)}`);
|
|
454
|
+
if (held.length) console.log(" Answer with `frutebox agents answer <id> --step-id <id> --decision approve|deny`.");
|
|
455
|
+
return 0;
|
|
456
|
+
}
|
|
457
|
+
case "show": {
|
|
458
|
+
if (!runId) { process.stderr.write("frutebox agents show: a run id is required.\n"); return 2; }
|
|
459
|
+
const out = await me.standby.retrieve(runId);
|
|
460
|
+
console.log(`run ${out.id} state=${out.state}`);
|
|
461
|
+
for (const [label, key] of [["goal", "goal"], ["workspace", "workspace"], ["region", "region"],
|
|
462
|
+
["replicas", "replicas"], ["step budget", "stepBudget"],
|
|
463
|
+
["steps used", "stepsUsed"], ["created", "createdAt"],
|
|
464
|
+
["finished", "finishedAt"]]) {
|
|
465
|
+
const val = out[key];
|
|
466
|
+
// Printed only when the server sent it: a blank line for a field it does not populate
|
|
467
|
+
// reads as "empty", which is a different claim from "not reported".
|
|
468
|
+
if (val !== undefined && val !== null && val !== "") console.log(` ${(label + ":").padEnd(14)}${val}`);
|
|
469
|
+
}
|
|
470
|
+
console.log(` ${(out.trail ?? []).length} trail entr(ies), ${(out.held ?? []).length} held step(s)`);
|
|
471
|
+
return 0;
|
|
472
|
+
}
|
|
473
|
+
case "stop":
|
|
474
|
+
if (!runId) { process.stderr.write("frutebox agents stop: a run id is required.\n"); return 2; }
|
|
475
|
+
await me.standby.stop(runId);
|
|
476
|
+
console.log(`Run ${runId} cancelled. Mirrors in flight were cancelled too.`);
|
|
477
|
+
console.log(" `frutebox agents pause <id>` stops NEW steps without cancelling them.");
|
|
478
|
+
return 0;
|
|
479
|
+
case "pause":
|
|
480
|
+
await me.standby.pause(runId);
|
|
481
|
+
console.log(`Run ${runId} paused. Mirrors already in flight keep going.`);
|
|
482
|
+
return 0;
|
|
483
|
+
case "resume":
|
|
484
|
+
await me.standby.resume(runId);
|
|
485
|
+
console.log(`Run ${runId} resumed.`);
|
|
486
|
+
return 0;
|
|
487
|
+
case "answer":
|
|
488
|
+
await me.standby.answerStep(runId, flags["--step-id"], {
|
|
489
|
+
decision: flags["--decision"], totp: await readTotp(flags),
|
|
490
|
+
});
|
|
491
|
+
console.log(`Step ${flags["--step-id"]} ${flags["--decision"]}d.`);
|
|
492
|
+
return 0;
|
|
493
|
+
default:
|
|
494
|
+
process.stderr.write(`frutebox agents: expected one of ${AGENTS_ACTIONS.join(", ")}.\n`);
|
|
495
|
+
return 2;
|
|
496
|
+
}
|
|
497
|
+
} catch (err) {
|
|
498
|
+
process.stderr.write(`frutebox agents: ${err.message}\n`);
|
|
499
|
+
return 1;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const HELP = `frutebox ${version} — share this machine with the Frutebox network, and manage it.
|
|
504
|
+
|
|
505
|
+
frutebox login Store a session token (read from STDIN, never argv)
|
|
506
|
+
frutebox logout Remove the stored session token
|
|
507
|
+
|
|
508
|
+
frutebox share --join Register this machine and store its credential
|
|
509
|
+
[--region R] [--name N] [--compute-type gpu|cpu] [--cpu-cores N] [--ram-gb N]
|
|
510
|
+
frutebox share --status Node state and earnings
|
|
511
|
+
frutebox share --limits When this machine will and will not take work
|
|
512
|
+
[--max-concurrent-jobs N] [--job-timeout-seconds S]
|
|
513
|
+
frutebox share --leave Stop taking work (keeps the node and its earnings)
|
|
514
|
+
|
|
515
|
+
frutebox node contribute Alias for \`share --join\`
|
|
516
|
+
frutebox node status Alias for \`share --status\`
|
|
517
|
+
frutebox node pause Alias for \`share --leave\`
|
|
518
|
+
|
|
519
|
+
frutebox agents create Queue work that continues while your device is off
|
|
520
|
+
--goal TEXT --step KIND:DETAIL [--replicas N] [--workspace W] [--step-budget N]
|
|
521
|
+
frutebox agents list Your standby runs, newest first
|
|
522
|
+
frutebox agents logs <id> The step trail
|
|
523
|
+
frutebox agents stop <id> Cancel (also cancels mirrors in flight)
|
|
524
|
+
frutebox agents pause <id> Stop posting NEW steps; mirrors in flight keep going
|
|
525
|
+
frutebox agents results <id> The answer, the completed steps and anything held (31-C6)
|
|
526
|
+
frutebox agents show <id> The run itself: goal, region, replicas, budget, counts
|
|
527
|
+
frutebox agents answer <id> --step-id S --decision approve|deny [--totp-stdin]
|
|
528
|
+
The step-up code comes from FRUTEBOX_TOTP or stdin, never argv
|
|
529
|
+
|
|
530
|
+
The node commands need a SESSION token (not an sk_live_ API key): they authenticate the account,
|
|
531
|
+
the same way the desktop app does. Config lives in $FRUTEBOX_CONFIG_DIR or ~/.config/frutebox,
|
|
532
|
+
mode 700, with secrets mode 600 — shared with the Python package's identical CLI.
|
|
533
|
+
`;
|
|
534
|
+
|
|
535
|
+
async function main(argv) {
|
|
536
|
+
const positional = argv.filter((a) => !a.startsWith("-"));
|
|
537
|
+
const flags = {};
|
|
538
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
539
|
+
if (!argv[i].startsWith("--")) continue;
|
|
540
|
+
const value = argv[i + 1] && !argv[i + 1].startsWith("-") ? argv[i + 1] : true;
|
|
541
|
+
// REPEATED FLAGS ACCUMULATE. `--step` is given once per step, and overwriting would silently
|
|
542
|
+
// queue a run with only the last one — the caller would get a different run from the one they
|
|
543
|
+
// asked for, with no error. Repeats become an array; a single use stays a scalar.
|
|
544
|
+
if (Object.prototype.hasOwnProperty.call(flags, argv[i])) {
|
|
545
|
+
flags[argv[i]] = [].concat(flags[argv[i]], value);
|
|
546
|
+
} else {
|
|
547
|
+
flags[argv[i]] = value;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const [cmd, sub] = positional;
|
|
552
|
+
if (flags["--version"]) { console.log(`frutebox ${version}`); return 0; }
|
|
553
|
+
if (!cmd || cmd === "help" || flags["--help"] || flags["-h"]) { process.stdout.write(HELP); return cmd ? 0 : 2; }
|
|
554
|
+
|
|
555
|
+
switch (cmd) {
|
|
556
|
+
case "login": return cmdLogin();
|
|
557
|
+
case "logout": return cmdLogout();
|
|
558
|
+
case "agents": return cmdAgents(positional, flags);
|
|
559
|
+
|
|
560
|
+
// `share` is the CANONICAL spelling — implementation_plan/31-standby-agents.md §C5 assigns
|
|
561
|
+
// this lane exactly these four, and "share a machine" is the desktop pane's own vocabulary.
|
|
562
|
+
case "share": {
|
|
563
|
+
const chosen = ["join", "status", "limits", "leave"].filter((a) => flags[`--${a}`]);
|
|
564
|
+
if (chosen.length > 1) {
|
|
565
|
+
process.stderr.write(`frutebox share: pick one of --join, --status, --limits, --leave (got ${chosen.length}).\n`);
|
|
566
|
+
return 1;
|
|
567
|
+
}
|
|
568
|
+
if (chosen.length === 0) {
|
|
569
|
+
process.stderr.write(
|
|
570
|
+
"frutebox share: say what to do.\n"
|
|
571
|
+
+ " --join register this machine and start the node agent\n"
|
|
572
|
+
+ " --status state and earnings\n"
|
|
573
|
+
+ " --limits when this machine will and will not take work\n"
|
|
574
|
+
+ " --leave stop taking work (keeps the node and its earnings)\n",
|
|
575
|
+
);
|
|
576
|
+
return 1;
|
|
577
|
+
}
|
|
578
|
+
switch (chosen[0]) {
|
|
579
|
+
case "join": return cmdNodeContribute(flags);
|
|
580
|
+
case "status": return cmdNodeStatus();
|
|
581
|
+
case "limits": return cmdLimits(flags);
|
|
582
|
+
case "leave": return cmdNodePause();
|
|
583
|
+
}
|
|
584
|
+
return 2;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// `node ...` is an ALIAS, kept because it is what this CLI shipped first.
|
|
588
|
+
case "node":
|
|
589
|
+
switch (sub) {
|
|
590
|
+
case "contribute": return cmdNodeContribute(flags);
|
|
591
|
+
case "status": return cmdNodeStatus();
|
|
592
|
+
case "pause": return cmdNodePause();
|
|
593
|
+
default:
|
|
594
|
+
process.stderr.write(
|
|
595
|
+
"frutebox node: expected `contribute`, `status` or `pause`.\n"
|
|
596
|
+
+ " These are aliases for `frutebox share --join|--status|--leave`.\n"
|
|
597
|
+
+ " `--limits` has no `node` spelling; it was never shipped under one.\n",
|
|
598
|
+
);
|
|
599
|
+
return 2;
|
|
600
|
+
}
|
|
601
|
+
default:
|
|
602
|
+
process.stderr.write(`frutebox: unknown command '${cmd}'.\n`);
|
|
603
|
+
process.stdout.write(HELP);
|
|
604
|
+
return 2;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
process.exitCode = await main(process.argv.slice(2));
|