smartypants-network 0.1.1 → 0.1.2

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
@@ -55,6 +55,16 @@ Every command takes `--json` for machine-readable output, plus `--api-key` and `
55
55
  Exit codes: 0 ok, 1 the site refused or failed, 2 bad usage, otherwise the program's own exit code.
56
56
  `smartypants help` lists every command.
57
57
 
58
+ ## Agent skills
59
+
60
+ ```sh
61
+ smartypants skills # the shelf: skills we checked and pinned to one commit
62
+ smartypants skills add grilling # installs into ~/.claude/skills and ~/.agents/skills
63
+ smartypants skills add --all --project # or into this project's .claude/skills and .agents/skills
64
+ ```
65
+
66
+ No key needed. Our own `smartypants` skill is always on the shelf.
67
+
58
68
  ## As a library
59
69
 
60
70
  The package also carries the one-file JavaScript kit:
@@ -7,7 +7,7 @@ import { dirname, join, basename } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { execFileSync } from "node:child_process";
9
9
 
10
- export const VERSION = "0.1.1";
10
+ export const VERSION = "0.1.2";
11
11
  const here = dirname(fileURLToPath(import.meta.url));
12
12
 
13
13
  /** The kit sits next to this file when both are downloaded from /kits/, inside the package (copied at
@@ -48,6 +48,10 @@ Computers (our own account first, for now)
48
48
  else the failed step's code. --retries N saves after
49
49
  each step; if the Mac is lost, a copy goes on from
50
50
  the cut-off step, on another Mac when there is one.
51
+ With --repo on GitHub and --task, it opens a DRAFT pull
52
+ request with the task's changes when the work is done,
53
+ using GITHUB_TOKEN or GH_TOKEN (it stays on our site,
54
+ never in the workspace). --no-pr turns that off.
51
55
  smartypants job ... --every MIN --name NAME Run the job again every MIN minutes (60 or more), on
52
56
  our side: works while your computer sleeps. Takes
53
57
  --repo/--from, --setup, --test, --where (not --task or
@@ -77,6 +81,11 @@ Computers (our own account first, for now)
77
81
  smartypants ws save ID NAME Save its files as NAME (the last 2 saves are kept)
78
82
  smartypants board post TITLE [--body T] [--label a,b] [--after TASK,..] [--group G --passphrase-env VAR]
79
83
  smartypants board list|show|claim [TASK]|renew|done|fail|note|flush
84
+ smartypants board renew TASK TOKEN [--progress T] [--save NAME] Where you got to, for whoever claims it next
85
+ smartypants board labels TASK [--add a,b] [--remove c] A label says whose turn it is
86
+ smartypants board changes [--since N] What changed since N (then ask from "next")
87
+ smartypants board watch --label L --agent AGENT | watchers | unwatch ID
88
+ Wake a saved agent only when a task with label L is ready
80
89
  The task board: claims with a lease; offline writes wait
81
90
  in ~/.smartypants/board-outbox.json until board flush
82
91
  smartypants board batch --model ID [--label L] [--max N] Run open tasks as one batch at half price;
@@ -93,6 +102,12 @@ passphrase in SMARTYPANTS_GROUP_PASSPHRASE or --passphrase-env VAR: files are lo
93
102
  smartypants mcp serve --group G Local MCP server (folder, log, board, models) for
94
103
  Claude Code and Codex; see: smartypants setup-agents
95
104
  smartypants setup-agents [--group G] Ready Claude Code and Codex setups using our models
105
+ smartypants skills [list] Agent skills on our shelf (each one approved and
106
+ pinned to one commit; no key needed)
107
+ smartypants skills add NAME... | --all [--project] [--to DIR]
108
+ Install them for Claude Code (~/.claude/skills) and
109
+ other agents (~/.agents/skills); --project puts them
110
+ in ./.claude/skills and ./.agents/skills instead
96
111
  smartypants ws link ID PORT A public link to a port in it (a web app or preview)
97
112
  smartypants ws links ID / ws unlink ID TOKEN List or close its public links
98
113
  smartypants ws end ID End it; its VM and files are destroyed
@@ -117,7 +132,7 @@ Exit codes: 0 ok, 1 error from the site, 2 bad usage, otherwise the program's ow
117
132
 
118
133
  export class UsageError extends Error {}
119
134
 
120
- const BOOLEAN_FLAGS = new Set(["json", "think", "public", "no-wait", "help", "version", "retry", "no-spill"]);
135
+ const BOOLEAN_FLAGS = new Set(["json", "think", "public", "no-wait", "help", "version", "retry", "no-spill", "no-pr"]);
121
136
  const SHORT = { c: "code", h: "help", v: "version" };
122
137
 
123
138
  /** Split argv into positional words and --flags. Flags may come anywhere. */
@@ -352,6 +367,7 @@ export async function main(argv, io) {
352
367
  case "board": return board(kit, sp, io, rest, flags, { show, json });
353
368
  case "space": return space(kit, sp, io, rest, flags, { show, json });
354
369
  case "setup-agents": return out(agentSetup(io, flags)), 0;
370
+ case "skills": return skills(sp, io, rest, flags, { out, show });
355
371
  case "fleet": return fleet(kit, sp, io, rest, flags, { out, json, show, pollMs });
356
372
  default: throw new UsageError(`unknown command ${command} (try smartypants help)`);
357
373
  }
@@ -379,9 +395,17 @@ async function board(kit, sp, io, words, flags, { show, json }) {
379
395
  const lease = number(flags, "lease", 300, { min: 30, max: 3600 });
380
396
  const t = words[1] ? await b.claim(words[1], { worker, leaseSeconds: lease }) : await b.claimNext({ worker, label: flags.label, leaseSeconds: lease });
381
397
  if (!t) { if (flags.json) json(null); else io.stderr("[nothing ready to claim]\n"); return 3; }
382
- return show(t, (v) => `${line(v)}\nclaim token: ${v.claimToken} (renew within ${lease} s: smartypants board renew ${v.id} ${v.claimToken})${v.body ? `\n${v.body}` : ""}`), 0;
398
+ return show(t, (v) => `${line(v)}\nclaim token: ${v.claimToken} (renew within ${lease} s: smartypants board renew ${v.id} ${v.claimToken})${v.pickup ? `\npick up from: ${v.pickup.progress ?? ""}${v.pickup.save ? ` (save: ${v.pickup.save})` : ""}` : ""}${v.body ? `\n${v.body}` : ""}`), 0;
383
399
  }
384
- case "renew": return show(await b.renew(need(words, 1, "TASK"), need(words, 2, "TOKEN"), number(flags, "lease", 300, { min: 30, max: 3600 })), line), 0;
400
+ case "renew": return show(await b.renew(need(words, 1, "TASK"), need(words, 2, "TOKEN"), number(flags, "lease", 300, { min: 30, max: 3600 }),
401
+ { ...(flags.progress !== undefined ? { progress: String(flags.progress) } : {}), ...(flags.save !== undefined ? { save: String(flags.save) } : {}) }), line), 0;
402
+ case "labels": return show(await b.labels(need(words, 1, "TASK"), { ...(flags.add ? { add: String(flags.add).split(",") } : {}),
403
+ ...(flags.remove ? { remove: String(flags.remove).split(",") } : {}) }), line), 0;
404
+ case "changes": return show(await b.changes({ since: number(flags, "since", 0, { min: 0, max: Number.MAX_SAFE_INTEGER }) }),
405
+ (r) => `${r.tasks.length ? r.tasks.map(line).join("\n") : "no changes"}\nnext: ${r.next}${r.more ? " (more)" : ""}`), 0;
406
+ case "watch": return show(await b.watch({ label: String(flags.label ?? ""), agent: String(flags.agent ?? "") }), (w) => `${w.id}: wakes agent ${w.agent} when a "${w.label}" task is ready`), 0;
407
+ case "watchers": return show(await b.watchers(), (ws) => ws.length ? ws.map((w) => `${w.id} ${w.label} -> ${w.agent} woken ${w.wakes}x${w.lastError ? ` last error: ${w.lastError}` : ""}`).join("\n") : "no watchers"), 0;
408
+ case "unwatch": return show(await b.unwatch(need(words, 1, "WATCHER")), () => "removed"), 0;
385
409
  case "done": return show(await b.done(need(words, 1, "TASK"), need(words, 2, "TOKEN"), flags.result === undefined ? undefined : String(flags.result)), (v) => queued(v) ?? line(v)), 0;
386
410
  case "fail": return show(await b.fail(need(words, 1, "TASK"), need(words, 2, "TOKEN"), { error: String(flags.error ?? "failed"), retry: flags.retry === true }), (v) => queued(v) ?? line(v)), 0;
387
411
  case "note": return show(await b.note(need(words, 1, "TASK"), need(words, 2, "TEXT"), { worker }), (v) => queued(v) ?? "noted"), 0;
@@ -403,7 +427,7 @@ async function board(kit, sp, io, words, flags, { show, json }) {
403
427
  const r = await b.finishBatch(id, saved.claims);
404
428
  return show(r, (v) => v.done + v.failed ? `${v.status}: ${v.done} tasks done, ${v.failed} back on the board` : `${v.status}: still running (claims renewed)`), 0;
405
429
  }
406
- default: throw new UsageError(`unknown board command ${sub ?? ""} (post, list, show, claim, renew, done, fail, note, flush, batch, batch-finish)`);
430
+ default: throw new UsageError(`unknown board command ${sub ?? ""} (post, list, show, claim, renew, labels, changes, watch, watchers, unwatch, done, fail, note, flush, batch, batch-finish)`);
407
431
  }
408
432
  }
409
433
 
@@ -479,6 +503,44 @@ The MCP server runs on your computer: files and notes are locked there with the
479
503
  `;
