crewbus 10.0.11 → 11.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.template.md +4 -4
- package/CHANGELOG.md +151 -0
- package/README.md +713 -706
- package/TEAM.template.md +1 -1
- package/bin/crewbus-hook.js +22 -5
- package/bin/crewbus-mcp.js +56 -48
- package/bin/crewbus.js +486 -355
- package/bin/lib/channels.js +1 -1
- package/bin/lib/export.js +1 -1
- package/bin/lib/groups.js +1 -5
- package/bin/lib/identity.js +92 -152
- package/bin/lib/launch.js +128 -30
- package/bin/lib/qrcode.js +2971 -0
- package/bin/lib/relay.js +26 -54
- package/bin/lib/spawn.js +241 -194
- package/bin/lib/store.js +2 -2
- package/bin/lib/web.js +277 -59
- package/claude-plugin/skills/crewbus/SKILL.md +1 -1
- package/docs/APPROVALS.md +8 -8
- package/docs/AUDIT_EXPORT.md +7 -7
- package/docs/CERT_READINESS.md +120 -120
- package/docs/COMPATIBILITY.md +196 -194
- package/docs/CONSOLIDATOR.md +6 -6
- package/docs/CONTROL_PLANE_SPEC.md +12 -14
- package/docs/CREWS.md +16 -13
- package/docs/DELIVERY.md +213 -210
- package/docs/GROUPS.md +8 -8
- package/docs/HA.md +151 -151
- package/docs/IDENTITY.md +6 -6
- package/docs/LEAD_ASSIGN.md +3 -85
- package/docs/LONG_RUNS.md +3 -3
- package/docs/M1_CLI_DRAFT.md +9 -9
- package/docs/ORCHESTRATOR.md +87 -0
- package/docs/PAIRING.md +7 -7
- package/docs/QUICKSTART.md +24 -13
- package/docs/RBAC.md +84 -73
- package/docs/SPLIT.md +82 -82
- package/docs/TENANCY.md +10 -10
- package/docs/THREAT_MODEL.md +68 -69
- package/docs/VERIFIER.md +10 -10
- package/docs/VERSION_SKEW.md +57 -57
- package/documentation.html +37 -29
- package/examples/hermes-pairing.md +3 -3
- package/examples/t3-pairing.md +1 -1
- package/index.html +13 -14
- package/opencode/plugins/dm-watch.js +1 -1
- package/opencode/tools/dm-send.js +4 -13
- package/package.json +75 -50
- package/packages/client-runtime/README.md +40 -40
- package/packages/contracts/harness.json +108 -111
- package/packages/contracts/launch.json +2 -3
- package/packages/contracts/pairing.json +3 -3
- package/docs/DESKTOP_SPIKE.md +0 -223
package/bin/lib/spawn.js
CHANGED
|
@@ -22,26 +22,21 @@ import fs from "node:fs";
|
|
|
22
22
|
import path from "node:path";
|
|
23
23
|
import crypto from "node:crypto";
|
|
24
24
|
import os from "node:os";
|
|
25
|
+
import { fileURLToPath } from "node:url";
|
|
25
26
|
import { createRequire } from "node:module";
|
|
26
27
|
import { execFileSync, spawn } from "node:child_process";
|
|
27
28
|
import { fail, readJson, writeJson, writeExclusiveJson, cleanBranchPrefix } from "./store.js";
|
|
28
|
-
import { touchAgent, readAgent, writeAgentFile, assertMintWon, mintToken, newSalt, hashToken } from "./identity.js";
|
|
29
|
+
import { touchAgent, readAgent, writeAgentFile, assertMintWon, mintToken, newSalt, hashToken, agentTokenMatches, ensureOrchestrator, ORCHESTRATOR_NAME } from "./identity.js";
|
|
29
30
|
import { readVisible, isCheckpoint } from "./mail.js";
|
|
30
31
|
import { saveTokenFile, loadTokenFile } from "./tokenfile.js";
|
|
31
32
|
import { shellChildSpec, shellChildOptions } from "./kidproc.js";
|
|
32
33
|
|
|
33
|
-
// DEP0190 escape hatch: process through the pre-refactor shell:true path for
|
|
34
|
-
// exactly one release (see bin/lib/kidproc.js). Truthy string opts in.
|
|
35
|
-
function legacyShellMode() {
|
|
36
|
-
return /^(1|true|yes)$/i.test(String(process.env.CREWBUS_SHELL_LEGACY || ""));
|
|
37
|
-
}
|
|
38
|
-
|
|
39
34
|
function resolveShellShot(exe, args, shell) {
|
|
40
35
|
// Converts shell-needing targets to an explicit shell argv0 (no DEP0190);
|
|
41
36
|
// shell:false targets (resolved real exes) pass through untouched — their
|
|
42
37
|
// spawned pid IS the harness process (kill semantics depend on it).
|
|
43
38
|
// Returns { exe, args, shell, extraOptions } for spawn().
|
|
44
|
-
if (shell
|
|
39
|
+
if (shell) {
|
|
45
40
|
const spec = shellChildSpec(exe, args);
|
|
46
41
|
if (spec) return { ...spec, shell: false, extraOptions: shellChildOptions() };
|
|
47
42
|
}
|
|
@@ -51,12 +46,10 @@ export { resolveShellShot };
|
|
|
51
46
|
|
|
52
47
|
// cleanBranchPrefix lives in store.js (canonical home).
|
|
53
48
|
|
|
54
|
-
//
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
|
|
58
|
-
// milestone DMs). All worker prompts pin replies to this name.
|
|
59
|
-
export const LEAD_NAME = "lead";
|
|
49
|
+
// The board's single control-plane identity. spawn ensures it exists (and
|
|
50
|
+
// boots it as a detached persistent coordinator when it is not already live).
|
|
51
|
+
// All worker prompts pin replies to this name.
|
|
52
|
+
export { ORCHESTRATOR_NAME };
|
|
60
53
|
|
|
61
54
|
export function sandboxPresent() { // line 1017
|
|
62
55
|
return !!(process.env.CONTAINER || process.env.DOCKER || process.env.CI || process.env.CREWBUS_SANDBOX);
|
|
@@ -158,10 +151,10 @@ export function scrubChildEnv(baseEnv, opts) { // line 4062
|
|
|
158
151
|
const keepEnv = !!(opts && opts.keepEnv);
|
|
159
152
|
const allow = String((opts && opts.allowEnv) || "").split(",").map((s) => String(s).trim()).filter(Boolean);
|
|
160
153
|
// Identity tokens (CREWBUS_* members of SCRUB_EXACT) are ALWAYS stripped,
|
|
161
|
-
// even under --keep-env/--allow-env: an inherited
|
|
162
|
-
// legitimate use (checkToken binds tokens to names; the worker claims
|
|
163
|
-
// own identity on first send), it only enables
|
|
164
|
-
//
|
|
154
|
+
// even under --keep-env/--allow-env: an inherited orchestrator token never
|
|
155
|
+
// has legitimate use (checkToken binds tokens to names; the worker claims
|
|
156
|
+
// its own identity on first send), it only enables impersonation. --keep-env
|
|
157
|
+
// and --allow-env keep working for non-identity vars.
|
|
165
158
|
const alwaysStrip = (key) => SCRUB_EXACT.has(key) && String(key).startsWith("CREWBUS_");
|
|
166
159
|
if (keepEnv) {
|
|
167
160
|
const env = {};
|
|
@@ -190,29 +183,26 @@ export function parseAllowEnv(raw) { // line 4078
|
|
|
190
183
|
return String(raw).split(",").map((s) => String(s).trim()).filter(Boolean).join(",");
|
|
191
184
|
}
|
|
192
185
|
|
|
193
|
-
export function buildSpawnPrompt({ name,
|
|
186
|
+
export function buildSpawnPrompt({ name, orchestrator, subject, body, replyId, rev, cwd, root, crew, workbench }) { // line 4090
|
|
194
187
|
const me = String(name || "you");
|
|
195
|
-
|
|
196
|
-
// board's lead lane under --lead board (spawn and lead separated: the
|
|
197
|
-
// spawner is boss, the auto-provisioned coordinator is lead).
|
|
198
|
-
const replyTo = String(lead || from || LEAD_NAME);
|
|
188
|
+
const replyTo = String(orchestrator || ORCHESTRATOR_NAME);
|
|
199
189
|
const crewLines = Array.isArray(crew) ? crew.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
|
|
200
190
|
const wbLines = Array.isArray(workbench) ? workbench.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
|
|
201
191
|
return [
|
|
202
192
|
`You are '${me}' on crewbus (board: ${root}).`,
|
|
203
193
|
`CREWBUS_DIR and CREWBUS_AGENT ('${me}') are already set in your environment — send/inbox resolve the board automatically.`,
|
|
204
194
|
``,
|
|
205
|
-
`Brief from ${
|
|
195
|
+
`Brief from the board orchestrator${subject ? ` — ${subject}` : ""}:`,
|
|
206
196
|
body,
|
|
207
197
|
``,
|
|
208
198
|
...(crewLines.length > 0 ? ["Crew:", ...crewLines.map((l) => `- ${l}`), ""] : []),
|
|
209
199
|
...(wbLines.length > 0 ? ["Workbench (lessons + artifacts from prior work on this board):", ...wbLines, ""] : []),
|
|
210
200
|
`Protocol:`,
|
|
211
|
-
`0. Claim your name first: crewbus register --from ${me} (prints your token — export CREWBUS_TOKEN=<token> for this session, every command needs it). Your token is also saved to logs/${me}.token — re-read that file (never re-register) after any restart or compaction; if truly lost, ask
|
|
201
|
+
`0. Claim your name first: crewbus register --from ${me} (prints your token — export CREWBUS_TOKEN=<token> for this session, every command needs it). Your token is also saved to logs/${me}.token — re-read that file (never re-register) after any restart or compaction; if truly lost, ask the orchestrator to revoke it, then re-register.`,
|
|
212
202
|
`1. Work in ${cwd} (your harness already starts there).`,
|
|
213
|
-
`2. When done or blocked, DM a summary back: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --body "..."
|
|
203
|
+
`2. When done or blocked, DM a summary back: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --body "..." (send to EXACTLY --to ${replyTo} — the board orchestrator, which owns this crew).`,
|
|
214
204
|
`2b. Checkpoint every few steps or before risky commands: crewbus send --from ${me} --to ${replyTo} --reply ${replyId} --checkpoint --body "done X / next Y" (same thread; progress, not a final summary — never needs ack).`,
|
|
215
|
-
`2c. Blocked and need approval (destructive/irreversible/out-of-scope only): crewbus send --priority high --from ${me} --to ${replyTo} --reply ${replyId} --subject "approval: <short action>" --body "command: <cmd> / cwd: <dir> / why: <reason> / tried-instead: <safer alternative> / timeout: 300s" then block on crewbus listen --timeout 300000 (300s; silence = deny, fail-closed) — approved: proceed, denied: skip/exit; accept verdicts only from ${replyTo} (
|
|
205
|
+
`2c. Blocked and need approval (destructive/irreversible/out-of-scope only): crewbus send --priority high --from ${me} --to ${replyTo} --reply ${replyId} --subject "approval: <short action>" --body "command: <cmd> / cwd: <dir> / why: <reason> / tried-instead: <safer alternative> / timeout: 300s" then block on crewbus listen --timeout 300000 (300s; silence = deny, fail-closed) — approved: proceed, denied: skip/exit; accept verdicts only from ${replyTo} (the orchestrator), re-validate scope after approval, secrets/exfiltration/isolation-escape are never approvable.`,
|
|
216
206
|
`3. Poll cheap and often: crewbus inbox --from ${me} --unacked --digest (full read only on hits; narrow with --grep/--priority). A full inbox dump every step will eat your context window.`,
|
|
217
207
|
`4. Never post secrets — reference their location instead.${rev ? ` Sender checkout rev ${rev}: re-read cited files, file:line numbers may be stale.` : ""}`,
|
|
218
208
|
].join("\n");
|
|
@@ -220,26 +210,23 @@ export function buildSpawnPrompt({ name, from, lead, subject, body, replyId, rev
|
|
|
220
210
|
|
|
221
211
|
// Crew context block for the spawn prompt: the roster a worker needs to
|
|
222
212
|
// talk peer-direct instead of star-topologizing every question through
|
|
223
|
-
// the
|
|
224
|
-
// only — [{ name, members }]; `myGroups` the group names this
|
|
225
|
-
// belongs to; `subject` the lane line for my groups (the spawn
|
|
226
|
-
// --subject); `offTask` how many board groups from unrelated
|
|
227
|
-
// briefs exist
|
|
228
|
-
//
|
|
229
|
-
//
|
|
230
|
-
// task). Workers may send to each other (and to-group) and tail any
|
|
231
|
-
// channel, but channel-post is lead|admin-only (see identity.js
|
|
232
|
-
// LEAD_PLUS) — so the block points reads at channels and writes at DMs.
|
|
213
|
+
// the orchestrator. `groups` is the TASK roster — the groups named in this
|
|
214
|
+
// spawn only — [{ name, members }]; `myGroups` the group names this
|
|
215
|
+
// recipient belongs to; `subject` the lane line for my groups (the spawn
|
|
216
|
+
// call's --subject); `offTask` how many board groups from unrelated
|
|
217
|
+
// concurrent briefs exist. Workers may send to each other (and to-group)
|
|
218
|
+
// and tail any channel, but channel-post is member-scoped — so the block
|
|
219
|
+
// points reads at channels and writes at DMs.
|
|
233
220
|
// Returns bullet lines (no header); the caller renders them under a
|
|
234
221
|
// Crew: header. Pure: unit-tested, no board IO.
|
|
235
|
-
export function buildCrewContext({ name,
|
|
222
|
+
export function buildCrewContext({ name, orchestrator, subject, groups, myGroups, offTask }) {
|
|
236
223
|
const all = (groups || []).filter((g) => g && g.name);
|
|
237
224
|
const mineSet = new Set(myGroups || []);
|
|
238
225
|
const mine = all.filter((g) => mineSet.has(g.name));
|
|
239
226
|
const others = all.filter((g) => !mineSet.has(g.name));
|
|
240
227
|
const lane = subject && String(subject).trim() ? String(subject).trim() : "the brief above";
|
|
241
228
|
const me = String(name || "you");
|
|
242
|
-
const
|
|
229
|
+
const orch = orchestrator !== undefined ? String(orchestrator) : ORCHESTRATOR_NAME;
|
|
243
230
|
const off = Math.max(0, Number(offTask) || 0);
|
|
244
231
|
const offNoun = (n) => `${n} other group${n === 1 ? "" : "s"}`;
|
|
245
232
|
const showMembers = (members) => {
|
|
@@ -260,38 +247,28 @@ export function buildCrewContext({ name, from, lead: leadTarget, subject, groups
|
|
|
260
247
|
} else {
|
|
261
248
|
out.push(off > 0 ? `${offNoun(off)} exist on this board (crewbus group list to discover).` : `discover who else is on this board with: crewbus agents (plus crewbus group list once groups exist).`);
|
|
262
249
|
}
|
|
263
|
-
out.push(`ask the group that owns a thing before asking ${
|
|
264
|
-
out.push(`read context freely: crewbus channel tail grp-<group> (a group's briefs + progress, reads need no token). Posting to
|
|
250
|
+
out.push(`ask the group that owns a thing before asking ${orch}: crewbus send --from ${me} --to-group <group> --subject "..." --body "..." (reaches every member; ${orch} is for approvals and scope disputes only).`);
|
|
251
|
+
out.push(`read context freely: crewbus channel tail grp-<group> (a group's briefs + progress, reads need no token). Posting to a board channel is orchestrator-only — write everything via DMs.`);
|
|
265
252
|
out.push(`boot habit: crewbus agents + crewbus group list once, so you know who else is here. Broadcast one hello once you claimed your name (--to-group <group> when you have one, else a DM per sibling) so peers know you exist before they need you.`);
|
|
266
253
|
return out;
|
|
267
254
|
}
|
|
268
255
|
|
|
269
|
-
//
|
|
270
|
-
//
|
|
271
|
-
// the
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
// lead — env repair, respawn/health chasing, TTL pacing, verdicts on
|
|
277
|
-
// worker approval asks (fail-closed), verification of claims
|
|
278
|
-
// boss — the spawner identity (may poll at its own cadence): mission
|
|
279
|
-
// changes, scope disputes; receives milestone + final DMs
|
|
280
|
-
// `workers` is [{ name, id, harness }]; `batch` the batch id ("" when solo).
|
|
281
|
-
// Pure: unit-tested, no board IO — the caller boots it via bootWorker
|
|
282
|
-
// (prompt override) and stamps the log file itself.
|
|
283
|
-
export function buildCoordinatorPrompt({ name, from, subject, body, batch, workers, crew, cwd, root, auto, workbench, budgetTokens, budgetMinutes }) {
|
|
284
|
-
const boss = String(from || "boss");
|
|
285
|
-
const me = String(name || LEAD_NAME);
|
|
256
|
+
// Orchestrator prompt: the board's persistent control-plane agent. It owns
|
|
257
|
+
// the crew — it wrote the briefs, triages, approves, verifies, and reports —
|
|
258
|
+
// but never does the workers' tasks. `workers` is [{ name, id, harness }];
|
|
259
|
+
// `batch` the batch id ("" when solo). Pure: unit-tested, no board IO — the
|
|
260
|
+
// caller boots it via bootWorker (prompt override) and stamps the log file.
|
|
261
|
+
export function buildOrchestratorPrompt({ name, subject, body, batch, workers, crew, cwd, root, auto, workbench, budgetTokens, budgetMinutes }) {
|
|
262
|
+
const me = String(name || ORCHESTRATOR_NAME);
|
|
286
263
|
const ws = Array.isArray(workers) ? workers.filter((w) => w && w.name) : [];
|
|
287
264
|
const crewLines = Array.isArray(crew) ? crew.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
|
|
288
265
|
const wbLines = Array.isArray(workbench) ? workbench.map((l) => String(l)).filter((s) => s.trim() !== "") : [];
|
|
289
266
|
const today = new Date().toISOString().slice(0, 10);
|
|
290
267
|
return [
|
|
291
|
-
`You are '${me}' on crewbus (board: ${root}) — the
|
|
292
|
-
|
|
268
|
+
`You are '${me}' on crewbus (board: ${root}) — the board orchestrator${batch ? ` (batch ${batch})` : ""}.`,
|
|
269
|
+
`You own this crew: you wrote the briefs, you own the workers, and you triage, approve, verify, and report. This is a control-plane role, not a do-the-task role.`,
|
|
293
270
|
``,
|
|
294
|
-
`Mission
|
|
271
|
+
`Mission${subject ? ` — ${subject}` : ""}:`,
|
|
295
272
|
String(body || "(original brief; see each worker's prompt file under logs/)"),
|
|
296
273
|
``,
|
|
297
274
|
...(crewLines.length > 0 ? ["Crew:", ...crewLines.map((l) => `- ${l}`), ""] : []),
|
|
@@ -299,21 +276,21 @@ export function buildCoordinatorPrompt({ name, from, subject, body, batch, worke
|
|
|
299
276
|
...(wbLines.length > 0 ? ["Workbench (lessons + artifacts from prior work on this board):", ...wbLines, ""] : []),
|
|
300
277
|
`Your identity: token saved at logs/${me}.token — read it into CREWBUS_TOKEN at the top of each shell that sends (PowerShell: \$env:CREWBUS_TOKEN = Get-Content .crewbus/logs/${me}.token). All sends run as --from ${me}. Never re-register over your own name — re-read the token file after any restart or compaction.`,
|
|
301
278
|
...(budgetTokens !== undefined || budgetMinutes !== undefined
|
|
302
|
-
? [`Budget mandate:${budgetTokens !== undefined ? ` ~${budgetTokens} est. tokens total${budgetMinutes !== undefined ? " and" : ""}` : ""}${budgetMinutes !== undefined ? ` ${budgetMinutes} wall-clock minutes total` : ""} — coordinate within it: batch your polls (listen --timeout 120000), digest-read first, and post the aggregate
|
|
279
|
+
? [`Budget mandate:${budgetTokens !== undefined ? ` ~${budgetTokens} est. tokens total${budgetMinutes !== undefined ? " and" : ""}` : ""}${budgetMinutes !== undefined ? ` ${budgetMinutes} wall-clock minutes total` : ""} — coordinate within it: batch your polls (listen --timeout 120000), digest-read first, and post the aggregate on the board BEFORE the budget runs out (a budgeted orchestrator gets reaped at the cap).`, ``]
|
|
303
280
|
: []),
|
|
304
281
|
``,
|
|
305
282
|
`Jobs, in order:`,
|
|
306
283
|
`0. Boot habit: crewbus agents + crewbus group list, so you know who is on the board (workers claim over the first minutes; re-check when triaging).`,
|
|
307
284
|
`1. Read every DM before acting on anything else: crewbus inbox --from ${me} --unacked --digest, full read on hits. Workers' checkpoints and finals arrive here (each pinned to --reply their brief id).`,
|
|
308
285
|
`2. Keep the board alive — poll in a loop, cheaply: crewbus listen --from ${me} --timeout 120000 (blocks until a DM arrives; re-issue after each wake; fall back to sleep 60 + inbox --digest when listen is unavailable). Triage as DMs land: unblock, dedupe sibling lanes, point a worker at its sibling's finding instead of redoing it.`,
|
|
309
|
-
`3. Watch crew health: crewbus spawn-status --all. A worker that exited without a final is a lane to close: prefer the catch-up path first (crewbus respawn --from ${me} --to <name>${ws.some((w) => w.harness === "opencode") ? " (--fresh when its session id was never captured)" : ""}${auto ? " --auto (this crew was spawned fully-unattended; respawns inherit it)" : ""}); fall back to a fresh spawn (crewbus spawn --
|
|
310
|
-
`4. Approvals: a worker's "approval:" ask (destructive/irreversible/out-of-scope) waits on your verdict — answer by --reply on its thread within the ask's stated timeout (crewbus send --from ${me} --to <worker> --reply <id> --body "approved ..." | "denied: <reason>; try-instead ..."). Silence beyond the ask's timeout reads as deny, fail-closed. Secrets/exfiltration/isolation-escape asks are NEVER approvable — deny and
|
|
311
|
-
`5. Scope disputes or mission changes:
|
|
312
|
-
`6. Long promises get deadlines: when you push a task or a lane's window, stamp --needs-by <duration> on the DM; chase inbox rows marked [OVERDUE] explicitly; when a lane stalls,
|
|
286
|
+
`3. Watch crew health: crewbus spawn-status --all. A worker that exited without a final is a lane to close: prefer the catch-up path first (crewbus respawn --from ${me} --to <name>${ws.some((w) => w.harness === "opencode") ? " (--fresh when its session id was never captured)" : ""}${auto ? " --auto (this crew was spawned fully-unattended; respawns inherit it)" : ""}); fall back to a fresh spawn (crewbus spawn --to <name> --persistent ... same mission text) only when respawn data is gone. Cap: 2 respawn attempts per lane before recording the stall on the board.`,
|
|
287
|
+
`4. Approvals: a worker's "approval:" ask (destructive/irreversible/out-of-scope) waits on your verdict — answer by --reply on its thread within the ask's stated timeout (crewbus send --from ${me} --to <worker> --reply <id> --body "approved ..." | "denied: <reason>; try-instead ..."). Silence beyond the ask's timeout reads as deny, fail-closed. Secrets/exfiltration/isolation-escape asks are NEVER approvable — deny and record it on the board.`,
|
|
288
|
+
`5. Scope disputes or mission changes: record the open question on the board (artifact/lesson) and keep working conservatively; surface it in your aggregate. Same lane for milestones: batch started, lane closed, blocked, final aggregate.`,
|
|
289
|
+
`6. Long promises get deadlines: when you push a task or a lane's window, stamp --needs-by <duration> on the DM; chase inbox rows marked [OVERDUE] explicitly; when a lane stalls, record it on the board rather than silently absorbing it.`,
|
|
313
290
|
`7. Verify before relaying: worker claims about files/output get spot-checked against the board and ${cwd} when reasonable; do not relay a claim you contradict. Record what you verified in the thread.`,
|
|
314
291
|
``,
|
|
315
|
-
`Never: change the workers' mission text (the mission above is the
|
|
316
|
-
`Exit: when every lane has a final report or a deliberate stand-down,
|
|
292
|
+
`Never: change the workers' mission text (the mission above is the user's brief — pass it through verbatim), redo workers' work yourself, paste secrets (reference file paths), or micro-manage strategy. Peer-coordination belongs to the peers; you own health, verdicts, and the clock.`,
|
|
293
|
+
`Exit: when every lane has a final report or a deliberate stand-down, post the aggregate on the board (artifact publish and/or lesson post — include outcome, lanes closed, respawn count, artifacts left), then you may exit. If the board is stalled with nothing spawnable, post the aggregate with the stall reason and exit.`,
|
|
317
294
|
``,
|
|
318
295
|
`Protocol:`,
|
|
319
296
|
`3. Poll cheap and often: crewbus inbox --from ${me} --unacked --digest (full read only on hits). A full inbox dump every step will eat your context window.`,
|
|
@@ -322,87 +299,39 @@ export function buildCoordinatorPrompt({ name, from, subject, body, batch, worke
|
|
|
322
299
|
}
|
|
323
300
|
|
|
324
301
|
|
|
325
|
-
//
|
|
326
|
-
//
|
|
327
|
-
//
|
|
328
|
-
//
|
|
329
|
-
//
|
|
330
|
-
//
|
|
331
|
-
//
|
|
332
|
-
//
|
|
333
|
-
//
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
// coordinator is reused, never duplicated.
|
|
337
|
-
export function provisionAutoLead(d, opts) {
|
|
338
|
-
const leadName = LEAD_NAME;
|
|
302
|
+
// Ensure the board orchestrator exists, boot it as a detached persistent
|
|
303
|
+
// coordinator when it is not already live, then transfer crew ownership
|
|
304
|
+
// (workers' spawnedBy -> orchestrator). A live orchestrator is reused, never
|
|
305
|
+
// duplicated: briefs land in the same lane by name.
|
|
306
|
+
// opts: { d, spawnOpts, subject, body, rev, logDir, workers, batch,
|
|
307
|
+
// crew, workbench, auto, budgetTokens, budgetMinutes }
|
|
308
|
+
// Returns { action: "created"|"reused"|"skipped", reason?, orchestratorName,
|
|
309
|
+
// pid?, logPath?, promptPath?, token?, transferred?, stoodDown? }.
|
|
310
|
+
// `token` is returned only when the identity was minted by this call.
|
|
311
|
+
export function provisionOrchestrator(d, opts) {
|
|
312
|
+
const orchestratorName = ORCHESTRATOR_NAME;
|
|
339
313
|
const o = opts || {};
|
|
340
|
-
const
|
|
341
|
-
if (
|
|
342
|
-
return { action: "skipped", reason: "
|
|
343
|
-
}
|
|
344
|
-
// Offboarded lead lane = deliberate teardown: refuse to skeleton it back
|
|
345
|
-
// up behind the caller's back (re-onboard it or pass --lead none).
|
|
346
|
-
const existing = readAgent(d, leadName);
|
|
347
|
-
if (existing && existing.offboarded) {
|
|
348
|
-
return { action: "skipped", reason: `lane "${leadName}" is offboarded (re-onboard it, or pass --lead none to pin replies to the spawner)`, leadName };
|
|
314
|
+
const ident = ensureOrchestrator(d);
|
|
315
|
+
if (!ident) {
|
|
316
|
+
return { action: "skipped", reason: "could not mint the board orchestrator", orchestratorName };
|
|
349
317
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
} else {
|
|
355
|
-
token = mintToken();
|
|
356
|
-
const salt = newSalt();
|
|
357
|
-
const tokenHash = hashToken(token, salt);
|
|
358
|
-
const doc = {
|
|
359
|
-
name: leadName, firstSeen: new Date().toISOString(), lastSeen: new Date().toISOString(),
|
|
360
|
-
lastDir: (o.spawnOpts && o.spawnOpts.cwd) || process.cwd(),
|
|
361
|
-
tokenHash, salt, role: "lead",
|
|
362
|
-
provisionedBy: boss, provisionedAt: new Date().toISOString(),
|
|
363
|
-
};
|
|
364
|
-
const claimed = writeExclusiveJson(path.join(d.agents, `${leadName}.json`), doc);
|
|
365
|
-
if (claimed) {
|
|
366
|
-
minted = true;
|
|
367
|
-
} else {
|
|
368
|
-
// Lost the exclusive create: either a concurrent minter won, or a
|
|
369
|
-
// legacy tokenless record holds the name (mint into it — this is the
|
|
370
|
-
// ensureSender post-revoke path, minus the token authentication step
|
|
371
|
-
// the caller already performed as board admin).
|
|
372
|
-
const again = readAgent(d, leadName);
|
|
373
|
-
if (again && !again.offboarded && !again.tokenHash && !again.token) {
|
|
374
|
-
const salt2 = newSalt();
|
|
375
|
-
again.tokenHash = hashToken(token, salt2);
|
|
376
|
-
again.salt = salt2;
|
|
377
|
-
if (!again.role) again.role = "lead";
|
|
378
|
-
writeAgentFile(d, leadName, again);
|
|
379
|
-
assertMintWon(d, leadName, again.tokenHash);
|
|
380
|
-
minted = true;
|
|
381
|
-
} else if (again && (again.tokenHash || again.token)) {
|
|
382
|
-
token = null; // absorbed by a concurrent minter — reuse its identity
|
|
383
|
-
} else {
|
|
384
|
-
return { action: "skipped", reason: `lane "${leadName}" raced a parallel claim that hid the name — retry or pass --lead none`, leadName };
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
// Always (re)record how this coordinator came to be, without clobbering
|
|
389
|
-
// an existing live one. Standing = pid alive AND not stale (reboot + OS
|
|
390
|
-
// pid reuse: a different (unrelated) process recycled the pid — see
|
|
391
|
-
// isPidStale; stale never blocks a fresh boot, it just disqualifies reuse).
|
|
392
|
-
const rec = readAgent(d, leadName);
|
|
318
|
+
const token = ident.created ? ident.token : undefined;
|
|
319
|
+
const rec = readAgent(d, orchestratorName);
|
|
320
|
+
// Standing = pid alive AND not stale (reboot + OS pid reuse: an unrelated
|
|
321
|
+
// process recycled the pid — see isPidStale; stale disqualifies reuse).
|
|
393
322
|
const standing = rec && typeof rec.spawnedPid === "number" && pidAlive(rec.spawnedPid) && !isPidStale(rec.spawnedPid, rec.spawnedAt);
|
|
394
|
-
|
|
323
|
+
const coordToken = loadTokenFile(d.root, orchestratorName) || ident.token;
|
|
324
|
+
if (!standing && !coordToken) {
|
|
325
|
+
return { action: "skipped", reason: `orchestrator lane has no live coordinator and no token file`, orchestratorName };
|
|
326
|
+
}
|
|
395
327
|
let booted = null;
|
|
396
|
-
if (standing) {
|
|
397
|
-
// A live coordinator is already running on the lead lane (previous
|
|
398
|
-
// burst): never duplicate it — DMs land in the same lane by name.
|
|
399
|
-
} else {
|
|
328
|
+
if (!standing) {
|
|
400
329
|
try {
|
|
401
330
|
booted = bootWorker(d, o.spawnOpts, {
|
|
402
|
-
to:
|
|
331
|
+
to: orchestratorName, id: o.batch || "orchestrator", from: orchestratorName, orchestrator: orchestratorName, subject: o.subject,
|
|
403
332
|
body: o.body, rev: o.rev, logDir: o.logDir, crew: o.crew,
|
|
404
|
-
workbench: o.workbench, prompt:
|
|
405
|
-
name:
|
|
333
|
+
workbench: o.workbench, prompt: buildOrchestratorPrompt({
|
|
334
|
+
name: orchestratorName, subject: o.subject, body: o.body,
|
|
406
335
|
batch: o.batch, workers: o.workers, crew: o.crew,
|
|
407
336
|
cwd: (o.spawnOpts && o.spawnOpts.cwd) || process.cwd(),
|
|
408
337
|
root: d.root, auto: !!o.auto, workbench: o.workbench,
|
|
@@ -413,32 +342,29 @@ export function provisionAutoLead(d, opts) {
|
|
|
413
342
|
});
|
|
414
343
|
} catch (e) {
|
|
415
344
|
const detail = String((e && (e.message || e)) || e).slice(0, 160);
|
|
416
|
-
if (
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
return { action: "minted", reason: `coordinator boot failed (${detail}) — lane minted; token at logs/${leadName}.token; boot it by hand (spawn --from ${boss} --to ${leadName} --persistent) or DM workers manually`, leadName, token, boss };
|
|
345
|
+
if (ident.created) {
|
|
346
|
+
try { touchAgent(d, orchestratorName, { lastDir: (o.spawnOpts && o.spawnOpts.cwd) || undefined }); } catch {}
|
|
347
|
+
return { action: "created", reason: `orchestrator boot failed (${detail}) — lane minted; token at logs/${orchestratorName}.token`, orchestratorName, token };
|
|
420
348
|
}
|
|
421
|
-
return { action: "skipped", reason: `
|
|
349
|
+
return { action: "skipped", reason: `orchestrator boot failed (${detail})`, orchestratorName };
|
|
422
350
|
}
|
|
423
351
|
}
|
|
424
|
-
try { touchAgent(d,
|
|
425
|
-
// Crew ownership
|
|
426
|
-
//
|
|
427
|
-
// spawner's audit trail (appendChainRecord) preserves the original actor.
|
|
352
|
+
try { touchAgent(d, orchestratorName, { lastDir: (o.spawnOpts && o.spawnOpts.cwd) || undefined }); } catch {}
|
|
353
|
+
// Crew ownership: workers belong to the orchestrator (audit keeps the
|
|
354
|
+
// original actor in the chain record).
|
|
428
355
|
let transferred = 0;
|
|
429
356
|
for (const w of (Array.isArray(o.workers) ? o.workers : [])) {
|
|
430
357
|
if (!w || !w.name) continue;
|
|
431
|
-
try { touchAgent(d, w.name, { spawnedBy:
|
|
358
|
+
try { touchAgent(d, w.name, { spawnedBy: orchestratorName }); transferred += 1; } catch {}
|
|
432
359
|
}
|
|
433
360
|
return {
|
|
434
|
-
action:
|
|
435
|
-
|
|
361
|
+
action: standing ? "reused" : (booted ? "created" : "skipped"),
|
|
362
|
+
orchestratorName,
|
|
436
363
|
pid: booted ? booted.pid : (rec && rec.spawnedPid),
|
|
437
364
|
logPath: booted ? booted.logPath : undefined,
|
|
438
365
|
promptPath: booted ? booted.promptPath : undefined,
|
|
439
366
|
token,
|
|
440
367
|
transferred,
|
|
441
|
-
boss,
|
|
442
368
|
stoodDown: !!standing,
|
|
443
369
|
};
|
|
444
370
|
}
|
|
@@ -454,11 +380,10 @@ export function provisionAutoLead(d, opts) {
|
|
|
454
380
|
// callers fall back to the shim invocation they always used.
|
|
455
381
|
let _opencodeExe = undefined; // undefined = unresolved; string | null after
|
|
456
382
|
export function resolveOpencodeExe() {
|
|
383
|
+
if (process.env.OPENCODE_EXE !== undefined) return process.env.OPENCODE_EXE || null;
|
|
457
384
|
if (_opencodeExe !== undefined) return _opencodeExe;
|
|
458
385
|
_opencodeExe = null;
|
|
459
386
|
try {
|
|
460
|
-
// where/which are real binaries — no shell was ever needed for this
|
|
461
|
-
// probe (execFileSync + args + shell:true was DEP0190 on modern Node).
|
|
462
387
|
const probe = process.platform === "win32" ? "where" : "which";
|
|
463
388
|
const out = execFileSync(probe, ["opencode"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
|
|
464
389
|
for (const raw of String(out || "").split(/\r?\n/)) {
|
|
@@ -483,6 +408,88 @@ export function resolveOpencodeExe() {
|
|
|
483
408
|
return _opencodeExe;
|
|
484
409
|
}
|
|
485
410
|
|
|
411
|
+
const _harnessExeCache = {};
|
|
412
|
+
export function resolveHarnessExe(harness) {
|
|
413
|
+
const envKey = `${harness.toUpperCase().replace(/[^A-Z0-9]/g, "_")}_EXE`;
|
|
414
|
+
if (process.env[envKey] !== undefined) return process.env[envKey] || null;
|
|
415
|
+
if (harness === "opencode") return resolveOpencodeExe();
|
|
416
|
+
if (_harnessExeCache[harness] !== undefined) return _harnessExeCache[harness];
|
|
417
|
+
_harnessExeCache[harness] = null;
|
|
418
|
+
const binName = harness === "antigravity" ? "agy" : harness;
|
|
419
|
+
try {
|
|
420
|
+
const probe = process.platform === "win32" ? "where" : "which";
|
|
421
|
+
const out = execFileSync(probe, [binName], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 10000 });
|
|
422
|
+
for (const raw of String(out || "").split(/\r?\n/)) {
|
|
423
|
+
const shim = raw.trim();
|
|
424
|
+
if (!shim) continue;
|
|
425
|
+
if (process.platform === "win32") {
|
|
426
|
+
if (/\.exe$/i.test(shim)) {
|
|
427
|
+
_harnessExeCache[harness] = shim;
|
|
428
|
+
break;
|
|
429
|
+
}
|
|
430
|
+
let txt = "";
|
|
431
|
+
try { txt = fs.readFileSync(shim, "utf8"); } catch { continue; }
|
|
432
|
+
const m = /"([^"\n]*?\.exe)"/i.exec(txt);
|
|
433
|
+
if (m) {
|
|
434
|
+
const target = path.resolve(m[1].replace(/%~?dp0%/gi, path.dirname(shim)).replace(/%dp0%/gi, path.dirname(shim)));
|
|
435
|
+
if (fs.existsSync(target) && fs.statSync(target).isFile()) {
|
|
436
|
+
_harnessExeCache[harness] = target;
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const mJs = /"([^"\n]*?\.js)"/i.exec(txt);
|
|
441
|
+
if (mJs) {
|
|
442
|
+
const jsPath = path.resolve(mJs[1].replace(/%~?dp0%/gi, path.dirname(shim)).replace(/%dp0%/gi, path.dirname(shim)));
|
|
443
|
+
const pkgDir = path.dirname(path.dirname(jsPath));
|
|
444
|
+
for (const cand of [
|
|
445
|
+
path.join(pkgDir, "node_modules", "@openai", "codex-win32-x64", "vendor", "x86_64-pc-windows-msvc", "bin", "codex.exe"),
|
|
446
|
+
path.join(path.dirname(pkgDir), "codex-win32-x64", "vendor", "x86_64-pc-windows-msvc", "bin", "codex.exe"),
|
|
447
|
+
]) {
|
|
448
|
+
if (fs.existsSync(cand) && fs.statSync(cand).isFile()) {
|
|
449
|
+
_harnessExeCache[harness] = cand;
|
|
450
|
+
break;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
if (_harnessExeCache[harness]) break;
|
|
454
|
+
}
|
|
455
|
+
} else {
|
|
456
|
+
_harnessExeCache[harness] = shim;
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
} catch {}
|
|
461
|
+
return _harnessExeCache[harness];
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// Per-worker model lists: `--model a,b,c` applies a/b/c to workers in order
|
|
465
|
+
// and cycles when there are more workers than models (same semantics as
|
|
466
|
+
// `--harness`). A single value keeps the old apply-to-all behavior. Model IDs
|
|
467
|
+
// do not contain commas today (provider/model, dashes, dots, colons are all
|
|
468
|
+
// fine), so the comma is the list separator.
|
|
469
|
+
export const MODEL_NAME_MAX = 100;
|
|
470
|
+
|
|
471
|
+
export function parseModelList(raw) {
|
|
472
|
+
if (raw === undefined || raw === null) return [];
|
|
473
|
+
const list = Array.isArray(raw) ? raw : String(raw).split(",");
|
|
474
|
+
return list
|
|
475
|
+
.map((m) => (m === undefined || m === null ? "" : String(m).trim()))
|
|
476
|
+
.filter(Boolean);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
export function modelForIndex(models, i) {
|
|
480
|
+
if (!Array.isArray(models) || models.length === 0) return undefined;
|
|
481
|
+
const n = models.length;
|
|
482
|
+
return models[((i % n) + n) % n];
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
export function modelListErrors(models) {
|
|
486
|
+
const errors = [];
|
|
487
|
+
for (const m of Array.isArray(models) ? models : []) {
|
|
488
|
+
if (String(m).length > MODEL_NAME_MAX) errors.push(`model name too long (max ${MODEL_NAME_MAX} chars)`);
|
|
489
|
+
}
|
|
490
|
+
return errors;
|
|
491
|
+
}
|
|
492
|
+
|
|
486
493
|
export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt, sessionId }) { // line 4114
|
|
487
494
|
const quoteFree = (s) => String(s).replace(/"/g, "'");
|
|
488
495
|
if (harness === "opencode") {
|
|
@@ -507,7 +514,8 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
|
|
|
507
514
|
// --output-format json reports session_id for later resume (same as above).
|
|
508
515
|
// --session-id pre-assigns it, so even a mid-run kill leaves a resumable
|
|
509
516
|
// id on record (verified in CLI docs; needs a valid UUID).
|
|
510
|
-
|
|
517
|
+
// Include mcp__crewbus__* in default allowedTools so bus tools can be invoked.
|
|
518
|
+
const cargs = ["-p", "--output-format", "json", "--allowedTools", allowTools || "Read,Edit,Write,Bash,mcp__crewbus__*"];
|
|
511
519
|
if (sessionId) cargs.push("--session-id", sessionId);
|
|
512
520
|
if (model) cargs.push("--model", model);
|
|
513
521
|
if (maxTurns !== undefined) cargs.push("--max-turns", String(maxTurns));
|
|
@@ -517,22 +525,30 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
|
|
|
517
525
|
if (harness === "codex") {
|
|
518
526
|
// codex exec has no --file attach: the positional message points at the
|
|
519
527
|
// brief file and the worker reads it with its own tools. Read-only is
|
|
520
|
-
// the exec default, so workspace-write
|
|
521
|
-
//
|
|
528
|
+
// the exec default, so workspace-write makes a worker that can work unattended;
|
|
529
|
+
// -c approval_policy="never" avoids unexpected argument '-a' failure in codex exec;
|
|
530
|
+
// --dangerously-bypass-hook-trust allows .codex/hooks.json to execute unattended;
|
|
531
|
+
// --skip-git-repo-check allows non-repo cwds.
|
|
522
532
|
// --json prints JSONL events: the first is thread.started {thread_id},
|
|
523
533
|
// which shares the session-id namespace (session_id: ThreadId in core)
|
|
524
534
|
// and is what `codex exec resume <id>` accepts — captured for respawn.
|
|
525
|
-
const cargs = ["exec", "--json", "--sandbox", auto ? "danger-full-access" : "workspace-write", "-
|
|
535
|
+
const cargs = ["exec", "--json", "--sandbox", auto ? "danger-full-access" : "workspace-write", "-c", "approval_policy=\"never\"", "--dangerously-bypass-hook-trust", "--skip-git-repo-check", "-C", cwd];
|
|
536
|
+
const mcpPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../crewbus-mcp.js");
|
|
537
|
+
if (fs.existsSync(mcpPath)) {
|
|
538
|
+
const normMcp = mcpPath.replace(/\\/g, "/");
|
|
539
|
+
cargs.push("-c", 'mcp_servers.crewbus.command="node"', "-c", `mcp_servers.crewbus.args=["${normMcp}"]`);
|
|
540
|
+
}
|
|
526
541
|
if (model) cargs.push("--model", model);
|
|
542
|
+
if (auto) cargs.push("--dangerously-bypass-approvals-and-sandbox");
|
|
527
543
|
cargs.push(quoteFree(`you are '${name}': read the brief at ${promptPath} and follow it`));
|
|
528
|
-
return { exe: "codex", args: cargs, shell: true };
|
|
544
|
+
return { exe: "codex", args: cargs, shell: true, stdinPath: promptPath };
|
|
529
545
|
}
|
|
530
546
|
if (harness === "grok") {
|
|
531
547
|
// grok.exe is a real binary: no shell, argv passes verbatim.
|
|
532
548
|
// --output-format json emits sessionId for later resume (see above).
|
|
533
549
|
// -s pre-assigns it (create-only UUID): the id is knowable at boot,
|
|
534
550
|
// before the run emits anything — the mid-run-kill case.
|
|
535
|
-
const gargs = ["--prompt-file", promptPath, "--cwd", cwd, "--output-format", "json", "--permission-mode", "auto", "--max-turns", String(maxTurns === undefined ? 50 : maxTurns)];
|
|
551
|
+
const gargs = ["--prompt-file", promptPath, "--cwd", cwd, "--output-format", "json", "--permission-mode", auto ? "bypassPermissions" : "auto", "--max-turns", String(maxTurns === undefined ? 50 : maxTurns)];
|
|
536
552
|
if (sessionId) gargs.push("-s", sessionId);
|
|
537
553
|
if (model) gargs.push("-m", model);
|
|
538
554
|
if (auto) gargs.push("--always-approve");
|
|
@@ -561,7 +577,21 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
|
|
|
561
577
|
cargs.push(quoteFree(`you are '${name}': read the brief at ${promptPath} and follow it`));
|
|
562
578
|
return { exe: "cursor-agent", args: cargs, shell: true };
|
|
563
579
|
}
|
|
564
|
-
|
|
580
|
+
if (harness === "qwen") {
|
|
581
|
+
// qwen is executed via CLI.
|
|
582
|
+
// --output-format json reports session id.
|
|
583
|
+
// --session-id pre-assigns session UUID for crash-safe resume.
|
|
584
|
+
// Positional brief prompt directs worker to read brief file.
|
|
585
|
+
const qargs = ["--output-format", "json"];
|
|
586
|
+
if (sessionId) qargs.push("--session-id", sessionId);
|
|
587
|
+
if (model) qargs.push("--model", model);
|
|
588
|
+
if (maxTurns !== undefined) qargs.push("--max-session-turns", String(maxTurns));
|
|
589
|
+
if (auto) qargs.push("-y", "--approval-mode", "yolo");
|
|
590
|
+
if (allowTools) qargs.push("--allowed-tools", allowTools);
|
|
591
|
+
qargs.push(quoteFree(`you are '${name}': read the brief at ${promptPath} and follow it`));
|
|
592
|
+
return { exe: "qwen", args: qargs, shell: true, stdinPath: promptPath };
|
|
593
|
+
}
|
|
594
|
+
fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor|qwen)`);
|
|
565
595
|
}
|
|
566
596
|
|
|
567
597
|
// Resume targets for `respawn` (slice 2): same worker name, same conversation,
|
|
@@ -569,10 +599,9 @@ export function buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowToo
|
|
|
569
599
|
// opencode `run --session`, claude `-p --resume` (never --session-id: it
|
|
570
600
|
// cannot combine with --resume), codex `exec <parent opts> resume <id>`
|
|
571
601
|
// (parent options precede the subcommand), grok `-r`, agy `--conversation`,
|
|
572
|
-
// cursor `--resume`.
|
|
573
|
-
// the catch-up brief. File/stdin plumbing mirrors buildSpawnTarget.
|
|
602
|
+
// cursor `--resume`. File/stdin plumbing mirrors buildSpawnTarget.
|
|
574
603
|
export function buildRespawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt, sessionId }) { // respawn slice 2
|
|
575
|
-
// No captured session id (
|
|
604
|
+
// No captured session id (the respawn --fresh fallback when a
|
|
576
605
|
// harness id could not be captured): plain fresh boot of the catch-up
|
|
577
606
|
// brief — the same command shape as spawn.
|
|
578
607
|
if (!sessionId) {
|
|
@@ -585,28 +614,24 @@ export function buildRespawnTarget({ harness, cmd, model, auto, maxTurns, allowT
|
|
|
585
614
|
const positional = String(`you are '${name}': read the catch-up brief at ${promptPath} and follow it`).replace(/"/g, "'");
|
|
586
615
|
return { ...base, args: [...base.args.slice(0, -1), "resume", sessionId, positional] };
|
|
587
616
|
}
|
|
588
|
-
if (harness === "generic") {
|
|
589
|
-
return buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt });
|
|
590
|
-
}
|
|
591
617
|
const t = buildSpawnTarget({ harness, cmd, model, auto, maxTurns, allowTools, cwd, name, promptPath, prompt });
|
|
592
618
|
const flag = harness === "opencode" ? ["--session", sessionId]
|
|
593
619
|
: harness === "claude" ? ["--resume", sessionId]
|
|
594
620
|
: harness === "grok" ? ["-r", sessionId]
|
|
595
621
|
: harness === "antigravity" ? ["--conversation", sessionId]
|
|
596
622
|
: harness === "cursor" ? ["--resume", sessionId]
|
|
623
|
+
: harness === "qwen" ? ["--resume", sessionId]
|
|
597
624
|
: null;
|
|
598
|
-
if (!flag) fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor|
|
|
625
|
+
if (!flag) fail(`unknown --harness "${harness}" (want opencode|claude|codex|grok|antigravity|cursor|qwen)`);
|
|
599
626
|
return { ...t, args: [...t.args, ...flag] };
|
|
600
627
|
}
|
|
601
628
|
|
|
602
|
-
export function buildRespawnBrief({ name, attempt, origPromptPath, briefId, harnessSessionId, harness,
|
|
603
|
-
// --fresh respawn (opencode with no captured id) boots fresh
|
|
629
|
+
export function buildRespawnBrief({ name, attempt, origPromptPath, briefId, harnessSessionId, harness, orchestrator, extraBody }) { // respawn slice 2
|
|
630
|
+
// --fresh respawn (opencode with no captured id) boots fresh;
|
|
604
631
|
// the wording must not claim "prior context intact" when there is none.
|
|
605
|
-
const resumed = harness === "
|
|
606
|
-
? "fresh session (
|
|
607
|
-
:
|
|
608
|
-
? "fresh session (opencode session id could not be captured; brief + checkpoints are your memory)"
|
|
609
|
-
: `resumed ${harness} session ${harnessSessionId} (prior context intact)`;
|
|
632
|
+
const resumed = !harnessSessionId && harness === "opencode"
|
|
633
|
+
? "fresh session (opencode session id could not be captured; brief + checkpoints are your memory)"
|
|
634
|
+
: `resumed ${harness} session ${harnessSessionId} (prior context intact)`;
|
|
610
635
|
const lines = [
|
|
611
636
|
`You are '${name}': this is restart attempt ${attempt} (${resumed}). Your previous process died.`,
|
|
612
637
|
``,
|
|
@@ -614,10 +639,10 @@ export function buildRespawnBrief({ name, attempt, origPromptPath, briefId, harn
|
|
|
614
639
|
`Then read your inbox: crewbus inbox --from ${name} (catch up on anything sent while you were down).`,
|
|
615
640
|
`Then read your checkpoints: crewbus thread --id ${briefId} (latest checkpoint is your resume point — do not redo its "done" steps).`,
|
|
616
641
|
`Continue the brief; do not redo completed steps — check files/worktree state first.`,
|
|
617
|
-
`When done or blocked, DM a summary back: crewbus send --from ${name} --to ${
|
|
642
|
+
`When done or blocked, DM a summary back: crewbus send --from ${name} --to ${orchestrator} --reply ${briefId} --body "..." (same thread as the original brief).`,
|
|
618
643
|
`Same approval protocol as your original brief: send --priority high --subject "approval: ..." then listen --timeout 300000 (300s, silence = deny, fail-closed).`,
|
|
619
644
|
];
|
|
620
|
-
if (extraBody && String(extraBody).trim()) lines.push("", "Additional instructions from
|
|
645
|
+
if (extraBody && String(extraBody).trim()) lines.push("", "Additional instructions from the orchestrator:", String(extraBody).trim());
|
|
621
646
|
return lines.join("\n");
|
|
622
647
|
}
|
|
623
648
|
|
|
@@ -652,7 +677,7 @@ function cleanSessionId(raw) {
|
|
|
652
677
|
|
|
653
678
|
// Harness driver allowlist (mirrors packages/contracts/harness.json drivers;
|
|
654
679
|
// unknown values are omitted, never invented).
|
|
655
|
-
export const KNOWN_HARNESS_DRIVERS = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "
|
|
680
|
+
export const KNOWN_HARNESS_DRIVERS = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "qwen"];
|
|
656
681
|
|
|
657
682
|
export function cleanHarnessDriver(raw) {
|
|
658
683
|
const s = String(raw === undefined || raw === null ? "" : raw).trim().toLowerCase();
|
|
@@ -987,9 +1012,16 @@ export function launchWorkerProcess({ exe, args, shell, cwd, env, logPath, stdin
|
|
|
987
1012
|
inFd = fs.openSync(stdinPath, "r");
|
|
988
1013
|
stdio[0] = inFd;
|
|
989
1014
|
}
|
|
990
|
-
const
|
|
1015
|
+
const direct = resolveHarnessExe(exe);
|
|
1016
|
+
let targetExe = exe;
|
|
1017
|
+
let targetShell = shell;
|
|
1018
|
+
if (direct) {
|
|
1019
|
+
targetExe = direct;
|
|
1020
|
+
targetShell = false;
|
|
1021
|
+
}
|
|
1022
|
+
const shot = resolveShellShot(targetExe, args || [], targetShell);
|
|
991
1023
|
child = spawn(shot.exe, shot.args, { cwd, env, detached: true, stdio, shell: shot.shell, windowsHide: true, ...shot.extraOptions });
|
|
992
|
-
} catch (e) {
|
|
1024
|
+
} catch (e) {
|
|
993
1025
|
try { fs.closeSync(logFd); } catch {}
|
|
994
1026
|
try { if (inFd !== null) fs.closeSync(inFd); } catch {}
|
|
995
1027
|
throw e;
|
|
@@ -1106,12 +1138,12 @@ export function installCliToUserPath() {
|
|
|
1106
1138
|
return { ok: true, binDir: userBinDir, addedToPath, detail };
|
|
1107
1139
|
}
|
|
1108
1140
|
|
|
1109
|
-
export function bootWorker(d, spawnOpts, { to, id, from,
|
|
1141
|
+
export function bootWorker(d, spawnOpts, { to, id, from, orchestrator, subject, body, rev, logDir, budgetTokens, budgetMinutes, deadlineAt, spawnedWorktree, spawnedBranch, spawnedLifetime, sessionId, crew, workbench, prompt }) { // line 4338
|
|
1110
1142
|
const { cwd, root } = spawnOpts;
|
|
1111
1143
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
1112
|
-
// Prompt override: the
|
|
1113
|
-
// (
|
|
1114
|
-
const finalPrompt = (typeof prompt === "string" && prompt.trim()) ? prompt : buildSpawnPrompt({ name: to,
|
|
1144
|
+
// Prompt override: the orchestrator passes its own prompt
|
|
1145
|
+
// (buildOrchestratorPrompt); everything else uses the worker template.
|
|
1146
|
+
const finalPrompt = (typeof prompt === "string" && prompt.trim()) ? prompt : buildSpawnPrompt({ name: to, orchestrator, subject, body, replyId: id, rev, cwd, root, crew, workbench });
|
|
1115
1147
|
const promptPath = path.join(logDir, `${to}-${stamp}.prompt.md`);
|
|
1116
1148
|
fs.writeFileSync(promptPath, finalPrompt + "\n");
|
|
1117
1149
|
const logPath = path.join(logDir, `${to}-${stamp}.log`);
|
|
@@ -1144,7 +1176,7 @@ export function bootWorker(d, spawnOpts, { to, id, from, lead, subject, body, re
|
|
|
1144
1176
|
// (tests); otherwise mint fresh. opencode/codex rely on log parsing
|
|
1145
1177
|
// (early event stream / thread.started); cursor/agy offer neither.
|
|
1146
1178
|
let preId = sessionId && String(sessionId).trim() ? String(sessionId).trim() : undefined;
|
|
1147
|
-
if (!preId && (spawnOpts.harness === "claude" || spawnOpts.harness === "grok")) {
|
|
1179
|
+
if (!preId && (spawnOpts.harness === "claude" || spawnOpts.harness === "grok" || spawnOpts.harness === "qwen")) {
|
|
1148
1180
|
try {
|
|
1149
1181
|
preId = crypto.randomUUID();
|
|
1150
1182
|
} catch {
|
|
@@ -1179,13 +1211,14 @@ export function bootWorker(d, spawnOpts, { to, id, from, lead, subject, body, re
|
|
|
1179
1211
|
// brief points at the original prompt file and the same reply thread, so a
|
|
1180
1212
|
// resumed worker continues instead of restarting. Returns
|
|
1181
1213
|
// { pid, logPath, promptPath, attempt }. Binding keeps the original
|
|
1182
|
-
//
|
|
1214
|
+
// briefId/harnessSessionId; spawnedAt refreshes to the new pid launch and
|
|
1215
|
+
// respawnCount increments.
|
|
1183
1216
|
export function bootRespawnedWorker(d, spawnOpts, { to, briefId, from, sessionId, attempt, origPromptPath, extraBody, logDir }) { // respawn slice 2
|
|
1184
1217
|
const { harness, cwd } = spawnOpts;
|
|
1185
1218
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
1186
1219
|
const catchup = buildRespawnBrief({
|
|
1187
1220
|
name: to, attempt, origPromptPath, briefId,
|
|
1188
|
-
harnessSessionId: sessionId, harness,
|
|
1221
|
+
harnessSessionId: sessionId, harness, orchestrator: from, extraBody,
|
|
1189
1222
|
});
|
|
1190
1223
|
const promptPath = path.join(logDir, `${to}-${stamp}.respawn.md`);
|
|
1191
1224
|
fs.writeFileSync(promptPath, catchup + "\n");
|
|
@@ -1212,9 +1245,11 @@ export function bootRespawnedWorker(d, spawnOpts, { to, briefId, from, sessionId
|
|
|
1212
1245
|
if (harness === "claude") childEnv.CLAUDE_CODE_RESUME_INTERRUPTED_TURN = "1";
|
|
1213
1246
|
const target = buildRespawnTarget({ ...spawnOpts, name: to, promptPath, prompt: catchup, sessionId });
|
|
1214
1247
|
const { pid } = launchWorkerProcess({ exe: target.exe, args: target.args, shell: target.shell, cwd, env: childEnv, logPath, stdinPath: target.stdinPath });
|
|
1215
|
-
//
|
|
1216
|
-
|
|
1248
|
+
// New pid + new launch stamp: spawnedAt must track the process the record
|
|
1249
|
+
// now points at, or the recycled-pid guard reads the fresh worker as stale.
|
|
1250
|
+
// briefId/spawnedBy stay original.
|
|
1217
1251
|
const now = new Date().toISOString();
|
|
1252
|
+
touchAgent(d, to, { spawnedPid: pid, spawnedAt: now, lastDir: cwd });
|
|
1218
1253
|
let prev = null;
|
|
1219
1254
|
try {
|
|
1220
1255
|
prev = readWorkerSession(d, to);
|
|
@@ -1223,7 +1258,7 @@ export function bootRespawnedWorker(d, spawnOpts, { to, briefId, from, sessionId
|
|
|
1223
1258
|
fs.mkdirSync(path.join(d.root, "worker-sessions"), { recursive: true });
|
|
1224
1259
|
writeJson(workerSessionPath(d, to), {
|
|
1225
1260
|
...(prev || {}),
|
|
1226
|
-
name: to, spawnedPid: pid, logPath, promptPath,
|
|
1261
|
+
name: to, spawnedPid: pid, spawnedAt: now, logPath, promptPath,
|
|
1227
1262
|
respawnCount: ((prev && prev.respawnCount) || 0) + 1,
|
|
1228
1263
|
lastRespawnAt: now,
|
|
1229
1264
|
});
|
|
@@ -1425,6 +1460,18 @@ export async function killWorkers(d, names) { // line 4529
|
|
|
1425
1460
|
process.kill(pid);
|
|
1426
1461
|
}
|
|
1427
1462
|
} catch (e) {
|
|
1463
|
+
// The process may have exited between the liveness check and the kill
|
|
1464
|
+
// call (taskkill also returns non-zero for a dying tree). Re-check
|
|
1465
|
+
// before reporting failure — a dead pid is not a kill failure.
|
|
1466
|
+
let dead = false;
|
|
1467
|
+
for (let i = 0; i < 20 && !dead; i++) {
|
|
1468
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1469
|
+
dead = !pidAlive(pid);
|
|
1470
|
+
}
|
|
1471
|
+
if (dead) {
|
|
1472
|
+
out.push({ name, result: "already-exited", pid });
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1428
1475
|
out.push({ name, result: "kill-failed", pid, detail: String((e && e.code) || e) });
|
|
1429
1476
|
continue;
|
|
1430
1477
|
}
|
|
@@ -1441,6 +1488,6 @@ export async function killWorkers(d, names) { // line 4529
|
|
|
1441
1488
|
|
|
1442
1489
|
export function defaultMaxTurnsFor(harness, raw) { // line 1172
|
|
1443
1490
|
if (raw !== undefined && raw !== null && String(raw).trim() !== "") return Number(raw);
|
|
1444
|
-
if (harness === "claude" || harness === "grok") return 50;
|
|
1491
|
+
if (harness === "claude" || harness === "grok" || harness === "qwen") return 50;
|
|
1445
1492
|
return undefined;
|
|
1446
1493
|
}
|