@nodii/dev 0.6.209 → 0.6.211

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.
@@ -0,0 +1,213 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DEV-PROCESS-1 must-item 1: the drill's stub runtime. A stub lane runs this
4
+ * in place of `claude`, so a drill uses no model and no account, whoever
5
+ * resumes its lane. O3 reuses it.
6
+ *
7
+ * drill-stub.js --script PATH [--resume SESSION_ID]
8
+ *
9
+ * It behaves as a lane runtime does where the harness can see it: it reads
10
+ * its prompt on stdin, prints Claude's stream-json records (a session id, an
11
+ * assistant turn with its token counts every tick, a final result), and starts
12
+ * the processes a real lane starts:
13
+ *
14
+ * child a plain child process
15
+ * nohup a `nohup` job, which ignores SIGHUP
16
+ * setsid a job in its own session and process group (what `setsid` does)
17
+ * heavy a job run through `nodii-dev heavy run --size light`, with the
18
+ * drill's own slot directory and limits file, never the machine's
19
+ *
20
+ * Each job's argv ends `nodii-drill-job <lane key> <role>`, so a scan of `ps`
21
+ * for the lane's key finds it without any list the stub keeps. Each writes its
22
+ * pid to <dir>/<role>.pid and a tick to <dir>/<role>.ticks every second.
23
+ *
24
+ * The script (JSON) says what this run does; every field may be left out:
25
+ *
26
+ * dir where pids, ticks and the end file live (default: the script's
27
+ * folder, then the lane key)
28
+ * jobs the roles to start (default: all four)
29
+ * cli the nodii-dev the heavy job runs (default: nodii-dev on PATH)
30
+ * tokens {"input": N, "output": N}: the usage each assistant tick reports
31
+ * silentAfterTicks N: after N ticks it writes nothing more and stays
32
+ * alive, as a hung runtime does (its jobs keep running)
33
+ * steps [{"afterTicks": N, "sh": "..."}]: at tick N each runs once, in
34
+ * order, as `/bin/sh -c sh` in the stub's cwd with STUB_SCRIPT_DIR
35
+ * set to the script's folder; its stdout and stderr go to the
36
+ * stub's stdout, then a line gives its exit code. The next tick
37
+ * waits for it; it never changes the ending.
38
+ * ending how the turn ends when no end file comes first:
39
+ * {"afterTicks": N, "code": C, "result": {...}}: a result record
40
+ * with these fields (is_error, api_error_status, terminal_reason,
41
+ * rate-limit status and reset), then exit C;
42
+ * {"afterTicks": N, "replay": "DIR"}: a recorded ending, printed as
43
+ * it was: DIR/stdout.jsonl line by line, then exit DIR/exit_code
44
+ * (an exit code of 128 + a signal ends it by that signal).
45
+ *
46
+ * --account PROFILE names the stub account the lane runs on (a drill folder,
47
+ * never a real profile); it appears in the init record and nowhere else.
48
+ *
49
+ * <dir>/end.json, written by the drill, ends the turn at once with the same
50
+ * fields as `ending`.
51
+ *
52
+ * Its jobs are left running when it ends, as a real runtime's background
53
+ * jobs are: stopping them is the harness's job, and the drill checks it.
54
+ */
55
+ import { spawn } from "node:child_process";
56
+ import { randomUUID } from "node:crypto";
57
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
58
+ import { dirname, isAbsolute, join, resolve } from "node:path";
59
+ import { setTimeout as delay } from "node:timers/promises";
60
+ import { fileURLToPath } from "node:url";
61
+
62
+ const TICK_MS = 1000;
63
+
64
+ /**
65
+ * A credential-shaped variable: a token, secret, password, key or PAT, and
66
+ * every GitHub, AWS, Figma, Anthropic, OpenAI, Claude, Codex, npm or Docker
67
+ * variable. The stub and its steps run without them: a step is a script's
68
+ * shell command, and a stub uses no account or service but Dev, which it
69
+ * reaches through its config file (NODII_DEV_CONFIG_PATH).
70
+ */
71
+ const CREDENTIAL = /(?:TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIALS?|API_?KEY|PRIVATE_?KEY|_PAT|AUTH)$|^(?:AWS_|GH_|GITHUB_|FIGMA|ANTHROPIC_|OPENAI_|CLAUDE_|CODEX_|NPM_|DOCKER_|GOOGLE_APPLICATION)/i;
72
+ export const stubEnv = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => !CREDENTIAL.test(name)));
73
+ export const ROLES = ["child", "nohup", "setsid", "heavy"];
74
+
75
+ /** The command line that runs one job: a loop that writes its pid and ticks. */
76
+ export function jobScript(dir, role) {
77
+ const pid = JSON.stringify(join(dir, `${role}.pid`));
78
+ const ticks = JSON.stringify(join(dir, `${role}.ticks`));
79
+ return `require("fs").writeFileSync(${pid}, process.pid + "\\n"); setInterval(() => require("fs").appendFileSync(${ticks}, Date.now() + "\\n"), ${TICK_MS});`;
80
+ }
81
+
82
+ /** How each job is started: the command, its arguments and its spawn options. */
83
+ export function jobSpawn(role, dir, { laneKey, cwd, env = process.env, node = process.execPath, cli = "nodii-dev" }) {
84
+ // The lane key and the role stand in the job's own argv, so `ps` names whose job it is.
85
+ const script = ["-e", jobScript(dir, role), "nodii-drill-job", laneKey, role];
86
+ const base = { cwd, env, stdio: "ignore" };
87
+ if (role === "child") return { command: node, args: script, options: base };
88
+ if (role === "nohup") return { command: "nohup", args: [node, ...script], options: base };
89
+ // Node's detached spawn calls setsid(2): the job leads a new session, out of the runtime's process group.
90
+ if (role === "setsid") return { command: node, args: script, options: { ...base, detached: true } };
91
+ if (role === "heavy") return {
92
+ command: cli,
93
+ args: ["heavy", "run", "--size", "light", "--", node, ...script],
94
+ options: { ...base, env: { ...env, HEAVY_SLOT_DIR: join(dir, "heavy-slots"), NODII_RESOURCE_LIMITS: join(dir, "limits.env"), HEAVY_SLOT_POLL_SEC: "1" } },
95
+ };
96
+ throw new Error(`unknown drill job ${role}`);
97
+ }
98
+
99
+ /** The drill's limits file: light slots that admit at once, so the heavy job never waits on this machine's queue. */
100
+ export const DRILL_LIMITS = "HEAVY_SLOTS=4\nHEAVY_MIN_AVAIL_GB=0\nHEAVY_STAGGER_SEC=0\nHEAVY_LANDING_RESERVE=0\nHEAVY_RECLAIM_MIN=0\nLIGHT_SLOTS=4\nLIGHT_MIN_AVAIL_GB=0\n";
101
+
102
+ /** The script's settings, with every default filled in. */
103
+ export function readScript(path, laneKey) {
104
+ if (typeof path !== "string" || !isAbsolute(path)) throw new Error("drill-stub needs --script with an absolute path");
105
+ const script = JSON.parse(readFileSync(path, "utf8"));
106
+ const jobs = Array.isArray(script.jobs) ? script.jobs : ROLES;
107
+ for (const role of jobs) if (!ROLES.includes(role)) throw new Error(`unknown drill job ${role}`);
108
+ return {
109
+ dir: script.dir ? resolve(dirname(path), script.dir) : join(dirname(path), laneKey),
110
+ jobs,
111
+ cli: typeof script.cli === "string" && script.cli ? script.cli : "nodii-dev",
112
+ tokens: { input: Number(script.tokens?.input) || 0, output: Number(script.tokens?.output) || 0 },
113
+ ending: script.ending ?? null,
114
+ silentAfterTicks: Number.isInteger(script.silentAfterTicks) ? script.silentAfterTicks : null,
115
+ steps: Array.isArray(script.steps) ? script.steps.filter((step) => Number.isInteger(step?.afterTicks) && typeof step.sh === "string") : [],
116
+ base: dirname(path),
117
+ };
118
+ }
119
+
120
+ /** The lines and exit code an ending prints: a result record, or a recorded run's own output. */
121
+ export function endingOutput(ending, sessionId, base) {
122
+ if (ending?.replay) {
123
+ const dir = resolve(base, ending.replay);
124
+ const lines = readFileSync(join(dir, "stdout.jsonl"), "utf8").split("\n").filter(Boolean);
125
+ const code = Number(readFileSync(join(dir, "exit_code"), "utf8").trim());
126
+ return { lines, code: Number.isInteger(code) ? code : 1 };
127
+ }
128
+ const code = Number.isInteger(ending?.code) ? ending.code : 0;
129
+ const record = { type: "result", subtype: code ? "error_during_execution" : "success", is_error: Boolean(code), session_id: sessionId, ...(ending?.result ?? {}) };
130
+ return { lines: [JSON.stringify(record)], code };
131
+ }
132
+
133
+ const argument = (argv, name) => {
134
+ const at = argv.indexOf(name);
135
+ return at >= 0 ? argv[at + 1] : undefined;
136
+ };
137
+
138
+ async function readStdin() {
139
+ let text = "";
140
+ process.stdin.setEncoding("utf8");
141
+ for await (const chunk of process.stdin) text += chunk;
142
+ return text;
143
+ }
144
+
145
+ export async function main({ argv = process.argv, env = process.env, cwd = process.cwd() } = {}) {
146
+ const laneKey = env.NODII_DEV_LANE_KEY ?? "drill";
147
+ const script = readScript(argument(argv, "--script"), laneKey);
148
+ const { dir } = script;
149
+ mkdirSync(dir, { recursive: true });
150
+ if (!existsSync(join(dir, "limits.env"))) writeFileSync(join(dir, "limits.env"), DRILL_LIMITS);
151
+ const print = (record) => process.stdout.write(`${typeof record === "string" ? record : JSON.stringify(record)}\n`);
152
+ const prompt = await readStdin();
153
+ const resumed = argument(argv, "--resume");
154
+ const sessionId = resumed ?? randomUUID();
155
+ writeFileSync(join(dir, "runtime.pid"), `${process.pid}\n`);
156
+ appendFileSync(join(dir, "runtime.starts"), `${Date.now()} ${process.pid} ${resumed ? "resume" : "fresh"}\n`);
157
+ print({ type: "system", subtype: "init", session_id: sessionId, model: "drill-stub", cwd, account: argument(argv, "--account") ?? null });
158
+ print({ type: "user", session_id: sessionId, message: { role: "user", content: prompt.slice(0, 2000) } });
159
+ // A resumed session's jobs are the first session's: the drill reads those.
160
+ if (!resumed) {
161
+ for (const role of script.jobs) {
162
+ const { command, args, options } = jobSpawn(role, dir, { laneKey, cwd, env, cli: script.cli });
163
+ const job = spawn(command, args, options);
164
+ job.on("error", (error) => appendFileSync(join(dir, `${role}.error`), `${error.message}\n`));
165
+ job.unref();
166
+ }
167
+ }
168
+ const endPath = join(dir, "end.json");
169
+ const scripted = script.ending && Number.isInteger(script.ending.afterTicks) ? script.ending : null;
170
+ // A step's output shares the stub's stdout, so what the stub printed is flushed first.
171
+ const flush = () => new Promise((done) => process.stdout.write("", done));
172
+ const runStep = async (step, number) => {
173
+ await flush();
174
+ const outcome = await new Promise((done) => {
175
+ const child = spawn("/bin/sh", ["-c", step.sh], { cwd, env: { ...stubEnv(env), STUB_SCRIPT_DIR: script.base }, stdio: ["ignore", 1, 1] });
176
+ child.once("error", (error) => done(`did not run: ${error.message}`));
177
+ child.once("close", (code, signal) => done(signal ? `exit signal ${signal}` : `exit ${code}`));
178
+ });
179
+ print(`drill step ${number} (afterTicks ${step.afterTicks}): ${outcome}`);
180
+ };
181
+ const ran = new Set();
182
+ const started = Date.now();
183
+ let ticks = 0;
184
+ let ending = null;
185
+ while (!ending) {
186
+ // Ticks keep to the clock; one that a step held up comes as soon as it is done.
187
+ await delay(Math.max(0, started + (ticks + 1) * TICK_MS - Date.now()));
188
+ ticks += 1;
189
+ const silent = script.silentAfterTicks !== null && ticks > script.silentAfterTicks;
190
+ if (!silent) print({ type: "assistant", session_id: sessionId, message: { model: "drill-stub", role: "assistant", content: [{ type: "text", text: `drill tick ${ticks}` }], usage: { input_tokens: script.tokens.input, output_tokens: script.tokens.output } } });
191
+ if (!silent) appendFileSync(join(dir, "runtime.ticks"), `${Date.now()}\n`);
192
+ for (const [index, step] of script.steps.entries()) {
193
+ if (ran.has(index) || ticks < step.afterTicks) continue;
194
+ ran.add(index);
195
+ await runStep(step, index + 1);
196
+ }
197
+ if (existsSync(endPath)) {
198
+ try { ending = JSON.parse(readFileSync(endPath, "utf8")); } catch { ending = {}; }
199
+ rmSync(endPath, { force: true });
200
+ } else if (scripted && ticks >= scripted.afterTicks) ending = scripted;
201
+ }
202
+ const { lines, code } = endingOutput(ending, sessionId, script.base);
203
+ for (const line of lines) print(line);
204
+ // A recorded run that a signal ended (exit 143 is SIGTERM) ends the same way here.
205
+ const signal = { 129: "SIGHUP", 130: "SIGINT", 137: "SIGKILL", 143: "SIGTERM" }[code];
206
+ if (signal) {
207
+ await new Promise((resolve) => process.stdout.write("", resolve));
208
+ process.kill(process.pid, signal);
209
+ }
210
+ process.exitCode = code;
211
+ }
212
+
213
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) await main();