480
504
  }
481
505
 
506
+ const SKILL_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
507
+ const SKILL_FILE = /^(?!.*(?:^|\/)\.\.?(?:\/|$))[A-Za-z0-9_][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9_][A-Za-z0-9_.-]*){0,5}$/;
508
+
509
+ /** Where `skills add` writes: Claude Code's folder and the shared agents folder, at home or in this project. */
510
+ export function skillTargets(io, flags) {
511
+ if (flags.to) return String(flags.to).split(",").filter(Boolean);
512
+ const root = flags.project ? "." : (io.env.HOME || ".");
513
+ return [join(root, ".claude", "skills"), join(root, ".agents", "skills")];
514
+ }
515
+
516
+ /** The skills shelf (goal 110): list it, or copy approved skills into the agent skill folders. */
517
+ async function skills(sp, io, words, flags, { out, show }) {
518
+ const sub = words[0] ?? "list";
519
+ const shelf = (await sp.request("GET", "/v1/skills", undefined, { auth: false })).data;
520
+ if (sub === "list") return show(shelf, (list) => list.map((s) => `${s.name.padEnd(24)} ${s.description}${s.source ? `\n${"".padEnd(25)}from ${s.source}${s.commit ? ` @ ${s.commit.slice(0, 12)}` : ""}, ${s.license}` : ""}`).join("\n") || "The shelf is empty."), 0;
521
+ if (sub !== "add") throw new UsageError(`unknown skills command "${sub}" (list or add)`);
522
+ const names = flags.all ? shelf.map((s) => s.name) : words.slice(1);
523
+ if (!names.length) throw new UsageError("name a skill to add (smartypants skills list shows them), or use --all");
524
+ const targets = skillTargets(io, flags);
525
+ for (const name of names) {
526
+ const skill = shelf.find((s) => s.name === name);
527
+ if (!skill || !SKILL_NAME.test(name)) throw new UsageError(`"${name}" is not on the shelf (smartypants skills list shows them)`);
528
+ for (const file of skill.files) {
529
+ if (!SKILL_FILE.test(file)) continue;
530
+ const response = await sp.fetch(`${sp.baseUrl}/v1/skills/${name}/${file.split("/").map(encodeURIComponent).join("/")}`, { method: "GET" });
531
+ if (!response.ok) throw new Error(`could not fetch ${name}/${file} (HTTP ${response.status})`);
532
+ const text = await response.text();
533
+ for (const target of targets) {
534
+ const path = join(target, name, file);
535
+ io.mkdir(dirname(path), { recursive: true });
536
+ io.writeFile(path, text);
537
+ }
538
+ }
539
+ out(`added ${name} (${skill.files.length} file${skill.files.length === 1 ? "" : "s"}) to ${targets.map((t) => join(t, name)).join(", ")}`);
540
+ }
541
+ return 0;
542
+ }
543
+
482
544
  /** The tools the local MCP server offers (goal 82). Board and folder text from others is data, not instructions. */
