@nodii/dev 0.6.208 → 0.6.210
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 +161 -38
- package/dist/accounts.js +17 -1
- package/dist/cli.js +74 -39
- package/dist/coordinator-items.js +31 -36
- package/dist/coordinator-watch.js +3 -1
- package/dist/core.js +72 -9
- package/dist/drill-stub.js +213 -0
- package/dist/drill.js +1081 -0
- package/dist/figma-scope.js +31 -6
- package/dist/flags.js +6 -4
- package/dist/harness.js +105 -2
- package/dist/impact.js +304 -12
- package/dist/lane-asks.js +22 -87
- package/dist/lane-messages.js +63 -1
- package/dist/lane-supervisor.js +17 -10
- package/dist/lane-switches.js +1 -1
- package/dist/lanes.js +26 -5
- package/dist/managed-version.js +90 -11
- package/dist/nodii-dev.js +2 -0
- package/dist/process-tree.js +18 -0
- package/dist/rulings.js +77 -0
- package/dist/runtime-launcher.js +41 -6
- package/dist/safety.js +3 -1
- package/dist/session-kind.js +164 -15
- package/dist/setup.js +1 -1
- package/dist/starting.js +2 -2
- package/dist/surface.js +10 -3
- package/dist/watchdog.js +108 -5
- package/package.json +1 -1
|
@@ -2,22 +2,23 @@ import { access, readFile, rm } from "node:fs/promises";
|
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
import { devRequest, query } from "./core.js";
|
|
5
|
-
import { laneAsksOn } from "./lane-asks.js";
|
|
6
5
|
import { cachedGet, laneReadCache } from "./read-cache.js";
|
|
7
6
|
|
|
8
7
|
/**
|
|
9
8
|
* hub-525 (MW1-37.2): the coordinator clears lane items first.
|
|
10
|
-
* Lanes ask
|
|
9
|
+
* Lanes ask for leeway and wait; Dev counts what waits on a machine's
|
|
11
10
|
* coordinator and says so in a response header on every answer to that
|
|
12
11
|
* coordinator. The CLI prints one line for it before each command's output,
|
|
13
12
|
* `coordinator items` lists the items, and the coordinator gate (a PreToolUse
|
|
14
13
|
* hook in the managed dispatcher) holds the coordinator's next nodii-dev write
|
|
15
|
-
* while
|
|
14
|
+
* while a leeway has waited over 10 minutes. Lane questions are retired
|
|
15
|
+
* (DEV-PROCESS-5, row 29b): an `ask` item Dev still serves is never listed,
|
|
16
|
+
* counted or gated, since no command clears it.
|
|
16
17
|
*/
|
|
17
18
|
|
|
18
19
|
export const LANE_ITEMS_HEADER = "x-dev-lane-items";
|
|
19
20
|
const ITEMS_PATH = "/api/v1/coordinator/items";
|
|
20
|
-
//
|
|
21
|
+
// Leeways gate after this long; waits and escalations never do.
|
|
21
22
|
export const GATE_AFTER_SECONDS = 10 * 60;
|
|
22
23
|
const GATE_CACHE_TTL_MS = 10_000;
|
|
23
24
|
const LINE_CACHE_KEY = "coordinator-items-line";
|
|
@@ -26,18 +27,19 @@ const DETAIL_TIMEOUT_MS = 3_000;
|
|
|
26
27
|
const GATE_TIMEOUT_MS = 5_000;
|
|
27
28
|
|
|
28
29
|
// kind, singular, plural: in the order the line names them.
|
|
29
|
-
const KINDS = [["leeway", "leeway", "leeways"], ["
|
|
30
|
+
const KINDS = [["leeway", "leeway", "leeways"], ["wait", "wait", "waits"], ["escalation", "escalation", "escalations"]];
|
|
31
|
+
// Lane questions are retired (DEV-PROCESS-5, row 29b): what Dev still counts as one is left out.
|
|
32
|
+
const RETIRED_KIND = "ask";
|
|
30
33
|
|
|
31
|
-
/** `total=3;leeway=1;
|
|
32
|
-
export function parseLaneItemsHeader(value
|
|
34
|
+
/** `total=3;leeway=1;wait=2;escalation=0;oldest=2040` as numbers, or null when there is nothing to say. */
|
|
35
|
+
export function parseLaneItemsHeader(value) {
|
|
33
36
|
if (typeof value !== "string" || !value.trim()) return null;
|
|
34
37
|
const fields = Object.fromEntries(value.split(";").map((part) => part.split("=").map((piece) => piece.trim())).filter(([name, number]) => name && /^\d+$/.test(number ?? "")).map(([name, number]) => [name, Number(number)]));
|
|
35
38
|
if (!Number.isInteger(fields.total) || fields.total <= 0) return null;
|
|
36
|
-
//
|
|
37
|
-
const
|
|
38
|
-
const total = fields.total - ((fields.ask ?? 0) - ask);
|
|
39
|
+
// Retired questions are not counted, and questions alone are nothing to say.
|
|
40
|
+
const total = fields.total - (fields[RETIRED_KIND] ?? 0);
|
|
39
41
|
if (total <= 0) return null;
|
|
40
|
-
return { total, leeway: fields.leeway ?? 0,
|
|
42
|
+
return { total, leeway: fields.leeway ?? 0, wait: fields.wait ?? 0, escalation: fields.escalation ?? 0, oldest: fields.oldest ?? 0 };
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
const age = (seconds) => {
|
|
@@ -47,10 +49,10 @@ const age = (seconds) => {
|
|
|
47
49
|
const deferred = (item, now) => Boolean(item?.deferredUntil) && Date.parse(item.deferredUntil) > now;
|
|
48
50
|
|
|
49
51
|
/** The one line a coordinator's command prints first. With no detail it is the counts alone. */
|
|
50
|
-
export function laneItemsLine(counts, items, {
|
|
52
|
+
export function laneItemsLine(counts, items, { now = Date.now() } = {}) {
|
|
51
53
|
const parts = KINDS.filter(([kind]) => counts[kind] > 0).map(([kind, one, many]) => {
|
|
52
54
|
const open = (Array.isArray(items) ? items : []).filter((item) => item?.kind === kind && item.laneKey && !deferred(item, now));
|
|
53
|
-
const names = open.slice(0, 5).map((item) =>
|
|
55
|
+
const names = open.slice(0, 5).map((item) => item.laneKey);
|
|
54
56
|
const more = open.length > 5 ? `, +${open.length - 5} more` : "";
|
|
55
57
|
return `${counts[kind]} ${counts[kind] === 1 ? one : many}${names.length ? ` (${names.join(", ")}${more})` : ""}`;
|
|
56
58
|
});
|
|
@@ -94,7 +96,7 @@ export async function observeLaneItems(header, { request = devRequest, cache = l
|
|
|
94
96
|
refreshing = false;
|
|
95
97
|
}
|
|
96
98
|
}
|
|
97
|
-
current = laneItemsLine(counts, detail?.items ?? null, {
|
|
99
|
+
current = laneItemsLine(counts, detail?.items ?? null, { now: now() });
|
|
98
100
|
} catch {
|
|
99
101
|
current = null;
|
|
100
102
|
}
|
|
@@ -110,28 +112,22 @@ export function takeLaneItemsLine() {
|
|
|
110
112
|
// ─── coordinator items ──────────────────────────────────────────────────────
|
|
111
113
|
|
|
112
114
|
/** `nodii-dev coordinator items [--machine NAME|ID]`: what lanes wait on, each with the command that clears it. */
|
|
113
|
-
export async function coordinatorItemsCommand(flags, { request = devRequest, now = Date.now
|
|
115
|
+
export async function coordinatorItemsCommand(flags, { request = devRequest, now = Date.now } = {}) {
|
|
114
116
|
const payload = await request("GET", `${ITEMS_PATH}${query({ machine: typeof flags.machine === "string" ? flags.machine : undefined })}`);
|
|
115
117
|
const data = payload.data ?? {};
|
|
116
|
-
//
|
|
117
|
-
const
|
|
118
|
-
const asksOff = asksOn ? "" : "Lane questions are off (NODII_DEV_LANE_ASKS): none is listed or counted.";
|
|
119
|
-
const items = (data.items ?? []).filter((item) => asksOn || item?.kind !== "ask");
|
|
118
|
+
// Retired questions (DEV-PROCESS-5, row 29b): none is listed or counted.
|
|
119
|
+
const items = (data.items ?? []).filter((item) => item?.kind !== RETIRED_KIND);
|
|
120
120
|
const counts = data.counts ?? {};
|
|
121
|
-
const total = Math.max(0, Number(data.total ?? 0) -
|
|
122
|
-
if (!total && !items.length) return { payload, human:
|
|
121
|
+
const total = Math.max(0, Number(data.total ?? 0) - Number(counts[RETIRED_KIND] ?? 0));
|
|
122
|
+
if (!total && !items.length) return { payload, human: "Nothing from lanes is waiting on you." };
|
|
123
123
|
const count = (kind, one, many) => `${counts[kind] ?? 0} ${(counts[kind] ?? 0) === 1 ? one : many}`;
|
|
124
|
-
const lines = [`${total} from lanes waiting on you (oldest ${age(data.oldestSeconds)}): ${
|
|
124
|
+
const lines = [`${total} from lanes waiting on you (oldest ${age(data.oldestSeconds)}): ${count("leeway", "leeway", "leeways")}, ${count("wait", "wait", "waits")}, ${count("escalation", "escalation", "escalations")}.`];
|
|
125
125
|
for (const item of items) {
|
|
126
126
|
const note = deferred(item, now()) || item.deferredUntil ? ` (deferred until ${item.deferredUntil})` : item.gates ? "" : " (counted, never gates)";
|
|
127
127
|
lines.push(`${item.kind}\t${item.laneKey}\t${age(item.ageSeconds)}\t${String(item.summary ?? "").replace(/\s+/g, " ").trim()}${note}`);
|
|
128
128
|
if (item.command) lines.push(` ${item.command}`);
|
|
129
129
|
}
|
|
130
|
-
lines.push(
|
|
131
|
-
asksOn
|
|
132
|
-
? `Asks and leeways older than ${GATE_AFTER_SECONDS / 60} minutes hold your next nodii-dev write: answer, grant, refuse, or defer with a reason (nodii-dev lane defer <id> --reason TEXT [--minutes N]).`
|
|
133
|
-
: `Leeways older than ${GATE_AFTER_SECONDS / 60} minutes hold your next nodii-dev write: grant, refuse, or defer with a reason (nodii-dev lane defer <id> --reason TEXT [--minutes N]). ${asksOff}`,
|
|
134
|
-
);
|
|
130
|
+
lines.push(`Leeways older than ${GATE_AFTER_SECONDS / 60} minutes hold your next nodii-dev write: grant, refuse, or defer with a reason (nodii-dev lane defer <leeway id> --reason TEXT [--minutes N]).`);
|
|
135
131
|
return { payload, human: lines.join("\n") };
|
|
136
132
|
}
|
|
137
133
|
|
|
@@ -154,9 +150,9 @@ export async function clearCoordinatorMarker(runId, { env = process.env } = {})
|
|
|
154
150
|
|
|
155
151
|
// Commands that never write lane or issue state in Dev, or that a coordinator must always be able to run.
|
|
156
152
|
const NEVER_GATED = new Set(["hook", "heavy", "run", "help", "doctor", "whoami", "config", "login", "logout", "rulebook", "rules", "inbox", "coordinator", "harness", "setup", "watchdog", "test", "repo", "state", "heartbeat", "next", "gather", "chrome", "receipt", "sync"]);
|
|
157
|
-
const READ_ACTIONS = new Set(["list", "show", "get", "diff", "versions", "status", "find", "parked", "audit", "usage", "accounts", "entries", "check", "board", "watch", "history", "timings", "behind", "resolve", "methodology", "lane-state", "overrides", "reviews", "waits"
|
|
153
|
+
const READ_ACTIONS = new Set(["list", "show", "get", "diff", "versions", "status", "find", "parked", "audit", "usage", "accounts", "entries", "check", "board", "watch", "history", "timings", "behind", "resolve", "methodology", "lane-state", "overrides", "reviews", "waits"]);
|
|
158
154
|
// The lane actions that clear an item, close out a lane or bring one back.
|
|
159
|
-
const LANE_ALLOWED = new Set(["
|
|
155
|
+
const LANE_ALLOWED = new Set(["defer", "resume", "close", "stop", "closeout"]);
|
|
160
156
|
// Lane actions with a subcommand: which of them write.
|
|
161
157
|
const LANE_SUB_WRITES = {
|
|
162
158
|
leeway: (sub) => !["grant", "refuse", "show", "list"].includes(sub),
|
|
@@ -196,7 +192,7 @@ export function gatedCommand(command) {
|
|
|
196
192
|
|
|
197
193
|
/**
|
|
198
194
|
* PreToolUse on Bash and AskUserQuestion, for a coordinator session. Denies a
|
|
199
|
-
* nodii-dev write while
|
|
195
|
+
* nodii-dev write while a leeway has waited over 10 minutes
|
|
200
196
|
* undeferred, naming each with the command that clears it. A question to the
|
|
201
197
|
* operator is never denied (MW1-116: an override or a lock change is asked the
|
|
202
198
|
* moment it arises): it passes with the same items named as context. Fails
|
|
@@ -219,17 +215,16 @@ export async function coordinatorGate(payload, deps = {}) {
|
|
|
219
215
|
} catch {
|
|
220
216
|
return { context: "lane items unread: Dev unreachable" };
|
|
221
217
|
}
|
|
222
|
-
//
|
|
223
|
-
const
|
|
224
|
-
const overdue = items.filter((item) => item?.gates === true && (asksOn || item.kind !== "ask") && Number(item.ageSeconds) > GATE_AFTER_SECONDS && !deferred(item, now));
|
|
218
|
+
// A retired question never holds the coordinator, since no command clears one.
|
|
219
|
+
const overdue = items.filter((item) => item?.gates === true && item.kind !== RETIRED_KIND && Number(item.ageSeconds) > GATE_AFTER_SECONDS && !deferred(item, now));
|
|
225
220
|
if (!overdue.length) return null;
|
|
226
221
|
const lines = [
|
|
227
222
|
...overdue.flatMap((item) => [` ${item.kind} ${item.laneKey} (${age(item.ageSeconds)}): ${String(item.summary ?? "").replace(/\s+/g, " ").trim()}`, ...(item.command ? [` ${item.command}`] : [])]),
|
|
228
|
-
"Defer one with a reason: nodii-dev lane defer <id> --reason TEXT [--minutes N]. List them: nodii-dev coordinator items.",
|
|
223
|
+
"Defer one with a reason: nodii-dev lane defer <leeway id> --reason TEXT [--minutes N]. List them: nodii-dev coordinator items.",
|
|
229
224
|
];
|
|
230
225
|
const waited = `${overdue.length} lane item${overdue.length === 1 ? " has" : "s have"} waited over ${GATE_AFTER_SECONDS / 60} minutes.`;
|
|
231
226
|
// MW1-116: the operator question goes through; the coordinator is told what still waits.
|
|
232
227
|
if (tool === "AskUserQuestion")
|
|
233
|
-
return { context: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Your question to the operator is not held (MW1-116);
|
|
234
|
-
return { deny: [`nodii-dev coordinator gate (MW1-37.2): ${waited}
|
|
228
|
+
return { context: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Your question to the operator is not held (MW1-116); grant, refuse or defer each right after it:`, ...lines].join("\n") };
|
|
229
|
+
return { deny: [`nodii-dev coordinator gate (MW1-37.2): ${waited} Grant, refuse or defer each before \`${what}\`:`, ...lines].join("\n") };
|
|
235
230
|
}
|
|
@@ -664,9 +664,11 @@ export async function watchServicePath({ home = homedir(), os = platform(), exec
|
|
|
664
664
|
* the keychain).
|
|
665
665
|
*/
|
|
666
666
|
export async function installWatch({
|
|
667
|
-
home = homedir(), uid = process.getuid?.(), os = platform(), env = process.env, runtime = process.execPath, entry =
|
|
667
|
+
home = homedir(), uid = process.getuid?.(), os = platform(), env = process.env, runtime = process.execPath, entry = null,
|
|
668
668
|
configFile = configPath(), execute = execFile, config = readConfig, request = devRequest, requireCoordinator = true,
|
|
669
669
|
} = {}) {
|
|
670
|
+
// The daemon runs the managed copy `harness update` keeps current (CLI-15).
|
|
671
|
+
entry ??= (await (await import("./managed-version.js")).managedEntry()) ?? resolve(process.argv[1]);
|
|
670
672
|
if (os !== "darwin" && os !== "linux")
|
|
671
673
|
throw new CliError("WATCH_UNSUPPORTED", `coordinator watch installs with launchd on macOS and with a systemd user service on Linux; ${os} is not supported.`, 2);
|
|
672
674
|
if (requireCoordinator) {
|
package/dist/core.js
CHANGED
|
@@ -4,7 +4,7 @@ import { chmod, lstat, mkdir, readFile, rename, rm, writeFile } from "node:fs/pr
|
|
|
4
4
|
import { homedir, platform } from "node:os";
|
|
5
5
|
import { basename, dirname, join } from "node:path";
|
|
6
6
|
|
|
7
|
-
export const VERSION = "0.6.
|
|
7
|
+
export const VERSION = "0.6.210";
|
|
8
8
|
export const configPath = () =>
|
|
9
9
|
process.env.NODII_DEV_CONFIG_PATH ??
|
|
10
10
|
join(homedir(), ".config/nodii-dev/config.json");
|
|
@@ -166,6 +166,57 @@ const refusalMessage = (raw) => {
|
|
|
166
166
|
}
|
|
167
167
|
};
|
|
168
168
|
|
|
169
|
+
// O3 item 4 (DEC-0569): what Dev's requests cost this machine. Each request
|
|
170
|
+
// adds {n, ms} to one small JSON beside the config (the nodii-dev directory
|
|
171
|
+
// lane configs under agents/ share), bucketed by what sent it: a hook, a
|
|
172
|
+
// Gather, or any other command. The sweep's machine report carries it, so it
|
|
173
|
+
// costs no Dev call. Best effort: no fsync, and a failed write is dropped.
|
|
174
|
+
export const CALL_COST_SOURCES = ["hook", "gather", "command"];
|
|
175
|
+
export function callCostPath(path = configPath()) {
|
|
176
|
+
const dir = dirname(path);
|
|
177
|
+
return join(basename(dir) === "agents" ? dirname(dir) : dir, "call-cost.json");
|
|
178
|
+
}
|
|
179
|
+
let callSource = "command";
|
|
180
|
+
/** What the calls of this process count as, from its argv. */
|
|
181
|
+
export function callSourceFor(argv = []) {
|
|
182
|
+
if (argv[0] === "hook") return "hook";
|
|
183
|
+
if (argv[0] === "gather" || (argv[0] === "lane" && argv[1] === "gather")) return "gather";
|
|
184
|
+
return "command";
|
|
185
|
+
}
|
|
186
|
+
export function setCallSource(source) {
|
|
187
|
+
callSource = CALL_COST_SOURCES.includes(source) ? source : "command";
|
|
188
|
+
}
|
|
189
|
+
const emptyCallCost = (since) => ({ since, calls: Object.fromEntries(CALL_COST_SOURCES.map((k) => [k, { n: 0, ms: 0 }])) });
|
|
190
|
+
/** The counter file, or null when there is none or it does not parse. */
|
|
191
|
+
export async function readCallCost(path = callCostPath()) {
|
|
192
|
+
try {
|
|
193
|
+
const saved = JSON.parse(await readFile(path, "utf8"));
|
|
194
|
+
if (typeof saved?.since !== "string" || !saved.calls || typeof saved.calls !== "object") return null;
|
|
195
|
+
const out = emptyCallCost(saved.since);
|
|
196
|
+
for (const k of CALL_COST_SOURCES) {
|
|
197
|
+
const n = Number(saved.calls[k]?.n), ms = Number(saved.calls[k]?.ms);
|
|
198
|
+
if (Number.isSafeInteger(n) && n >= 0 && Number.isFinite(ms) && ms >= 0) out.calls[k] = { n, ms };
|
|
199
|
+
}
|
|
200
|
+
return out;
|
|
201
|
+
} catch {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
// The counts are best effort: two processes that read the file at once each
|
|
206
|
+
// write their own +1, and one of them is lost. A weekly number tolerates that;
|
|
207
|
+
// a lock on every Dev request would cost more than the count is worth.
|
|
208
|
+
export async function recordCallCost(ms, { source = callSource, path = callCostPath(), now = () => new Date() } = {}) {
|
|
209
|
+
try {
|
|
210
|
+
const cost = (await readCallCost(path)) ?? emptyCallCost(now().toISOString());
|
|
211
|
+
const bucket = cost.calls[CALL_COST_SOURCES.includes(source) ? source : "command"];
|
|
212
|
+
bucket.n += 1;
|
|
213
|
+
bucket.ms = Math.round((bucket.ms + Math.max(0, ms)) * 10) / 10;
|
|
214
|
+
const temporary = `${path}.${process.pid}.${randomBytes(4).toString("hex")}`;
|
|
215
|
+
await writeFile(temporary, JSON.stringify(cost), { mode: 0o600 });
|
|
216
|
+
await rename(temporary, path);
|
|
217
|
+
} catch { /* best effort: never fails a request */ }
|
|
218
|
+
}
|
|
219
|
+
|
|
169
220
|
async function devFetchOnce(method, path, bodyText, contentType, accept, extra = {}, signal) {
|
|
170
221
|
const first = await devFetchSend(method, path, bodyText, contentType, accept, extra, signal);
|
|
171
222
|
if (first.response.status !== 429) return first;
|
|
@@ -203,10 +254,13 @@ async function devFetchSend(method, path, bodyText, contentType, accept, extra =
|
|
|
203
254
|
let refreshed = false;
|
|
204
255
|
let adopted = false;
|
|
205
256
|
for (;;) {
|
|
206
|
-
|
|
257
|
+
// The CLI's version rides every Dev request (O3 item 7). Not x-nodii-*: the
|
|
258
|
+
// edge strips those and the hub reads them as gateway claims.
|
|
259
|
+
const headers = { accept, "x-dev-cli-version": VERSION, ...extra };
|
|
207
260
|
if (bodyText !== undefined) headers["content-type"] = contentType;
|
|
208
261
|
Object.assign(headers, await wait(auth.headers({ method, path, body: bodyText ?? "" })));
|
|
209
262
|
let response;
|
|
263
|
+
const started = performance.now();
|
|
210
264
|
try {
|
|
211
265
|
response = await wait(fetch(url, { method, headers, body: bodyText, signal }));
|
|
212
266
|
} catch (error) {
|
|
@@ -215,6 +269,7 @@ async function devFetchSend(method, path, bodyText, contentType, accept, extra =
|
|
|
215
269
|
throw new CliError("DEV_UNREACHABLE", `Cannot reach Dev at ${new URL(url).origin}: ${error.message}`);
|
|
216
270
|
}
|
|
217
271
|
const raw = await wait(response.text());
|
|
272
|
+
await recordCallCost(performance.now() - started);
|
|
218
273
|
if (response.status !== 401 || typeof auth.refreshStale !== "function" || !staleCode(raw)) return { response, raw };
|
|
219
274
|
if (refreshed) return { response, raw };
|
|
220
275
|
// A cached token that is stale too is not adopted twice: the next one is refreshed.
|
|
@@ -525,16 +580,24 @@ export async function devExchange(method, path, bodyText, { contentType = "appli
|
|
|
525
580
|
if (!response.ok || payload.error === true) {
|
|
526
581
|
const waitMs = response.status === 429 ? retryAfterMs(response.headers?.get?.("retry-after")) : null;
|
|
527
582
|
const after = waitMs === null ? "" : ` Dev asks to wait ${Math.ceil(waitMs / 1000)} s before trying again.`;
|
|
528
|
-
throw
|
|
529
|
-
payload.code ?? `HTTP_${response.status}`,
|
|
530
|
-
`${payload.message ?? `Dev returned HTTP ${response.status}`}${after}`,
|
|
531
|
-
1,
|
|
532
|
-
payload.details,
|
|
533
|
-
);
|
|
583
|
+
throw devError(payload, response.status, after);
|
|
534
584
|
}
|
|
535
585
|
return { status: response.status, payload };
|
|
536
586
|
}
|
|
537
587
|
|
|
588
|
+
/**
|
|
589
|
+
* Dev's refusal as a CliError. VERSION_BELOW_FLOOR (426, O3 item 7, DEC-0569,
|
|
590
|
+
* MW5-8.1): this CLI is below Dev's floor, so the write was refused; Dev's
|
|
591
|
+
* message names the floor and the version, and the fix is printed under it
|
|
592
|
+
* (exit 2: the caller must act).
|
|
593
|
+
*/
|
|
594
|
+
export function devError(payload, status, after = "") {
|
|
595
|
+
const code = payload?.code ?? `HTTP_${status}`;
|
|
596
|
+
const message = `${payload?.message ?? `Dev returned HTTP ${status}`}${after}`;
|
|
597
|
+
if (code === "VERSION_BELOW_FLOOR") return new CliError(code, `${message}\nFix: nodii-dev harness update`, 2, payload.details);
|
|
598
|
+
return new CliError(code, message, 1, payload?.details);
|
|
599
|
+
}
|
|
600
|
+
|
|
538
601
|
export async function devRawRequest(method, path, bodyText, contentType = "application/json", options = {}) {
|
|
539
602
|
return (await devExchange(method, path, bodyText, { ...options, contentType })).payload;
|
|
540
603
|
}
|
|
@@ -545,7 +608,7 @@ export async function devTextRequest(method, path) {
|
|
|
545
608
|
if (response.ok) return raw;
|
|
546
609
|
let payload = {};
|
|
547
610
|
try { payload = JSON.parse(raw); } catch { payload = { message: raw }; }
|
|
548
|
-
throw
|
|
611
|
+
throw devError(payload, response.status);
|
|
549
612
|
}
|
|
550
613
|
|
|
551
614
|
export const devRequest = (method, path, body, options) =>
|
|
@@ -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();
|