483
545
  export const LOCAL_MCP_TOOLS = [
484
546
  { name: "space_list", description: "List files in the Group folder (path, version, who changed it). Optional prefix.", inputSchema: { type: "object", properties: { prefix: { type: "string" } } } },
@@ -571,6 +633,10 @@ async function job(sp, io, flags, { out, json }) {
571
633
  waitSeconds: number(flags, "wait", 300, { min: 1, max: 3600 }), retries: number(flags, "retries", 0, { min: 0, max: 5 }),
572
634
  ...(flags.where !== undefined ? { where: whereFlag(flags.where) } : {}),
573
635
  source: io.env?.SMARTYPANTS_JOB_SOURCE === "github" ? "github" : "cli" };
636
+ // A draft pull request when the work is done: on unless --no-pr. The token comes from the environment, never the command line.
637
+ options.pr = flags["no-pr"] !== true;
638
+ const githubToken = io.env?.GITHUB_TOKEN || io.env?.GH_TOKEN;
639
+ if (options.pr && githubToken) options.github = { token: githubToken };
574
640
  if (options.budgetUsd > 0 && options.budgetUsd < 0.1) throw new UsageError("--budget is 0 (no model key) or $0.10 to $20");
575
641
  if (flags.model) options.model = flags.model;
576
642
  if (flags.dir) {
@@ -599,7 +665,12 @@ async function job(sp, io, flags, { out, json }) {
599
665
  io.stderr(`[${failed}, exit ${result.exitCode ?? "none"}, ${result.steps.length} steps, ${result.seconds} s, cost ${usd(result.chargeMicros)}`
600
666
  + `${result.inferenceUsage?.spentMicros ? ` + models ${usd(result.inferenceUsage.spentMicros)}` : ""}, workspace ${result.workspaceId}`
601
667
  + `${result.retries ? `, picked up ${result.retries} time${result.retries > 1 ? "s" : ""}` : ""}]\n`);
668
+ if (result.cost?.headline) io.stderr(`${[result.cost.headline, ...result.cost.lines].join("\n")}\n`);
669
+ const pr = result.pullRequest;
670
+ if (pr?.url) io.stderr(`[draft pull request: ${pr.url}]\n`);
671
+ else if (pr?.skipped && flags.task) io.stderr(`[no pull request: ${pr.skipped}]\n`);
602
672
  if (flags.out) io.stderr(`[saved to ${flags.out}]\n`);
673
+ if (result.checkpointError) io.stderr(`[could not save its progress (${result.checkpointError}), so a lost Mac would have started it over. Free a slot with: smartypants saved, then DELETE one you don't need]\n`);
603
674
  }
604
675
  return result.passed ? 0 : (result.exitCode || 1);
605
676
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "smartypants-network",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Use when an agent needs cheap, exact open-model AI calls (OpenAI-compatible, priced per token) or sealed Linux workspaces on idle Macs. Smarty Pants: exact open models priced per token, plus sealed Linux workspaces and fleets on idle Macs. Command-line tool and one-file JavaScript kit, no dependencies.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/smartypants.mjs CHANGED
@@ -68,13 +68,13 @@ export class SmartyPants {
68
68
  this.rpcId = 0;
69
69
  }
70
70
 
71
- async request(method, path, body, { auth = true, headers = {} } = {}) {
71
+ async request(method, path, body, { auth = true, headers = {}, timeoutMs } = {}) {
72
72
  if (auth && !this.apiKey) throw new SmartyPantsError("No API key. Set SMARTYPANTS_API_KEY (create one at https://smartypants.network/api).");
73
73
  const response = await this.fetch(`${this.baseUrl}${path}`, {
74
74
  method,
75
75
  headers: { accept: "application/json", ...(body === undefined ? {} : { "content-type": "application/json" }), ...(auth ? { authorization: `Bearer ${this.apiKey}` } : {}), ...headers },
76
76
  body: body === undefined ? undefined : JSON.stringify(body),
77
- signal: AbortSignal.timeout(this.timeoutMs),
77
+ signal: AbortSignal.timeout(Math.max(this.timeoutMs, timeoutMs ?? 0)),
78
78
  });
79
79
  const text = await response.text();
80
80
  let data = null;
@@ -181,7 +181,8 @@ export class SmartyPants {
181
181
  if (workspace) body.sessionId = typeof workspace === "string" ? workspace : workspace.id;
182
182
  if (where !== undefined) body.where = where;
183
183
  if (waitSeconds !== undefined) body.waitSeconds = waitSeconds;
184
- return this.request("POST", "/v1/code/run", body);
184
+ // The site holds the call while it waits for a Mac and runs the code, so don't give up before it does.
185
+ return this.request("POST", "/v1/code/run", body, { timeoutMs: ((waitSeconds ?? 120) + body.timeoutSeconds + 30) * 1000 });
185
186
  }
186
187
 
187
188
  async runCode(language, source, { timeoutSeconds = 20, pollMs = 5000, waitSeconds = 120 } = {}) {
@@ -212,18 +213,27 @@ export class SmartyPants {
212
213
  * inferenceBudgetUsd gives the workspace its own Smarty Pants key (ws.inference.apiKey and
213
214
  * ws.inference.baseUrl) that can spend at most that much and stops working when it ends.
214
215
  */
215
- async workspace({ minutes = 10, waitSeconds = 120, pollMs = 1000, inferenceBudgetUsd, internet, from, retryOf, where, shape, sites } = {}) {
216
+ async workspace({ minutes = 10, waitSeconds = 120, pollMs = 1000, inferenceBudgetUsd, internet, from, retryOf, where, shape, sites, git, pause, spill, alwaysOn } = {}) {
216
217
  const body = { seconds: Math.round(minutes * 60) };
218
+ // Goal 108: one of a Pro seat's 2 always-on workspaces in that Group (where { group }): never idles out, woken again when its time runs out.
219
+ if (alwaysOn !== undefined) { body.alwaysOn = alwaysOn; if (alwaysOn) delete body.seconds; }
220
+ // Goal 97: pause: true (or the model id it calls) keeps it: idle, owner back, Mac lost or time up saves
221
+ // its files and pauses it (nothing billed); the next use wakes it, same id, on whichever Mac is free.
222
+ if (pause) body.pause = typeof pause === "string" ? { model: pause } : true;
217
223
  if (shape !== undefined) body.shape = shape; // "browser": 4 GB, its own disk, Chromium inside
218
224
  if (sites !== undefined) body.sites = sites; // a browser workspace's internet: only these sites ("*.example.com" for a whole domain)
219
225
  if (where !== undefined) body.where = where; // "mine" or { group: id }: only those Macs, free
226
+ if (spill !== undefined) body.spill = spill; // with where { group }: may go to a paid network Mac when the Group's are busy, under the Group's cap
220
227
  if (from) body.from = from; // a copy of that saved workspace: its files are in /work before this returns
221
228
  if (retryOf) body.retryOf = retryOf; // a lost workspace: for a minute, prefer a Mac other than the one it ran on
222
229
  if (inferenceBudgetUsd !== undefined) body.inference = { budgetMicros: Math.round(inferenceBudgetUsd * 1e6) };
223
230
  if (internet !== undefined) body.internet = internet; // "listed": the reviewed sites (GitHub, PyPI, npm, ...)
231
+ // { github: { token, repos? } }: git push and private clones through the site; the token never enters the VM.
232
+ if (git !== undefined) body.git = git;
224
233
  let session = await this.request("POST", "/v1/cpu/sessions", body);
225
234
  const ws = new Workspace(this, session.id, pollMs);
226
235
  ws.inference = session.inference ?? null;
236
+ ws.git = session.git ?? null; // { setupCommand, ... }: run setupCommand in the VM before using git
227
237
  const deadline = Date.now() + waitSeconds * 1000;
228
238
  while (session.status === "queued") {
229
239
  if (Date.now() > deadline) { await ws.close(); throw new SmartyPantsError(`workspace ${session.id} still waiting for a Mac after ${waitSeconds} s`, { code: "WAIT_TIMEOUT" }); }
@@ -290,21 +300,84 @@ code=$?
290
300
  exit $code
291
301
  `;
292
302
 
303
+ // The workspace's git grant (written to /work/.sp-git.sh once it opens) points https://github.com at the site's git proxy.
304
+ const GIT_SETUP = "{ [ ! -f /work/.sp-git.sh ] || sh /work/.sp-git.sh; }";
305
+ // Commit the task's changes on a new branch and push it; prints SP-PR-BASE=<the branch it started from>, or SP-PR-NOTHING.
306
+ export const PR_PUSH_SCRIPT = String.raw`[ ! -f /work/.sp-git.sh ] || sh /work/.sp-git.sh
307
+ git add -A >/dev/null 2>&1
308
+ if git diff --cached --quiet; then echo SP-PR-NOTHING; exit 0; fi
309
+ base=$(git rev-parse --abbrev-ref HEAD)
310
+ git checkout -q -b @BRANCH@ && git -c user.name='Smarty Pants job' -c user.email=job@smartypants.network commit -qm @TITLE@ \
311
+ && git push -q origin HEAD:refs/heads/@BRANCH@ >&2 && echo "SP-PR-BASE=$base"`;
312
+
313
+ /** owner/name of an https://github.com/owner/name(.git) URL, else null. */
314
+ export function githubRepo(url) {
315
+ const m = /^https:\/\/github\.com\/([A-Za-z0-9_-][A-Za-z0-9_.-]*)\/([A-Za-z0-9_-][A-Za-z0-9_.-]*?)(?:\.git)?\/?$/.exec(String(url ?? ""));
316
+ return m ? `${m[1]}/${m[2]}` : null;
317
+ }
318
+
319
+ /** The draft pull request's title and body for a finished job. */
320
+ export function pullRequestText({ task, passed, failedStep, testRan, chargeMicros, inferenceSpentMicros, seconds }) {
321
+ const first = String(task ?? "").trim().split("\n")[0].trim();
322
+ const title = first.length > 72 ? `${first.slice(0, 69).trimEnd()}...` : first || "Smarty Pants job";
323
+ const tests = !testRan ? "No test command was given." : passed ? "The tests passed in the workspace." : `The job failed at the ${failedStep} step; see its logs.`;
324
+ const cost = chargeMicros === null || chargeMicros === undefined ? "" : ` Workspace time cost $${(chargeMicros / 1e6).toFixed(4)}`
325
+ + `${inferenceSpentMicros ? `, models $${(inferenceSpentMicros / 1e6).toFixed(4)}` : ""}.`;
326
+ return { title, body: `Opened as a draft by a Smarty Pants job when the work was done.\n\n**Task**\n\n${String(task ?? "").trim()}\n\n**Tests**\n\n${tests}\n\n${seconds} s in all.${cost}\n` };
327
+ }
328
+
329
+ export const GROUPS_URL = "https://smartypants.network/groups";
330
+ const cents = (micros) => {
331
+ const c = micros / 1e4;
332
+ return c < 1 ? `${Math.max(0.1, Math.round(c * 10) / 10)}¢` : c < 100 ? `${Math.round(c)}¢` : `$${(c / 100).toFixed(2)}`;
333
+ };
334
+
335
+ /**
336
+ * What a finished job cost, in words that point at Groups (Frog lesson, Nat 2026-11-20): work on your own
337
+ * or your Group's Macs is free, so the next step is inviting friends with Macs, or paying a few cents a job.
338
+ * Returns { free, headline, lines }.
339
+ */
340
+ export function jobCostWords({ where = null, chargeMicros = null, inferenceSpentMicros = 0, seconds = 0, passed = true } = {}) {
341
+ const spent = (chargeMicros ?? 0) + (inferenceSpentMicros ?? 0);
342
+ const perHour = seconds > 0 ? Math.floor(3600 / seconds) : null;
343
+ const pace = passed !== false && perHour && perHour >= 1 ? ` One Mac can run about ${perHour.toLocaleString("en-US")} jobs like this an hour.` : "";
344
+ const mine = where === "mine";
345
+ const group = where && typeof where === "object" && where.group;
346
+ if (chargeMicros !== null && spent === 0) {
347
+ // A failed job is still free, but it is not "done" (11-21: a job that stopped at its task step said "Done free").
348
+ const place = mine ? "your own Mac" : "your Group's Macs";
349
+ return { free: true, headline: passed === false ? `It stopped before finishing; the time on ${place} was free.` : `Done free on ${place}.`,
350
+ lines: [mine ? `Start a Group and invite friends with Macs, and their Macs take your jobs free too: ${GROUPS_URL}.${pace}`
351
+ : `Each friend who adds a Mac to your Group means more jobs like this run free at once: ${GROUPS_URL}.${pace}`] };
352
+ }
353
+ if (chargeMicros === null) return { free: false, headline: "The cost isn't known yet.", lines: [] };
354
+ const what = `${cents(spent)}${inferenceSpentMicros ? ` (Mac time ${cents(chargeMicros)}, models ${cents(inferenceSpentMicros)})` : ""}`;
355
+ if (group) {
356
+ return { free: false, headline: `Your Group's Macs were busy, so this job ran on network Macs for ${what}, from the Group's spill-over cap.`,
357
+ lines: [`More Macs in your Group means more jobs run free: invite friends at ${GROUPS_URL}.`] };
358
+ }
359
+ return { free: false, headline: `That job cost ${what}.`,
360
+ lines: [`On your own or your Group's Macs it would have been free: invite friends with Macs at ${GROUPS_URL}, then run with --where group:ID.`,
361
+ `Or keep going at about ${cents(spent)} a job like this.`] };
362
+ }
363
+
293
364
  /** The shell steps a job runs, in order. Exported so tests and other kits can see the exact scripts. */
294
- export function jobSteps({ repo = "", upload = false, from = "", setup = "", task = "", test = "", collect = [], model = CODING_MODEL, maxTurns = 12 } = {}) {
365
+ export function jobSteps({ repo = "", upload = false, from = "", setup = "", task = "", test = "", collect = [], model = CODING_MODEL, maxTurns = 12, pr = null } = {}) {
295
366
  const steps = [];
296
367
  // The first step starts the list of finished steps afresh (a saved setup copied in brings its own).
297
368
  const step = (name, body) => steps.push({ name, script: JOB_STEP_SCRIPT
298
369
  .replace("@BODY@", steps.length ? body : `: > /work/.sp-job/done\n${body}`).replaceAll("@NAME@", name) });
299
370
  // git is only on the internet-ready image; an offline workspace still unpacks and tests, it just keeps no history.
300
371
  const baseline = "if [ ! -d .git ] && command -v git >/dev/null 2>&1; then git init -q . && git add -A && git -c user.name=job -c user.email=job@smartypants.network commit -qm start --allow-empty; fi";
301
- if (repo) step("clone", `cd /work && rm -rf /work/repo && git clone --depth 1 ${shQuote(repo)} /work/repo >&2`);
372
+ if (repo) step("clone", `${pr ? `${GIT_SETUP} && ` : ""}cd /work && rm -rf /work/repo && git clone --depth 1 ${shQuote(repo)} /work/repo >&2`);
302
373
  else if (upload) step("unpack", `tar xzf /work/.sp-upload.tar.gz -C /work/repo && rm -f /work/.sp-upload.tar.gz && ${baseline}`);
303
374
  else if (from) step("start", `[ -d /work/repo ] && ${baseline}`);
304
375
  else step("start", baseline);
305
376
  if (setup) step("setup", setup);
306
377
  if (task) step("task", `${CODING_AGENT_SCRIPT.replace(/^set -u\n/, "").replaceAll("@MODEL@", shQuote(model))
307
378
  .replace("@REPO@", "''").replace("@TURNS@", String(Math.round(maxTurns))).replace(/\nexit \$code\n$/, "\n(exit $code)")}`);
379
+ // The task's changes go up as their own branch before the tests run, so test output never lands in the pull request.
380
+ if (task && pr) step("push", PR_PUSH_SCRIPT.replaceAll("@BRANCH@", shQuote(pr.branch)).replace("@TITLE@", shQuote(pr.title)));
308
381
  if (test) step("test", test);
309
382
  const paths = (Array.isArray(collect) ? collect : String(collect).split(",")).map((p) => String(p).trim()).filter(Boolean);
310
383
  if (paths.length) step("collect", `rm -f /work/.sp-job/files.tar.gz; tar czf /work/.sp-job/files.tar.gz ${paths.join(" ")} && tar tzf /work/.sp-job/files.tar.gz`);
@@ -324,12 +397,20 @@ export function jobSteps({ repo = "", upload = false, from = "", setup = "", tas
324
397
  */
325
398
  SmartyPants.prototype.job = async function job({ repo = "", upload = null, from = "", setup = "", task = "", test = "", collect = [], model = CODING_MODEL,
326
399
  minutes = 30, budgetUsd = 0.25, stepTimeoutSeconds = 600, maxTurns = 12, waitSeconds = 180, internet = "listed", onStep, onOutput, report = true, source = "kit",
327
- retries = 0, onRetry, where } = {}) {
400
+ retries = 0, onRetry, where, pr = true, github = null, fetchImpl = globalThis.fetch } = {}) {
328
401
  if (from && (repo || upload)) throw new SmartyPantsError("give from, repo or upload, not two of them", { code: "BAD_JOB" });
329
402
  if (task && !budgetUsd) throw new SmartyPantsError("a task needs a model budget (budgetUsd)", { code: "BUDGET_NEEDED" });
330
403
  const started = Date.now();
331
- const steps = jobSteps({ repo, upload: Boolean(upload && !repo), from, setup, task, test, collect, model, maxTurns });
332
- const open = (opts) => this.workspace({ minutes, waitSeconds, inferenceBudgetUsd: budgetUsd || undefined, internet, where, ...opts });
404
+ // A draft pull request when the work is done: on by default for a task on a GitHub repo, given a GitHub token
405
+ // (the token stays on the site; the VM only gets a capability for this one repo, for this workspace).
406
+ const ghRepo = githubRepo(repo);
407
+ const prSkip = !pr ? "turned off" : !task ? null : !ghRepo ? (repo ? "not a https://github.com repo" : null) : !github?.token ? "no GitHub token" : null;
408
+ const prPlan = pr && task && ghRepo && github?.token
409
+ ? { branch: `smartypants/job-${Math.random().toString(36).slice(2, 10)}`, title: pullRequestText({ task }).title } : null;
410
+ const steps = jobSteps({ repo, upload: Boolean(upload && !repo), from, setup, task, test, collect, model, maxTurns, pr: prPlan });
411
+ const git = prPlan ? { github: { token: github.token, repos: [ghRepo.toLowerCase()] } } : undefined;
412
+ const open = (opts) => this.workspace({ minutes, waitSeconds, inferenceBudgetUsd: budgetUsd || undefined, internet, where, git, ...opts });
413
+ const grantGit = async () => { if (prPlan && ws.git?.setupCommand) await ws.putFile(".sp-git.sh", `${ws.git.setupCommand}\n`); };
333
414
  let ws = await open(from ? { from } : {});
334
415
  const result = { passed: false, failedStep: null, exitCode: null, steps: [], diff: "", files: null, inferenceUsage: null,
335
416
  workspaceId: ws.id, workspaceIds: [ws.id], retries: 0 };
@@ -344,6 +425,7 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
344
425
  };
345
426
  try {
346
427
  await send();
428
+ await grantGit();
347
429
  for (let i = 0; i < steps.length; i++) {
348
430
  const { name, script } = steps[i];
349
431
  onStep?.(name);
@@ -360,6 +442,7 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
360
442
  ws = await open({ retryOf: lostId, ...(saved ? { from: checkpoint } : from ? { from } : {}) });
361
443
  result.workspaceIds.push(ws.id);
362
444
  result.workspaceId = ws.id;
445
+ await grantGit(); // a new workspace has a new git capability
363
446
  let finished = [];
364
447
  if (saved) finished = await ws.getFile(".sp-job/done").then((b) => Buffer.from(b).toString("utf8").split("\n").filter(Boolean)).catch(() => []);
365
448
  else await send();
@@ -373,7 +456,7 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
373
456
  result.steps.push(done);
374
457
  // Save after each step that is worth not doing again (not after the test or the last step).
375
458
  if (retries > 0 && run.exitCode === 0 && i < steps.length - 1 && name !== "test") {
376
- saved = await ws.save(checkpoint).then(() => true, () => saved);
459
+ saved = await ws.save(checkpoint).then(() => true, (error) => { result.checkpointError ??= error.code || error.message; return saved; });
377
460
  }
378
461
  if (name === "test") result.exitCode = run.exitCode;
379
462
  if (run.exitCode !== 0 && result.failedStep === null) {
@@ -387,7 +470,12 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
387
470
  const packed = result.steps.find((s) => s.name === "collect" && s.exitCode === 0);
388
471
  if (packed) result.files = { names: packed.stdout.split("\n").filter(Boolean), bytes: await ws.getFile(".sp-job/files.tar.gz").catch(() => null) };
389
472
  result.inferenceUsage = await this.request("GET", `${ws.path}/inference`).catch(() => null);
390
- } finally { await ws.close(); }
473
+ } finally {
474
+ await ws.close();
475
+ // The checkpoint is only for this job, even one that stopped with an error: let it go, so it
476
+ // doesn't fill the account's saved workspaces (8 at most).
477
+ if (saved) await this.request("DELETE", `/v1/cpu/saved/${encodeURIComponent(checkpoint)}`).catch(() => null);
478
+ }
391
479
  if (saved) result.checkpoint = checkpoint;
392
480
  result.chargeMicros = null;
393
481
  for (let i = 0; i < 20 && result.chargeMicros === null; i++) { // the charge follows the Mac's end report
@@ -401,6 +489,20 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
401
489
  if (result.chargeMicros !== null) result.chargeMicros += c;
402
490
  }
403
491
  result.seconds = Math.round((Date.now() - started) / 100) / 10;
492
+ result.cost = jobCostWords({ where, passed: result.passed, chargeMicros: result.chargeMicros, inferenceSpentMicros: result.inferenceUsage?.spentMicros ?? 0, seconds: result.seconds });
493
+ result.pullRequest = prSkip ? { skipped: prSkip } : null;
494
+ const pushed = result.steps.find((s) => s.name === "push" && s.exitCode === 0);
495
+ const base = /SP-PR-BASE=(\S+)/.exec(pushed?.stdout ?? "")?.[1];
496
+ if (prPlan && pushed && !base) result.pullRequest = { skipped: "the task changed nothing" };
497
+ else if (prPlan && !pushed) result.pullRequest = { skipped: "the job stopped before its changes were pushed" };
498
+ else if (prPlan && base) {
499
+ const text = pullRequestText({ task, passed: result.passed, failedStep: result.failedStep, testRan: Boolean(test),
500
+ chargeMicros: result.chargeMicros, inferenceSpentMicros: result.inferenceUsage?.spentMicros, seconds: result.seconds });
501
+ if (result.cost?.headline) text.body += `\n${[result.cost.headline, ...result.cost.lines].join(" ")}\n`;
502
+ result.pullRequest = await openDraftPullRequest(fetchImpl, github.token, ghRepo, { ...text, head: prPlan.branch, base })
503
+ .catch((error) => ({ skipped: `GitHub refused it: ${error.message}${/not permitted to create/i.test(error.message)
504
+ ? ` (turn on the repo's Settings > Actions > General > "Allow GitHub Actions to create and approve pull requests", or use a token of your own; the changes are on branch ${prPlan.branch})` : ""}`, branch: prPlan.branch }));
505
+ }
404
506
  // The job scoreboard: how it went, for cost per successful job, finish times and recovery. Best effort.
405
507
  if (report) {
406
508
  const size = (x) => (x ? Buffer.byteLength(x) : 0);
@@ -413,6 +515,16 @@ SmartyPants.prototype.job = async function job({ repo = "", upload = null, from
413
515
  return result;
414
516
  };
415
517
 
518
+ /** POST /repos/{repo}/pulls as a draft; returns { url, number, draft, branch }. */
519
+ async function openDraftPullRequest(fetchImpl, token, repo, { title, body, head, base }) {
520
+ const response = await fetchImpl(`https://api.github.com/repos/${repo}/pulls`, { method: "POST",
521
+ headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "content-type": "application/json", "user-agent": "smartypants-job" },
522
+ body: JSON.stringify({ title, body, head, base, draft: true }) });
523
+ const data = await response.json().catch(() => ({}));
524
+ if (!response.ok) throw new Error(`${response.status} ${data.message ?? ""}`.trim());
525
+ return { url: data.html_url, number: data.number, draft: data.draft !== false, branch: head };
526
+ }
527
+
416
528
  /**
417
529
  * A saved setup: clone `repo` (or unpack `upload`), run `setup` once (installs, builds), and save the
418
530
  * result as `name`. Later workspaces and jobs open as a copy of it ({ from: name }), so they start with
@@ -460,8 +572,11 @@ export class Board {
460
572
  lock(text) { return this.passphrase ? lockText(text, this.passphrase) : text; }
461
573
  unlock(task) {
462
574
  if (!task || !this.passphrase) return task;
463
- const open = (t) => (typeof t === "string" && t.startsWith("spbox1:") ? unlockText(t, this.passphrase) : t);
464
- return { ...task, body: open(task.body), result: open(task.result), notes: task.notes?.map((n) => ({ ...n, text: open(n.text) })) };
575
+ let unreadable = false;
576
+ const open = (t) => { const r = openText(t, this.passphrase); if (r.unreadable) unreadable = true; return r.text; };
577
+ const out = { ...task, body: open(task.body), result: open(task.result), notes: task.notes?.map((n) => ({ ...n, text: open(n.text) })),
578
+ ...(task.pickup ? { pickup: { ...task.pickup, progress: open(task.pickup.progress) } } : {}) };
579
+ return unreadable ? { ...out, unreadable: true } : out;
465
580
  }
466
581
  where() { return this.group ? { group: this.group } : {}; }
467
582
  async write(path, body, { queue = true } = {}) {
@@ -508,9 +623,25 @@ export class Board {
508
623
  return this.unlock(r.task);
509
624
  }
510
625
  async claim(id, { worker, leaseSeconds = 300 } = {}) { return this.unlock(await this.write(`/v1/board/tasks/${encodeURIComponent(id)}/claim`, { worker, leaseSeconds }, { queue: false })); }
511
- renew(id, claimToken, leaseSeconds = 300) { return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/renew`, { claimToken, leaseSeconds }, { queue: false }); }
626
+ /** Keep the claim. `progress` (where the work got to) and `save` (your last save's name) go to whoever claims it next. */
627
+ renew(id, claimToken, leaseSeconds = 300, { progress, save } = {}) {
628
+ return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/renew`, { claimToken, leaseSeconds, ...this.pickupFields({ progress, save }) }, { queue: false });
629
+ }
630
+ pickupFields({ progress, save } = {}) { return { ...(progress !== undefined ? { progress: this.lock(progress) } : {}), ...(save !== undefined ? { save } : {}) }; }
512
631
  done(id, claimToken, result) { return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/done`, { claimToken, ...(result !== undefined ? { result: this.lock(result) } : {}) }); }
513
- fail(id, claimToken, { error, retry = false } = {}) { return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/fail`, { claimToken, error, retry }); }
632
+ fail(id, claimToken, { error, retry = false, progress, save } = {}) { return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/fail`, { claimToken, error, retry, ...this.pickupFields({ progress, save }) }); }
633
+ /** Change labels, so a label can say whose turn it is: labels(id, { add: ["needs-review"], remove: ["needs-fix"] }). */
634
+ async labels(id, { add, remove } = {}) { return this.unlock(await this.write(`/v1/board/tasks/${encodeURIComponent(id)}/labels`, { ...(add ? { add } : {}), ...(remove ? { remove } : {}) })); }
635
+ /** What changed since change number `since` (0 for everything); ask again from `next`. */
636
+ async changes({ since = 0 } = {}) {
637
+ const q = new URLSearchParams({ ...this.where(), since: String(since) }).toString();
638
+ const r = await this.sp.request("GET", `/v1/board/changes?${q}`);
639
+ return { ...r, tasks: r.tasks.map((t) => this.unlock(t)) };
640
+ }
641
+ /** Wake one of your saved workspace agents when a task with this label becomes ready (no polling, nothing billed meanwhile). */
642
+ watch({ label, agent }) { return this.sp.request("POST", "/v1/board/watchers", { label, agent, ...this.where() }); }
643
+ async watchers() { return (await this.sp.request("GET", "/v1/board/watchers")).watchers; }
644
+ unwatch(id) { return this.sp.request("DELETE", `/v1/board/watchers/${encodeURIComponent(id)}`); }
514
645
  note(id, text, { worker } = {}) { return this.write(`/v1/board/tasks/${encodeURIComponent(id)}/note`, { text: this.lock(text), ...(this.passphrase ? { locked: true } : {}), ...(worker ? { worker } : {}) }); }
515
646
  /**
516
647
  * Goal 84: run open tasks as one batch at half the model price. Claims up to `max` ready tasks
@@ -628,13 +759,18 @@ export class Space {
628
759
  /** The Group's activity log (notes unlocked): what the last person or agent did. */
629
760
  async log({ since } = {}) {
630
761
  const r = await this.sp.request("GET", this.path(`/activity${since !== undefined ? `?since=${since}` : ""}`));
631
- return r.entries.map((e) => (e.kind === "note" && typeof e.text === "string" && e.text.startsWith("spbox1:") ? { ...e, text: unlockText(e.text, this.passphrase) } : e));
762
+ return r.entries.map((e) => {
763
+ if (e.kind !== "note") return e;
764
+ const o = openText(e.text, this.passphrase);
765
+ return o.unreadable ? { ...e, text: null, unreadable: true } : { ...e, text: o.text };
766
+ });
632
767
  }
633
768
  note(text, { path } = {}) { return this.sp.request("POST", this.path("/notes"), { text: lockText(text, this.passphrase), ...(path ? { path } : {}), ...(this.by ? { by: this.by } : {}) }); }
634
769
  grant({ prefix = "", minutes = 5, mode = "read", label } = {}) { return this.sp.request("POST", this.path("/grants"), { prefix, minutes, mode, ...(label ? { label } : {}) }); }
635
770
  grants() { return this.sp.request("GET", this.path("/grants")); }
636
771
  revoke(id) { return this.sp.request("DELETE", this.path(`/grants/${encodeURIComponent(id)}`)); }
637
- seat(seat, { account } = {}) { return this.sp.request("POST", this.path("/seat"), { seat, ...(account ? { account } : {}) }); }
772
+ /** "entry" or "pro" (Pro charges $49 from the balance and adds $50 of credit). Entry ends Pro at the paid month's end, or now with { now: true }. */
773
+ seat(seat, { account, now } = {}) { return this.sp.request("POST", this.path("/seat"), { seat, ...(account ? { account } : {}), ...(now !== undefined ? { now } : {}) }); }
638
774
 
639
775
  /**
640
776
  * Two-way sync of a local folder with the Group folder. Local changes go up first (a clash becomes a
@@ -740,6 +876,220 @@ async function writeOutbox(path, items) {
740
876
  await fs.rename(`${path}.tmp`, path);
741
877
  }
742
878
 
879
+ /**
880
+ * Goal 103: the program a Group factory's agent runs (Node, inside a workspace on the Group's Macs).
881
+ * Woken by a card with the factory's label, it takes ready cards one by one until none are left or its
882
+ * time is nearly up. A normal card: it reads the prompt the card should use, asks the factory's model,
883
+ * and in "practice" drafts the answer on the card for a person to approve (goal 104), or in "live"
884
+ * writes it into the Group folder at once. An "apply" card (posted when a person approves a draft)
885
+ * writes that approved draft into the Group folder. It never prints card text, only card ids.
886
+ */
887
+ export const FACTORY_RUNNER = String.raw`// Smarty Pants Group factory runner (goals 103-105).
888
+ const F = __FACTORY__;
889
+ (async () => {
890
+ const fs = require('node:fs');
891
+ const base = (process.env.SMARTYPANTS_BASE_URL || '').replace(/\/v1\/?$/, '');
892
+ if (!base || !process.env.SMARTYPANTS_API_KEY) throw new Error('this workspace has no model key (give the agent a model budget)');
893
+ const passphrase = fs.readFileSync('/work/.sp-group-passphrase', 'utf8').trim();
894
+ const kit = await fetch(base + '/kits/smartypants.mjs');
895
+ if (!kit.ok) throw new Error('could not fetch the kit: HTTP ' + kit.status);
896
+ fs.writeFileSync('/work/.sp-kit.mjs', await kit.text());
897
+ const { SmartyPants, Board, Space, openText } = await import('/work/.sp-kit.mjs');
898
+ const sp = new SmartyPants({ baseUrl: base });
899
+ const board = new Board(sp, { group: F.group, passphrase });
900
+ const space = new Space(sp, { group: F.group, passphrase, by: 'factory:' + F.name });
901
+ const worker = 'factory-' + F.name;
902
+ const mine = (await sp.request('GET', '/v1/factories?group=' + encodeURIComponent(F.group))).factories.find((f) => f.label === F.label && f.name === F.name);
903
+ if (!mine) throw new Error('factory ' + F.name + ' is gone');
904
+ const stopAt = Date.now() + Number(process.env.SP_FACTORY_SECONDS || 200) * 1000;
905
+ const slug = (t) => t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'card';
906
+ const pathFor = (card) => 'factories/' + F.name + '/' + slug(card.title) + '-' + card.id.slice(-6) + '.md';
907
+ let did = 0, failed = 0;
908
+ while (Date.now() < stopAt) {
909
+ const t = await board.claimNext({ worker, label: F.label, leaseSeconds: 600 });
910
+ if (!t) break;
911
+ try {
912
+ if (t.unreadable) throw new Error('card locked with another passphrase');
913
+ if (t.labels.includes('apply')) {
914
+ const draft = await board.get(t.dependsOn[0]);
915
+ if (draft.unreadable || draft.result == null) throw new Error('the approved draft is missing or unreadable');
916
+ const path = pathFor(draft);
917
+ await space.write(path, draft.result);
918
+ await board.done(t.id, t.claimToken, 'Applied: written to ' + path);
919
+ } else {
920
+ const p = await sp.request('GET', '/v1/factories/' + mine.id + '/prompt?task=' + t.id);
921
+ const system = openText(p.text, passphrase).text;
922
+ if (system == null) throw new Error('prompt v' + p.version + ' is locked with another passphrase');
923
+ const reply = await sp.chat([{ role: 'system', content: system }, { role: 'user', content: t.body ? t.title + '\n\n' + t.body : t.title }],
924
+ { model: p.model, max_tokens: 2048, reasoning: { enabled: false } });
925
+ const answer = String(reply.choices?.[0]?.message?.content ?? '').slice(0, 12000);
926
+ const text = '<!-- factory ' + F.name + ', prompt v' + p.version + ' (' + p.status + '), model ' + p.model + ' -->\n' + answer;
927
+ if (t.labels.includes('test')) {
928
+ await board.done(t.id, t.claimToken, text);
929
+ } else if (p.mode === 'live') {
930
+ const path = pathFor(t);
931
+ await space.write(path, text);
932
+ await board.done(t.id, t.claimToken, text + '\n\n(Written to ' + path + ')');
933
+ } else {
934
+ await board.labels(t.id, { add: ['awaiting-approval'] });
935
+ await board.done(t.id, t.claimToken, text);
936
+ }
937
+ }
938
+ did += 1;
939
+ } catch (e) {
940
+ failed += 1;
941
+ console.error('card ' + t.id + ': ' + String((e && e.message) || e).slice(0, 300));
942
+ await board.fail(t.id, t.claimToken, { error: String((e && e.message) || e).slice(0, 300) }).catch(() => {});
943
+ }
944
+ }
945
+ fs.writeFileSync('/work/.sp-agent-status', did + ' card(s) done, ' + failed + ' failed, ' + new Date().toISOString());
946
+ if (failed && !did) process.exit(1);
947
+ })().catch((e) => { console.error(String((e && e.stack) || e).slice(0, 1500)); process.exit(1); });
948
+ `;
949
+
950
+ /**
951
+ * Goals 103-105: a Group's factories. A factory is a shared agent for one kind of task: post a card with
952
+ * its label on the Group board and it does the work on the Group's own Macs (free there). Every member
953
+ * sees its runs; owners and admins set it up and edit its prompt. It starts in "practice": it drafts on
954
+ * the card and a person approves (approve()) before anything lands in the Group folder.
955
+ *
956
+ * const factories = new Factories(sp, { group, passphrase });
957
+ * const f = await factories.create({ name: "weekly-update", label: "weekly-update", model, prompt: "You write ..." });
958
+ * await new Board(sp, { group, passphrase }).post("Update for the Harbor project", { labels: ["weekly-update"] });
959
+ * (await factories.list())[0].awaitingApproval // drafts waiting for a person
960
+ * await factories.approve(f.id, taskId) // posts an "Apply:" card; the factory writes it to the folder
961
+ */
962
+ export class Factories {
963
+ constructor(sp, { group, passphrase } = {}) {
964
+ if (!group) throw new SmartyPantsError("Factories needs a group (the Group's id)", { code: "NO_GROUP" });
965
+ if (!passphrase) throw new SmartyPantsError("Factories needs the Group's passphrase (prompts are locked with it)", { code: "NO_PASSPHRASE" });
966
+ this.sp = sp; this.group = group; this.passphrase = passphrase;
967
+ }
968
+ /** Every factory in the Group, with its recent runs, prompt versions and drafts awaiting approval (unlocked). */
969
+ async list() {
970
+ const { factories } = await this.sp.request("GET", `/v1/factories?group=${encodeURIComponent(this.group)}`);
971
+ return factories.map((f) => ({ ...f, awaitingApproval: f.awaitingApproval.map((t) => {
972
+ const o = openText(t.result, this.passphrase);
973
+ return o.unreadable ? { ...t, result: null, unreadable: true } : { ...t, result: o.text };
974
+ }) }));
975
+ }
976
+ /**
977
+ * Set one up (Group owners and admins). Opens one workspace on the Group's Macs, writes the Group's
978
+ * passphrase into the agent's own files and saves it as the agent's starting point. Saves are kept on
979
+ * the site, so the passphrase is too, inside that save, until the Group's Macs hand it over instead.
980
+ * Then makes the saved agent with a model budget for each run, then the factory and its board watcher.
981
+ */
982
+ async create({ name, label, prompt, model, mode = "practice", inferenceBudgetUsd = 0.5, runSeconds = 300, waitSeconds = 300 } = {}) {
983
+ if (!name || !label || !prompt || !model) throw new SmartyPantsError("create needs name, label, prompt and model", { code: "MISSING_FIELDS" });
984
+ const setup = `factory-${name}-setup`.slice(0, 64);
985
+ const ws = await this.sp.workspace({ minutes: 10, waitSeconds, where: { group: this.group } });
986
+ try {
987
+ await ws.putFile(".sp-group-passphrase", this.passphrase);
988
+ await ws.save(setup);
989
+ } finally { await ws.close(); }
990
+ const source = FACTORY_RUNNER.replace("__FACTORY__", () => JSON.stringify({ group: this.group, name, label }));
991
+ const agent = await this.sp.request("POST", "/v1/cpu/agents", { name: `factory-${name}`.slice(0, 40), language: "node", source, from: setup,
992
+ where: { group: this.group }, inference: { budgetMicros: Math.round(inferenceBudgetUsd * 1e6) }, runSeconds, restart: "never" });
993
+ try {
994
+ return await this.sp.request("POST", "/v1/factories", { group: this.group, name, label, agent: agent.id, model, mode,
995
+ prompt: lockText(prompt, this.passphrase) });
996
+ } catch (error) {
997
+ // No factory, no agent: take back what was just made.
998
+ await this.sp.request("DELETE", `/v1/cpu/agents/${encodeURIComponent(agent.id)}`).catch(() => null);
999
+ await this.sp.request("DELETE", `/v1/cpu/saved/${encodeURIComponent(setup)}`).catch(() => null);
1000
+ throw error;
1001
+ }
1002
+ }
1003
+ addPrompt(id, text, { status = "testing" } = {}) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/prompts`, { text: lockText(text, this.passphrase), status }); }
1004
+ /** Make a version production (the one before is retired), testing, or retired. */
1005
+ setPrompt(id, version, status) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/prompts/${version}`, { status }); }
1006
+ /** The prompt this card would use (unlocked): its "prompt-vN" label's version, else production. */
1007
+ async prompt(id, { task } = {}) {
1008
+ const p = await this.sp.request("GET", `/v1/factories/${encodeURIComponent(id)}/prompt${task ? `?task=${encodeURIComponent(task)}` : ""}`);
1009
+ const o = openText(p.text, this.passphrase);
1010
+ return { ...p, text: o.text, ...(o.unreadable ? { unreadable: true } : {}) };
1011
+ }
1012
+ setMode(id, mode) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/mode`, { mode }); }
1013
+ approve(id, task) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/decide`, { task, decision: "approve" }); }
1014
+ reject(id, task, why) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/decide`, { task, decision: "reject", ...(why ? { why } : {}) }); }
1015
+ /**
1016
+ * Goal 105: the factory's test set. Each case is a sample card and what must be true of the answer:
1017
+ * { title, body?, checks: { contains?: [...], notContains?: [...], minWords?, maxWords? } }. Cases are
1018
+ * locked with the Group's passphrase; setTests replaces the whole set (Group owners and admins).
1019
+ */
1020
+ setTests(id, cases) { return this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/tests`, { cases: cases.map((c) => lockText(JSON.stringify(c), this.passphrase)) }); }
1021
+ async tests(id) {
1022
+ const { cases } = await this.sp.request("GET", `/v1/factories/${encodeURIComponent(id)}/tests`);
1023
+ return cases.map((c) => { const o = openText(c.text, this.passphrase); return o.unreadable ? { n: c.n, unreadable: true } : { n: c.n, ...JSON.parse(o.text) }; });
1024
+ }
1025
+ /** Does this answer pass this case's checks? Returns the checks it failed (empty: passed). */
1026
+ static check(answer, checks = {}) {
1027
+ const text = String(answer ?? "").replace(/^<!--.*?-->\n?/, ""), low = text.toLowerCase(), words = text.split(/\s+/).filter(Boolean).length;
1028
+ const failed = [];
1029
+ for (const w of checks.contains ?? []) if (!low.includes(String(w).toLowerCase())) failed.push(`missing "${w}"`);
1030
+ for (const w of checks.notContains ?? []) if (low.includes(String(w).toLowerCase())) failed.push(`has "${w}"`);
1031
+ if (checks.minWords && words < checks.minWords) failed.push(`${words} words, under ${checks.minWords}`);
1032
+ if (checks.maxWords && words > checks.maxWords) failed.push(`${words} words, over ${checks.maxWords}`);
1033
+ return failed;
1034
+ }
1035
+ /**
1036
+ * Run the test set against one prompt version: posts each case as a "test" card pinned to that version
1037
+ * (the factory answers it but never writes it anywhere), waits for the answers, scores them here, and
1038
+ * reports only the score to the site. Compare versions before making one production.
1039
+ */
1040
+ async runTests(id, { version, waitSeconds = 900, pollMs = 10_000 } = {}) {
1041
+ const factory = (await this.list()).find((f) => f.id === id);
1042
+ if (!factory) throw new SmartyPantsError(`factory ${id} not found`, { code: "FACTORY_NOT_FOUND" });
1043
+ const v = version ?? factory.prompts.find((p) => p.status === "production")?.version;
1044
+ const cases = (await this.tests(id)).filter((c) => !c.unreadable);
1045
+ if (!cases.length) throw new SmartyPantsError("this factory has no test set (setTests first)", { code: "NO_TESTS" });
1046
+ const board = new Board(this.sp, { group: this.group, passphrase: this.passphrase });
1047
+ const posted = [];
1048
+ for (const c of cases) {
1049
+ const card = await board.post(`Test ${c.n}: ${String(c.title).slice(0, 150)}`, { ...(c.body ? { body: c.body } : {}), labels: [factory.label, "test", `prompt-v${v}`] });
1050
+ posted.push({ c, id: card.id });
1051
+ }
1052
+ const deadline = Date.now() + waitSeconds * 1000;
1053
+ const results = new Map();
1054
+ while (results.size < posted.length && Date.now() < deadline) {
1055
+ for (const p of posted) {
1056
+ if (results.has(p.id)) continue;
1057
+ const t = await board.get(p.id);
1058
+ if (t.status === "done" || t.status === "failed") results.set(p.id, t);
1059
+ }
1060
+ if (results.size < posted.length) await sleep(pollMs);
1061
+ }
1062
+ const report = posted.map(({ c, id: taskId }) => {
1063
+ const t = results.get(taskId);
1064
+ if (!t) return { n: c.n, task: taskId, passed: false, failed: ["no answer in time"] };
1065
+ if (t.status !== "done") return { n: c.n, task: taskId, passed: false, failed: [`card failed: ${t.error}`] };
1066
+ const failed = Factories.check(t.result, c.checks);
1067
+ return { n: c.n, task: taskId, passed: failed.length === 0, failed };
1068
+ });
1069
+ const passed = report.filter((r) => r.passed).length;
1070
+ await this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/test-results`, { version: v, passed, total: report.length });
1071
+ return { version: v, passed, total: report.length, cases: report };
1072
+ }
1073
+ /**
1074
+ * Goal 106: a link that turns an outside row into a card for this factory. Paste it into a Notion database
1075
+ * automation ("Send webhook"); a new row becomes a card with the factory's label and the factory wakes.
1076
+ * Shown once; asking again makes a new link and the old one stops working.
1077
+ */
1078
+ async outsideCardLink(id) { const r = await this.sp.request("POST", `/v1/factories/${encodeURIComponent(id)}/hook`, {}); return { ...r, url: `${this.sp.baseUrl}${r.path}` }; }
1079
+ stopOutsideCards(id) { return this.sp.request("DELETE", `/v1/factories/${encodeURIComponent(id)}/hook`); }
1080
+ /** Removes the factory, and, when you made it, its agent and its saved setup (which holds the passphrase). */
1081
+ async remove(id) {
1082
+ const f = (await this.list().catch(() => [])).find((x) => x.id === id);
1083
+ const out = await this.sp.request("DELETE", `/v1/factories/${encodeURIComponent(id)}`);
1084
+ if (f) {
1085
+ const agents = (await this.sp.request("GET", "/v1/cpu/agents").catch(() => ({ agents: [] }))).agents ?? [];
1086
+ for (const a of agents.filter((a) => a.name === `factory-${f.name}`.slice(0, 40))) await this.sp.request("DELETE", `/v1/cpu/agents/${encodeURIComponent(a.id)}`).catch(() => null);
1087
+ await this.sp.request("DELETE", `/v1/cpu/saved/${encodeURIComponent(`factory-${f.name}-setup`.slice(0, 64))}`).catch(() => null);
1088
+ }
1089
+ return out;
1090
+ }
1091
+ }
1092
+
743
1093
  /** Lock text with a passphrase (AES-256-GCM, key from scrypt): "spbox1:" + base64(salt, iv, tag, text). */
744
1094
  export function lockText(text, passphrase) {
745
1095
  const { scryptSync, randomBytes, createCipheriv } = requireCrypto();
@@ -748,6 +1098,11 @@ export function lockText(text, passphrase) {
748
1098
  const data = Buffer.concat([cipher.update(String(text), "utf8"), cipher.final()]);
749
1099
  return `spbox1:${Buffer.concat([salt, iv, cipher.getAuthTag(), data]).toString("base64")}`;
750
1100
  }
1101
+ /** Opens locked text; text locked with another passphrase comes back as { text: null, unreadable: true } instead of throwing. */
1102
+ export function openText(text, passphrase) {
1103
+ if (typeof text !== "string" || !text.startsWith("spbox1:")) return { text };
1104
+ try { return { text: unlockText(text, passphrase) }; } catch { return { text: null, unreadable: true }; }
1105
+ }
751
1106
  export function unlockText(locked, passphrase) {
752
1107
  const { scryptSync, createDecipheriv } = requireCrypto();
753
1108
  const raw = Buffer.from(String(locked).slice(7), "base64");
@@ -808,6 +1163,22 @@ export class Workspace {
808
1163
  unlink(token) { return this.sp.request("DELETE", `${this.path}/links/${encodeURIComponent(token)}`); }
809
1164
  /** End the workspace. Its VM, files and disk are destroyed. */
810
1165
  close() { return this.sp.request("DELETE", this.path).catch(() => null); }
1166
+ /** A request that wakes a paused workspace (goal 97): while it pauses or resumes, wait and ask again. */
1167
+ async use(method, path, body, { waitSeconds = 600 } = {}) {
1168
+ const deadline = Date.now() + waitSeconds * 1000;
1169
+ for (;;) {
1170
+ try { return await this.sp.request(method, path, body); }
1171
+ catch (error) {
1172
+ const code = error?.body?.error;
1173
+ if (error?.status !== 409 || (code !== "WORKSPACE_RESUMING" && code !== "WORKSPACE_PAUSING") || Date.now() > deadline) throw error;
1174
+ await sleep(Math.max(this.pollMs, (error.body.retryAfterSeconds ?? 3) * 1000));
1175
+ }
1176
+ }
1177
+ }
1178
+ /** Pause now (pause: true workspaces): save the files, then stop. The next use wakes it. */
1179
+ pause() { return this.sp.request("POST", `${this.path}/pause`, {}); }
1180
+ /** Wake a paused workspace now, without waiting for its next use. */
1181
+ wake() { return this.sp.request("POST", `${this.path}/wake`, {}); }
811
1182
  async wait(requestId, waitSeconds, onOutput) {
812
1183
  const offsets = { stdout: 0, stderr: 0 };
813
1184
  const deadline = Date.now() + waitSeconds * 1000;
@@ -838,9 +1209,31 @@ export class Workspace {
838
1209
  if (job.state !== "done") throw new SmartyPantsError(`save ${name} failed: ${job.error}`, { code: job.error });
839
1210
  return job.result;
840
1211
  }
1212
+ /** Put the workspace to sleep: save /work, then end it, so nothing is billed while it sleeps.
1213
+ * Returns the save's name; wake it later, on any Mac, with sp.workspace({ from: name }). */
1214
+ async sleep(name, { waitSeconds = 600 } = {}) {
1215
+ const r = await this.sp.request("POST", `${this.path}/sleep`, name === undefined ? {} : { name });
1216
+ let job = r.saveJob;
1217
+ const deadline = Date.now() + waitSeconds * 1000;
1218
+ while (job.state === "running") {
1219
+ if (Date.now() > deadline) throw new SmartyPantsError(`sleep still saving after ${waitSeconds} s`, { code: "WAIT_TIMEOUT" });
1220
+ await sleep(this.pollMs);
1221
+ job = await this.sp.request("GET", `/v1/cpu/saved/jobs/${encodeURIComponent(job.id)}`);
1222
+ }
1223
+ if (job.state !== "done") throw new SmartyPantsError(`sleep failed, the workspace is still running: ${job.error}`, { code: job.error });
1224
+ return r.name;
1225
+ }
841
1226
  /** Run a program ("python", "node" or "sh"). onOutput(stream, text) gets output as it arrives. */
842
1227
  async run(language, source, { timeoutSeconds = 60, onOutput } = {}) {
843
- const { requestId } = await this.sp.request("POST", `${this.path}/exec`, { language, source, timeoutSeconds: Math.round(timeoutSeconds) });
1228
+ // Sent base64-encoded, so a web firewall never sees shell text; an older site gets it as text.
1229
+ const sourceB64 = Buffer.from(source, "utf8").toString("base64");
1230
+ let requestId;
1231
+ try {
1232
+ ({ requestId } = await this.use("POST", `${this.path}/exec`, { language, sourceB64, timeoutSeconds: Math.round(timeoutSeconds) }));
1233
+ } catch (error) {
1234
+ if (error?.status !== 400 || !JSON.stringify(error.body ?? "").includes("INVALID_SOURCE")) throw error;
1235
+ ({ requestId } = await this.use("POST", `${this.path}/exec`, { language, source, timeoutSeconds: Math.round(timeoutSeconds) }));
1236
+ }
844
1237
  const out = { stdout: "", stderr: "" };
845
1238
  const r = await this.wait(requestId, timeoutSeconds + 30, (stream, text) => { out[stream] += text; onOutput?.(stream, text); });
846
1239
  return { exitCode: r.exitCode ?? null, timedOut: r.timedOut ?? null, ...out };
@@ -849,7 +1242,7 @@ export class Workspace {
849
1242
  async putFile(path, content) {
850
1243
  const data = Buffer.from(content);
851
1244
  if (data.length <= 8 * 1024) {
852
- const { requestId } = await this.sp.request("POST", `${this.path}/files`, { path, contentBase64: data.toString("base64") });
1245
+ const { requestId } = await this.use("POST", `${this.path}/files`, { path, contentBase64: data.toString("base64") });
853
1246
  await this.wait(requestId, 60);
854
1247
  return;
855
1248
  }
@@ -857,7 +1250,7 @@ export class Workspace {
857
1250
  const waiting = [];
858
1251
  for (let offset = 0; offset < data.length; offset += PIECE) {
859
1252
  const contentBase64 = data.subarray(offset, offset + PIECE).toString("base64");
860
- waiting.push((await this.sp.request("POST", `${this.path}/files`, { path, offset, contentBase64 })).requestId);
1253
+ waiting.push((await this.use("POST", `${this.path}/files`, { path, offset, contentBase64 })).requestId);
861
1254
  if (waiting.length >= AHEAD) await this.wait(waiting.shift(), 120);
862
1255
  }
863
1256
  for (const id of waiting) await this.wait(id, 120);
@@ -865,13 +1258,13 @@ export class Workspace {
865
1258
  /** Read a file (up to 64 MiB) from the workspace, as a Buffer. */
866
1259
  async getFile(path) {
867
1260
  const q = encodeURIComponent(path);
868
- const { requestId } = await this.sp.request("GET", `${this.path}/files?path=${q}`);
1261
+ const { requestId } = await this.use("GET", `${this.path}/files?path=${q}`);
869
1262
  try {
870
1263
  return Buffer.from((await this.wait(requestId, 60)).contentBase64 ?? "", "base64");
871
1264
  } catch (error) {
872
1265
  if (error.code !== "TOO_LARGE") throw error;
873
1266
  }
874
- const piece = async offset => (await this.sp.request("GET", `${this.path}/files?path=${q}&offset=${offset}`)).requestId;
1267
+ const piece = async offset => (await this.use("GET", `${this.path}/files?path=${q}&offset=${offset}`)).requestId;
875
1268
  const first = await this.wait(await piece(0), 120);
876
1269
  const parts = [Buffer.from(first.contentBase64 ?? "", "base64")];
877
1270
  const offsets = [];