crewbus 10.0.12 → 11.3.1

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.
Files changed (48) hide show
  1. package/AGENTS.template.md +4 -4
  2. package/CHANGELOG.md +153 -0
  3. package/README.md +69 -44
  4. package/TEAM.template.md +1 -1
  5. package/bin/crewbus-hook.js +22 -5
  6. package/bin/crewbus-mcp.js +56 -48
  7. package/bin/crewbus.js +459 -238
  8. package/bin/lib/channels.js +1 -1
  9. package/bin/lib/export.js +1 -1
  10. package/bin/lib/groups.js +1 -5
  11. package/bin/lib/identity.js +90 -128
  12. package/bin/lib/launch.js +63 -8
  13. package/bin/lib/relay.js +25 -42
  14. package/bin/lib/spawn.js +155 -162
  15. package/bin/lib/store.js +2 -2
  16. package/bin/lib/web.js +241 -60
  17. package/claude-plugin/skills/crewbus/SKILL.md +1 -1
  18. package/docs/APPROVALS.md +8 -8
  19. package/docs/AUDIT_EXPORT.md +7 -7
  20. package/docs/CERT_READINESS.md +5 -5
  21. package/docs/COMPATIBILITY.md +6 -2
  22. package/docs/CONSOLIDATOR.md +6 -6
  23. package/docs/CONTROL_PLANE_SPEC.md +3 -3
  24. package/docs/CREWS.md +58 -55
  25. package/docs/DELIVERY.md +11 -8
  26. package/docs/GROUPS.md +8 -8
  27. package/docs/IDENTITY.md +6 -6
  28. package/docs/LONG_RUNS.md +3 -3
  29. package/docs/ORCHESTRATOR.md +87 -0
  30. package/docs/PAIRING.md +7 -7
  31. package/docs/QUICKSTART.md +81 -70
  32. package/docs/RBAC.md +84 -73
  33. package/docs/TENANCY.md +10 -10
  34. package/docs/THREAT_MODEL.md +3 -3
  35. package/docs/VERIFIER.md +10 -10
  36. package/docs/VERSION_SKEW.md +1 -1
  37. package/documentation.html +34 -24
  38. package/examples/hermes-pairing.md +3 -3
  39. package/examples/t3-pairing.md +1 -1
  40. package/index.html +6 -6
  41. package/opencode/plugins/dm-watch.js +1 -1
  42. package/opencode/tools/dm-send.js +1 -1
  43. package/package.json +27 -2
  44. package/packages/contracts/harness.json +15 -1
  45. package/packages/contracts/launch.json +2 -3
  46. package/packages/contracts/pairing.json +3 -3
  47. package/docs/LEAD_ASSIGN.md +0 -74
  48. package/docs/M1_CLI_DRAFT.md +0 -175
package/bin/lib/web.js CHANGED
@@ -16,16 +16,18 @@ import fs from "node:fs";
16
16
  import { spawn } from "node:child_process";
17
17
  import path from "node:path";
18
18
  import http from "node:http";
19
+ import os from "node:os";
19
20
  import { fileURLToPath } from "node:url";
20
- import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, readBoardMeta, writeBoardMeta, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS } from "./store.js";
21
- import { readAgent, agentTokenMatches, authorizeCheck, ensureLoopbackOperator, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
21
+ import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, readBoardMeta, writeBoardMeta, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS, writeExclusiveJson } from "./store.js";
22
+ import { readAgent, agentTokenMatches, authorizeCheck, ensureOrchestrator, mintToken, newSalt, hashToken, touchAgent, timingSafeEqualStr } from "./identity.js";
22
23
  import { readDMs, readVisible, ackedIds, ackedIdSet, findMessageById, deliverDMs, parseRecipients } from "./mail.js";
23
- import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim, buildCoordinatorPrompt, provisionAutoLead, LEAD_NAME, isPidStale } from "./spawn.js";
24
+ import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim, buildOrchestratorPrompt, provisionOrchestrator,
25
+ ORCHESTRATOR_NAME, isPidStale, parseModelList, modelForIndex } from "./spawn.js";
24
26
  import { groupTelemetryData, collectBatch, gatherTelemetry, listBatches } from "./groups.js";
25
27
  import { httpJson } from "./sync.js";
26
28
  import { readChainRecords, verifyChainRecords, appendChainRecord, readHold, readBoardQuotas } from "./export.js";
27
- import { launchDrivers, detectHarnessBinaries, validateLaunchPlan, advertiseEnv, buildPairUrl, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels } from "./launch.js";
28
- import { newPairToken, pairingPath, readRelayState } from "./relay.js";
29
+ import { launchDrivers, detectHarnessBinaries, validateLaunchPlan, advertiseEnv, buildPairUrl, HARNESS_MODELS, getDiscoveredModels, refreshDiscoveredModels, PAIR_SCOPES } from "./launch.js";
30
+ import { newPairToken, pairingPath, readRelayState, newDeviceCred, devicePath } from "./relay.js";
29
31
 
30
32
  export function escapeHtml(s) {
31
33
  return String(s === undefined || s === null ? "" : s).replace(/[&<>"']/g, (c) => ({
@@ -784,9 +786,9 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
784
786
  <button type="button" data-perm="auto">auto</button>
785
787
  <button type="button" data-perm="full">full</button>
786
788
  </span>
787
- <span class="dim" style="margin-left:8px">Coordinator:</span>
788
- <select id="launch-lead" style="background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:4px;padding:3px 8px;font-size:12px" title="Observer coordinator lane: auto provisions a persistent background coordinator (lead) to triage workers and report to you">
789
- <option value="auto">auto (Observer coordinator)</option>
789
+ <span class="dim" style="margin-left:8px">Orchestrator:</span>
790
+ <select id="launch-lead" style="background:var(--panel);color:var(--ink);border:1px solid var(--line);border-radius:4px;padding:3px 8px;font-size:12px" title="The board orchestrator: auto-provisions a persistent background coordinator to triage workers and report">
791
+ <option value="auto">auto (board orchestrator)</option>
790
792
  </select>
791
793
  <label class="dim" style="cursor:pointer;margin-left:6px"><input id="launch-dry" type="checkbox" checked> Dry-run</label>
792
794
  </div>
@@ -807,7 +809,7 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
807
809
 
808
810
  <div class="composer-bottom">
809
811
  <div class="launch-identity" title="Desktop launches as the board owner (auto-provisioned) — no token step needed">
810
- <span class="dim">launching as <b id="launch-as">boss</b> (auto)</span>
812
+ <span class="dim">launching as <b id="launch-as">orchestrator</b> (auto)</span>
811
813
  <input id="launch-from" type="hidden" value="">
812
814
  <input id="launch-token" type="password" style="display:none" value="">
813
815
  </div>
@@ -1015,7 +1017,7 @@ function markIdent(){
1015
1017
  try{
1016
1018
  var man=document.getElementById('launch-from-manual');
1017
1019
  var lbl=document.getElementById('launch-as');
1018
- if(lbl)lbl.textContent=(man&&man.value.trim())||lf.value.trim()||c.from||'lead';
1020
+ if(lbl)lbl.textContent=(man&&man.value.trim())||lf.value.trim()||c.from||'orchestrator';
1019
1021
  }catch(_){}
1020
1022
  }
1021
1023
  async function autoLoadOperatorCreds(){
@@ -1211,9 +1213,9 @@ async function refresh(){
1211
1213
  return '<tr><td>'+esc(m.id)+'</td><td>'+esc(m.from)+'</td><td>'+(m.subject?'<b>'+esc(m.subject)+'</b><br>':'')+esc(m.head)+'</td><td><button data-ack="'+esc(m.id)+'">ack</button></td></tr>';
1212
1214
  }).join('')||'<tr><td colspan="4" class="dim">inbox zero for '+esc(c.from)+'</td></tr>';
1213
1215
  var ap=(tj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
1214
- if(c.from!=='lead'){
1216
+ if(c.from!=='orchestrator'){
1215
1217
  try{
1216
- var lr=await fetch('/api/inbox?agent=lead&unacked=1&limit=50',{cache:'no-store'});
1218
+ var lr=await fetch('/api/inbox?agent=orchestrator&unacked=1&limit=50',{cache:'no-store'});
1217
1219
  if(lr.ok){
1218
1220
  var lj=await lr.json();
1219
1221
  var lap=(lj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
@@ -1225,7 +1227,7 @@ async function refresh(){
1225
1227
  }catch(_){}
1226
1228
  }
1227
1229
  document.getElementById('approvals').innerHTML=ap.map(function(m){
1228
- var tag=m._forLead?' <span class="badge" style="font-size:10px;background:var(--panel);border:1px solid var(--line);padding:1px 4px;border-radius:3px">to lead</span>':'';
1230
+ var tag=m._forLead?' <span class="badge" style="font-size:10px;background:var(--panel);border:1px solid var(--line);padding:1px 4px;border-radius:3px">to orchestrator</span>':'';
1229
1231
  return '<tr><td>'+esc(m.id)+tag+'</td><td>'+esc(m.from)+'</td><td>'+(m.subject?'<b>'+esc(m.subject)+'</b><br>':'')+esc(m.head)+'</td><td><input data-reason="'+esc(m.id)+'" maxlength="500" size="18" placeholder="optional reason"></td><td><button data-approve="'+esc(m.id)+'">approve</button> <button class="danger" data-deny="'+esc(m.id)+'">deny</button></td></tr>';
1230
1232
  }).join('')||'<tr><td colspan="5" class="dim">no approval requests for '+esc(c.from)+'</td></tr>';
1231
1233
  }else{
@@ -1512,19 +1514,19 @@ async function doLaunch(dry){
1512
1514
  if(j.dryRun){
1513
1515
  var warn=(j.warnings||[]).length?('warnings: '+j.warnings.join('; ')+'\\n'):'';
1514
1516
  var cwdNotice=j.cwd?('target directory (cwd): '+j.cwd+'\\n'):'';
1515
- var coordNotice=j.coordinator?('\\ncoordinator ('+j.coordinator.name+'): '+(j.coordinator.action==='reused'?('reused standing pid '+j.coordinator.pid):(j.coordinator.action==='minted'?'would auto-provision':'skipped ('+(j.coordinator.reason||'')+')'))):'';
1517
+ var coordNotice=j.coordinator?('\\ncoordinator ('+j.coordinator.name+'): '+(j.coordinator.action==='reused'?('reused standing pid '+j.coordinator.pid):(j.coordinator.action==='created'?'would auto-provision':'skipped ('+(j.coordinator.reason||'')+')'))):'';
1516
1518
  try{renderLaunchDiff(j);}catch(_){}out.textContent=warn+cwdNotice+(j.commands||[]).map(function(c){return c.to+' ['+(c.harness||'')+']: '+c.command;}).join('\\n')+coordNotice+'\\n(dry-run — booted nothing)';
1517
1519
  }else{
1518
1520
  try{showUndoToast((j.workers||[]).map(function(w){return w.name;}));}catch(_){}
1519
1521
  var cwdNotice=j.cwd?(' [cwd: '+j.cwd+']'):'';
1520
1522
  var coordNotice='';
1521
1523
  if(j.coordinator){
1522
- if(j.coordinator.action==='minted'&&j.coordinator.pid){
1523
- coordNotice=' · coordinator: lead (pid '+j.coordinator.pid+')';
1524
+ if(j.coordinator.action==='created'&&j.coordinator.pid){
1525
+ coordNotice=' · orchestrator: pid '+j.coordinator.pid;
1524
1526
  }else if(j.coordinator.action==='reused'){
1525
- coordNotice=' · coordinator: lead (reused'+(j.coordinator.pid?' pid '+j.coordinator.pid:'')+')';
1527
+ coordNotice=' · orchestrator: reused'+(j.coordinator.pid?' pid '+j.coordinator.pid:'');
1526
1528
  }else if(j.coordinator.reason){
1527
- coordNotice=' · coordinator: skipped ('+j.coordinator.reason+')';
1529
+ coordNotice=' · orchestrator: skipped ('+j.coordinator.reason+')';
1528
1530
  }
1529
1531
  }
1530
1532
  out.textContent='launched: '+(j.workers||[]).map(function(w){return w.name+' ['+(w.driver||'')+']'+(w.pid?(' (pid '+w.pid+')'):'')+(w.error?(' ERROR '+w.error):'');}).join(', ')+coordNotice+cwdNotice;
@@ -2463,7 +2465,7 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2463
2465
  res.end(JSON.stringify({ error: "loopback only" }));
2464
2466
  return true;
2465
2467
  }
2466
- for (const name of ["boss", "lead"]) {
2468
+ for (const name of [ORCHESTRATOR_NAME]) {
2467
2469
  const tokenFile = path.join(d.root, "logs", `${name}.token`);
2468
2470
  let tok = "";
2469
2471
  try { tok = fs.readFileSync(tokenFile, "utf8").trim(); } catch {}
@@ -2566,16 +2568,27 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2566
2568
  const ttlMs = 10 * 60 * 1000;
2567
2569
  const doc = {
2568
2570
  tokenHash: hashToken(token, salt), salt, label: "dashboard-oneclick",
2569
- createdBy: "lead", createdAt: new Date(now).toISOString(),
2571
+ createdBy: ORCHESTRATOR_NAME, createdAt: new Date(now).toISOString(),
2570
2572
  expiresAt: new Date(now + ttlMs).toISOString(),
2571
2573
  };
2572
2574
  fs.mkdirSync(path.join(d.root, "pairing"), { recursive: true });
2573
2575
  writeJson(pairingPath(d, doc.tokenHash), doc);
2574
- try { appendChainRecord(d, "lead", "pair", { label: "dashboard-oneclick", expiresAt: doc.expiresAt }); } catch {}
2575
- const envId = (readRelayState(d) && readRelayState(d).envId) || ("board:" + path.basename(d.root));
2576
- const pairUrl = buildPairUrl({ envId, routes: [], caps: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"], pairToken: token });
2576
+ try { appendChainRecord(d, ORCHESTRATOR_NAME, "pair", { label: "dashboard-oneclick", expiresAt: doc.expiresAt }); } catch {}
2577
+ const relayDoc = readRelayState(d);
2578
+ const envId = (relayDoc && relayDoc.envId) || ("board:" + path.basename(d.root));
2579
+ let routes = (relayDoc && Array.isArray(relayDoc.advertisedRoutes) && relayDoc.advertisedRoutes.length > 0)
2580
+ ? relayDoc.advertisedRoutes
2581
+ : [];
2582
+ if (routes.length === 0) {
2583
+ const port = req.socket.localPort || 8471;
2584
+ routes = localNetworkRoutes(port);
2585
+ }
2586
+ if (routes.length === 0 && req.headers.host && !req.headers.host.startsWith("localhost") && !req.headers.host.startsWith("127.")) {
2587
+ routes.push(`http://${req.headers.host}`);
2588
+ }
2589
+ const pairUrl = buildPairUrl({ envId, routes, caps: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"], pairToken: token });
2577
2590
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2578
- res.end(JSON.stringify({ ok: true, pairUrl, expiresAt: doc.expiresAt, envId }));
2591
+ res.end(JSON.stringify({ ok: true, pairUrl, expiresAt: doc.expiresAt, envId, routes }));
2579
2592
  } catch (err) {
2580
2593
  res.writeHead(500, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2581
2594
  res.end(JSON.stringify({ ok: false, error: String((err && err.message) || err) }));
@@ -2585,17 +2598,32 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2585
2598
  return false;
2586
2599
  }
2587
2600
 
2601
+ export function localNetworkRoutes(port) {
2602
+ const routes = [];
2603
+ try {
2604
+ const ifaces = os.networkInterfaces();
2605
+ for (const list of Object.values(ifaces)) {
2606
+ for (const item of list || []) {
2607
+ if (item.family === "IPv4" && !item.internal && item.address && !item.address.startsWith("169.254.") && !item.address.startsWith("127.")) {
2608
+ routes.push(`http://${item.address}:${port}`);
2609
+ }
2610
+ }
2611
+ }
2612
+ } catch {}
2613
+ return routes;
2614
+ }
2615
+
2588
2616
  export async function cmdWeb(args) {
2589
2617
  const root = boardDir(args);
2590
2618
  const d = requireBoard(root);
2591
2619
  ensureBoardCliShim(d);
2592
- const host = getFlag(args, "--host") || "127.0.0.1";
2620
+ const host = getFlag(args, "--host") || "0.0.0.0";
2593
2621
  const port = Number(getFlag(args, "--port") || 0);
2594
- // Desktop plug-and-play: same loopback auto-provision as `serve` (see
2595
- // ensureLoopbackOperator in identity.js). First loopback boot mints `lead`.
2596
- try { ensureLoopbackOperator(d, host); } catch {}
2622
+ // Same local auto-provision as `serve`: the board's single orchestrator is
2623
+ // ensured on boot (minted on first use, token at logs/orchestrator.token).
2624
+ try { ensureOrchestrator(d); } catch {}
2597
2625
  if (!(port >= 0 && port < 65536)) fail("--port must be 0-65535 (0 = random)");
2598
- if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1") {
2626
+ if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && host !== "0.0.0.0") {
2599
2627
  process.stderr.write(`crewbus: warning: binding non-local ${host} — the dashboard has no auth, anyone who can reach it can read the board\n`);
2600
2628
  }
2601
2629
  const server = http.createServer((req, res) => {
@@ -2615,6 +2643,144 @@ export async function cmdWeb(args) {
2615
2643
  }
2616
2644
  if (await handleWebDashboardRoute(req, res, url, d)) return;
2617
2645
  if (serveBrandAsset(req, res, url.pathname)) return;
2646
+ if (req.method === "GET" && url.pathname === "/healthz") {
2647
+ const s = readRelayState(d);
2648
+ const uptimeSec = Math.floor(process.uptime());
2649
+ const port = req.socket.localPort || 8471;
2650
+ const routes = localNetworkRoutes(port);
2651
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2652
+ res.end(JSON.stringify({
2653
+ role: (s && s.role) || "dashboard",
2654
+ weight: 100,
2655
+ workers: 0,
2656
+ advertisedRoutes: (s && Array.isArray(s.advertisedRoutes) && s.advertisedRoutes.length > 0) ? s.advertisedRoutes : routes,
2657
+ uptimeSec,
2658
+ }));
2659
+ return;
2660
+ }
2661
+ if (req.method === "POST" && url.pathname === "/api/pair/exchange") {
2662
+ const s = readRelayState(d);
2663
+ if (s && s.role === "standby") {
2664
+ res.writeHead(503, { "content-type": "application/json; charset=utf-8", "x-relay-role": "standby" });
2665
+ res.end(JSON.stringify({ error: "standby relay: writes refused", role: "standby" }));
2666
+ return;
2667
+ }
2668
+ if (!String(req.headers["content-type"] || "").includes("application/json")) {
2669
+ res.writeHead(415, { "content-type": "application/json; charset=utf-8" });
2670
+ res.end(JSON.stringify({ error: "content-type must be application/json" }));
2671
+ return;
2672
+ }
2673
+ const chunks = [];
2674
+ let size = 0;
2675
+ let tooBig = false;
2676
+ req.on("data", (c) => {
2677
+ size += c.length;
2678
+ if (size <= 65536) chunks.push(c);
2679
+ else tooBig = true;
2680
+ });
2681
+ req.on("end", () => {
2682
+ try {
2683
+ if (tooBig) {
2684
+ res.writeHead(413, { "content-type": "application/json; charset=utf-8" });
2685
+ res.end(JSON.stringify({ error: "body too large (max 64KB)" }));
2686
+ return;
2687
+ }
2688
+ let body = null;
2689
+ try {
2690
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
2691
+ } catch {
2692
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2693
+ res.end(JSON.stringify({ error: "invalid JSON body" }));
2694
+ return;
2695
+ }
2696
+ const presented = String((body && body.pairToken) || "");
2697
+ const label = String((body && body.label) || "").slice(0, 80);
2698
+ let requested = null;
2699
+ if (body && body.scopes !== undefined && body.scopes !== null) {
2700
+ if (!Array.isArray(body.scopes)) {
2701
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2702
+ res.end(JSON.stringify({ error: "scopes must be an array" }));
2703
+ return;
2704
+ }
2705
+ requested = [];
2706
+ for (const sc of body.scopes) {
2707
+ const c = String(sc).trim();
2708
+ if (!PAIR_SCOPES.includes(c)) {
2709
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2710
+ res.end(JSON.stringify({ error: `unknown scope "${c.slice(0, 60)}" (want ${PAIR_SCOPES.join("|")})` }));
2711
+ return;
2712
+ }
2713
+ if (!requested.includes(c)) requested.push(c);
2714
+ }
2715
+ }
2716
+ let rec = null;
2717
+ let recPath = null;
2718
+ try {
2719
+ const dir = path.join(d.root, "pairing");
2720
+ for (const f of fs.readdirSync(dir)) {
2721
+ if (!f.endsWith(".json") || f.endsWith(".used.json")) continue;
2722
+ try {
2723
+ const pdoc = readJson(path.join(dir, f));
2724
+ if (pdoc && pdoc.tokenHash && pdoc.salt && timingSafeEqualStr(hashToken(presented, String(pdoc.salt)), String(pdoc.tokenHash))) {
2725
+ rec = pdoc;
2726
+ recPath = path.join(dir, f);
2727
+ break;
2728
+ }
2729
+ } catch {}
2730
+ }
2731
+ } catch {}
2732
+ if (!rec) {
2733
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
2734
+ res.end(JSON.stringify({ error: "unknown pairing token" }));
2735
+ return;
2736
+ }
2737
+ if (Date.parse(rec.expiresAt) <= Date.now()) {
2738
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
2739
+ res.end(JSON.stringify({ error: "pairing token expired" }));
2740
+ return;
2741
+ }
2742
+ const granted = Array.isArray(rec.scopes) ? rec.scopes : null;
2743
+ if (requested !== null && granted !== null) {
2744
+ const wider = requested.filter((s) => !granted.includes(s));
2745
+ if (wider.length > 0) {
2746
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
2747
+ res.end(JSON.stringify({ error: `scope widen refused (not granted: ${wider.join(",")})` }));
2748
+ return;
2749
+ }
2750
+ }
2751
+ const usedPath = recPath.replace(/\.json$/, ".used.json");
2752
+ if (!writeExclusiveJson(usedPath, { at: new Date().toISOString(), label })) {
2753
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" });
2754
+ res.end(JSON.stringify({ error: "pairing token already used" }));
2755
+ return;
2756
+ }
2757
+ const dc = newDeviceCred();
2758
+ const salt = newSalt();
2759
+ fs.mkdirSync(path.join(d.root, "devices"), { recursive: true });
2760
+ writeJson(devicePath(d, dc.id), {
2761
+ id: dc.id, label, secretHash: hashToken(dc.secret, salt), salt,
2762
+ createdBy: rec.createdBy || "", createdAt: new Date().toISOString(),
2763
+ lastSeen: "", revoked: false,
2764
+ scopes: requested !== null ? requested : granted,
2765
+ });
2766
+ try {
2767
+ appendChainRecord(d, "relay", "device-issue", { id: dc.id, label, by: rec.createdBy || "" });
2768
+ } catch {}
2769
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2770
+ res.end(JSON.stringify({ deviceId: dc.id, credential: dc.cred }));
2771
+ } catch (err) {
2772
+ res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
2773
+ res.end(JSON.stringify({ error: `exchange failed: ${(err && err.message) || err}` }));
2774
+ }
2775
+ });
2776
+ req.on("error", () => {
2777
+ try {
2778
+ res.writeHead(400, { "content-type": "application/json; charset=utf-8" });
2779
+ res.end(JSON.stringify({ error: "unreadable body" }));
2780
+ } catch {}
2781
+ });
2782
+ return;
2783
+ }
2618
2784
  if (req.method === "POST" && url.pathname === "/api/kill") {
2619
2785
  // JSON-only (browsers preflight this; simple CSRF forms can't reach
2620
2786
  // it), token-checked like the CLI. Same trust zone as the board.
@@ -2659,12 +2825,22 @@ export async function cmdWeb(args) {
2659
2825
  return;
2660
2826
  }
2661
2827
  if (req.method === "GET" && url.pathname === "/api/routes") {
2662
- // Control-plane M1: reachability hints. The local dashboard is not
2663
- // a relay, so routes are empty — pair via `relay pair qr` on the
2664
- // relay instead. Same shape as the relay's /api/routes.
2665
- const envId = `board:${path.basename(d.root)}`;
2828
+ // Control-plane M1: reachability hints. The local dashboard exposes
2829
+ // LAN/relay routes so paired clients can reach it.
2830
+ const relayDoc = readRelayState(d);
2831
+ const envId = (relayDoc && relayDoc.envId) || `board:${path.basename(d.root)}`;
2832
+ let routes = (relayDoc && Array.isArray(relayDoc.advertisedRoutes) && relayDoc.advertisedRoutes.length > 0)
2833
+ ? relayDoc.advertisedRoutes
2834
+ : [];
2835
+ if (routes.length === 0) {
2836
+ const effectivePort = req.socket.localPort || 8471;
2837
+ routes = localNetworkRoutes(effectivePort);
2838
+ }
2839
+ if (routes.length === 0 && req.headers.host && !req.headers.host.startsWith("localhost") && !req.headers.host.startsWith("127.")) {
2840
+ routes.push(`http://${req.headers.host}`);
2841
+ }
2666
2842
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
2667
- res.end(JSON.stringify(advertiseEnv({ envId, routes: [], capabilities: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"] })));
2843
+ res.end(JSON.stringify(advertiseEnv({ envId, routes, capabilities: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"] })));
2668
2844
  return;
2669
2845
  }
2670
2846
  if (req.method === "POST" && url.pathname === "/api/launch") {
@@ -2712,7 +2888,10 @@ export async function cmdWeb(args) {
2712
2888
  server.on("error", reject);
2713
2889
  server.listen(port, host, () => {
2714
2890
  const a = server.address();
2715
- const shown = a && typeof a === "object" ? `${a.address}:${a.port}` : `${host}:${port}`;
2891
+ const addr = a && typeof a === "object" ? a.address : host;
2892
+ const effectivePort = a && typeof a === "object" ? a.port : port;
2893
+ const displayHost = (addr === "0.0.0.0" || addr === "::" || addr === "0:0:0:0:0:0:0:0") ? "127.0.0.1" : addr;
2894
+ const shown = `${displayHost}:${effectivePort}`;
2716
2895
  const webUrl = `http://${shown}`;
2717
2896
  console.log(`crewbus web at ${webUrl} [board ${d.root}]`);
2718
2897
  if (args.includes("--open")) {
@@ -2771,11 +2950,13 @@ export async function handleApiKill(d, body) {
2771
2950
  // CLI); dryRun previews exact commands without booting; live delivers the
2772
2951
  // brief + boots via bootWorker (same core as CLI spawn/remoteSpawn).
2773
2952
  export async function handleApiLaunch(d, body) {
2774
- const from = cleanWebName(body && body.from);
2953
+ const from = ORCHESTRATOR_NAME;
2775
2954
  const token = body && body.token !== undefined && body.token !== null && String(body.token) !== "" ? String(body.token) : undefined;
2776
- if (!from) return { status: 400, payload: { error: "missing from (your agent name)" } };
2777
- const rec = readAgent(d, from);
2778
- if (!rec || !(rec.tokenHash || rec.token) || !agentTokenMatches(rec, token)) return { status: 403, payload: { error: "bad token" } };
2955
+ ensureOrchestrator(d);
2956
+ if (token) {
2957
+ const rec = readAgent(d, from);
2958
+ if (!rec || !(rec.tokenHash || rec.token) || !agentTokenMatches(rec, token)) return { status: 403, payload: { error: "bad token" } };
2959
+ }
2779
2960
  {
2780
2961
  const r = authorizeCheck(d, from, "spawn");
2781
2962
  if (!r.ok) return { status: 403, payload: { error: r.reason } };
@@ -2784,11 +2965,11 @@ export async function handleApiLaunch(d, body) {
2784
2965
  if (!v.ok) return { status: 400, payload: { error: "launch plan invalid", errors: v.errors, warnings: v.warnings } };
2785
2966
  const p = v.plan;
2786
2967
  const harnesses = Array.isArray(p.harnesses) && p.harnesses.length > 0 ? p.harnesses : [p.harness || "opencode"];
2787
- const leadMode = p.lead || "auto";
2788
- if (leadMode !== "auto") {
2789
- return { status: 400, payload: { error: `invalid lead mode "${p.lead}" (only "auto" supported)` } };
2790
- }
2791
- const leadTarget = LEAD_NAME;
2968
+ const models = Array.isArray(p.models) ? p.models : parseModelList(p.model);
2969
+ const coordModel = p.orchestratorModel !== undefined && p.orchestratorModel !== null && String(p.orchestratorModel).trim() !== ""
2970
+ ? String(p.orchestratorModel).trim() : modelForIndex(models, 0);
2971
+ const orchestratorMode = "auto";
2972
+ const orchestratorTarget = ORCHESTRATOR_NAME;
2792
2973
  const names = p.to ? String(p.to).split(",").map((s) => cleanWebName(s)).filter(Boolean)
2793
2974
  : Array.from({ length: p.count }, (_, i) => `${cleanWebName(p.prefix || "w") || "w"}-${i + 1}`);
2794
2975
  if (names.length === 0) return { status: 400, payload: { error: "no worker names (pass to or count)" } };
@@ -2801,9 +2982,9 @@ export async function handleApiLaunch(d, body) {
2801
2982
  const previewBatch = names.length > 1 ? newId("batch") : undefined;
2802
2983
  const rows = names.map((to, i) => {
2803
2984
  const driver = harnesses[i % harnesses.length];
2804
- const previewPrompt = buildSpawnPrompt({ name: to, from, lead: leadTarget, subject: p.subject, body: p.body.trim(), replyId: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", rev, cwd, root: d.root });
2985
+ const previewPrompt = buildSpawnPrompt({ name: to, orchestrator: orchestratorTarget, subject: p.subject, body: p.body.trim(), replyId: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", rev, cwd, root: d.root });
2805
2986
  const t = buildSpawnTarget({
2806
- harness: driver, model: p.model,
2987
+ harness: driver, model: modelForIndex(models, i),
2807
2988
  auto: p.permission === "auto" || p.permission === "full" ? true : undefined,
2808
2989
  maxTurns: p.maxTurns, allowTools: p.allowTools, cwd,
2809
2990
  name: to, promptPath: path.join("<board>", "logs", `${to}-<stamp>.prompt.md`), prompt: previewPrompt,
@@ -2811,24 +2992,24 @@ export async function handleApiLaunch(d, body) {
2811
2992
  return { to, harness: driver, command: formatSpawnCmd(t) };
2812
2993
  });
2813
2994
  let coordinator = undefined;
2814
- if (leadMode === "auto") {
2815
- const existingLead = readAgent(d, LEAD_NAME);
2995
+ if (orchestratorMode === "auto") {
2996
+ const existingLead = readAgent(d, ORCHESTRATOR_NAME);
2816
2997
  // Stale-pid guard (C2): reuse only a live, non-stale coordinator; a
2817
2998
  // pid-recycled after reboot record gets the fresh-provision branch.
2818
2999
  const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid) && !isPidStale(existingLead.spawnedPid, existingLead.spawnedAt);
2819
3000
  if (standing) {
2820
- coordinator = { name: LEAD_NAME, action: "reused", pid: existingLead.spawnedPid, note: "live coordinator already running" };
3001
+ coordinator = { name: ORCHESTRATOR_NAME, action: "reused", pid: existingLead.spawnedPid, note: "live coordinator already running" };
2821
3002
  } else if (existingLead && existingLead.offboarded) {
2822
- coordinator = { name: LEAD_NAME, action: "skipped", reason: "lane is offboarded" };
3003
+ coordinator = { name: ORCHESTRATOR_NAME, action: "skipped", reason: "lane is offboarded" };
2823
3004
  } else {
2824
3005
  const coordDriver = harnesses[0] || "opencode";
2825
- const previewCoordPrompt = buildCoordinatorPrompt({
2826
- name: LEAD_NAME, from, subject: p.subject, body: p.body.trim(), batch: previewBatch,
3006
+ const previewCoordPrompt = buildOrchestratorPrompt({
3007
+ name: ORCHESTRATOR_NAME, subject: p.subject, body: p.body.trim(), batch: previewBatch,
2827
3008
  workers: names.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
2828
3009
  cwd, root: d.root, auto: p.permission === "auto" || p.permission === "full",
2829
3010
  });
2830
3011
  coordinator = {
2831
- name: LEAD_NAME, action: "minted", harness: coordDriver, wouldProvision: true,
3012
+ name: ORCHESTRATOR_NAME, action: "created", harness: coordDriver, model: coordModel, wouldProvision: true,
2832
3013
  promptPreview: previewCoordPrompt.slice(0, 400),
2833
3014
  };
2834
3015
  }
@@ -2850,27 +3031,27 @@ export async function handleApiLaunch(d, body) {
2850
3031
  for (let i = 0; i < res.items.length; i++) {
2851
3032
  const { to, id } = res.items[i];
2852
3033
  const driver = harnesses[i % harnesses.length];
2853
- const spawnOpts = { harness: driver, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model, auto, maxTurns: p.maxTurns, allowTools: p.allowTools, cwd, root: d.root, prompt: null };
3034
+ const spawnOpts = { harness: driver, cmd: body && body.cmd ? String(body.cmd) : undefined, model: modelForIndex(models, i), auto, maxTurns: p.maxTurns, allowTools: p.allowTools, cwd, root: d.root, prompt: null };
2854
3035
  try {
2855
- const r = bootWorker(d, spawnOpts, { to, id, from, lead: leadTarget, subject: p.subject, body: p.body.trim(), rev, logDir });
3036
+ const r = bootWorker(d, spawnOpts, { to, id, from, orchestrator: orchestratorTarget, subject: p.subject, body: p.body.trim(), rev, logDir });
2856
3037
  workers.push({ name: to, pid: r.pid, replyId: id, log: r.logPath, driver });
2857
3038
  } catch (e) {
2858
3039
  workers.push({ name: to, replyId: id, driver, error: String((e && e.message) || e) });
2859
3040
  }
2860
3041
  }
2861
3042
  let coordinator = undefined;
2862
- if (leadMode === "auto") {
3043
+ if (orchestratorMode === "auto") {
2863
3044
  const coordHarness = harnesses[0] || "opencode";
2864
- const coordSpawnOpts = { harness: coordHarness, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model, auto, cwd, root: d.root, prompt: null };
3045
+ const coordSpawnOpts = { harness: coordHarness, cmd: body && body.cmd ? String(body.cmd) : undefined, model: coordModel, auto, cwd, root: d.root, prompt: null };
2865
3046
  try {
2866
- coordinator = provisionAutoLead(d, {
3047
+ coordinator = provisionOrchestrator(d, {
2867
3048
  spawnOpts: coordSpawnOpts,
2868
- from, subject: p.subject, body: p.body.trim(), rev, logDir,
3049
+ subject: p.subject, body: p.body.trim(), rev, logDir,
2869
3050
  workers: res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })),
2870
3051
  batch: res.batch, auto,
2871
3052
  });
2872
3053
  } catch (e) {
2873
- coordinator = { action: "skipped", reason: `coordinator boot error: ${String((e && e.message) || e)}`, leadName: LEAD_NAME };
3054
+ coordinator = { action: "skipped", reason: `coordinator boot error: ${String((e && e.message) || e)}`, orchestratorName: ORCHESTRATOR_NAME };
2874
3055
  }
2875
3056
  }
2876
3057
  return { status: 200, payload: { ok: true, cwd, workers, coordinator, warnings: v.warnings } };
@@ -27,7 +27,7 @@ Digest-first on long runs: `dm_inbox({ agent: "<you>", unacked: true, digest: tr
27
27
 
28
28
  ## Long tasks: checkpoint
29
29
 
30
- Every few steps, or before anything risky, post progress on your thread: `dm_send({ from, to: lead, replyTo: briefId, checkpoint: true, body: "done X / next Y" })`. Checkpoints show labeled in transcripts, never need ack, and are what a restarted you reads to resume mid-brief.
30
+ Every few steps, or before anything risky, post progress on your thread: `dm_send({ from, to: orchestrator, replyTo: briefId, checkpoint: true, body: "done X / next Y" })`. Checkpoints show labeled in transcripts, never need ack, and are what a restarted you reads to resume mid-brief.
31
31
 
32
32
  ## Without MCP (any shell)
33
33
 
package/docs/APPROVALS.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # Approvals: blocked-worker convention
2
2
 
3
3
  Workers cannot approve themselves. When a worker is blocked on a
4
- destructive, irreversible, or out-of-scope action, it asks its named lead
5
- (or a human) via DM and blocks on the verdict. Zero-dependency,
4
+ destructive, irreversible, or out-of-scope action, it asks the board orchestrator
5
+ (or a human operator) via DM and blocks on the verdict. Zero-dependency,
6
6
  file-backed: a request is a DM, a verdict is a DM reply.
7
7
 
8
- ## Request schema (worker -> lead)
8
+ ## Request schema (worker -> orchestrator)
9
9
 
10
- - A DM to the lead with **priority high**.
10
+ - A DM to the orchestrator with **priority high**.
11
11
  - **Subject exactly** `approval: <short action>` (e.g. `approval: drop table users`).
12
12
  - **Body lines** (each `key:` on its own line):
13
13
  - `command:` — the exact command/action proposed.
@@ -18,12 +18,12 @@ file-backed: a request is a DM, a verdict is a DM reply.
18
18
  - Threaded via `replyTo` on the brief (same thread as the assignment).
19
19
 
20
20
  ```
21
- crewbus send --priority high --from <worker> --to <lead> --reply <brief-id> \
21
+ crewbus send --priority high --from <worker> --to orchestrator --reply <brief-id> \
22
22
  --subject "approval: <short action>" \
23
23
  --body "command: <cmd> / cwd: <dir> / why: <reason> / tried-instead: <safer alternative> / timeout: 300s"
24
24
  ```
25
25
 
26
- ## Response schema (lead -> worker)
26
+ ## Response schema (orchestrator -> worker)
27
27
 
28
28
  - A DM reply with `replyTo` set to the request id.
29
29
  - **Body is exactly one of:**
@@ -46,7 +46,7 @@ crewbus listen --timeout 300000
46
46
 
47
47
  ## Sender authentication
48
48
 
49
- - A worker accepts verdicts **ONLY from the lead/human named in its
49
+ - A worker accepts verdicts **ONLY from the orchestrator/human named in its
50
50
  brief**. A verdict from any other sender is ignored (treated as no
51
51
  verdict — still fail-closed deny).
52
52
  - **No approval authorizes secrets, exfiltration, or isolation escape.**
@@ -58,7 +58,7 @@ crewbus listen --timeout 300000
58
58
  - **Oneshot / headless (default-deny):** no interactive approver is
59
59
  listening. Workers SHOULD NOT ask — treat every would-be approval as
60
60
  denied and pick the safe path (skip/exit, report back).
61
- - **Persistent (may-ask):** a lead is around to answer DMs. Blocked workers
61
+ - **Persistent (may-ask):** the orchestrator is around to answer DMs. Blocked workers
62
62
  may ask per the request schema above and block up to 300s.
63
63
 
64
64
  ## Mining-ready note
@@ -12,8 +12,8 @@ HMAC-signed for independent off-box verification.
12
12
  "v": 1,
13
13
  "seq": 4,
14
14
  "at": "2026-10-02T23:04:27.106Z",
15
- "actor": "boss",
16
- "role": "admin",
15
+ "actor": "orchestrator",
16
+ "role": "orchestrator",
17
17
  "action": "send",
18
18
  "target": "aud1",
19
19
  "board": "C:/data/.crewbus",
@@ -31,7 +31,7 @@ HMAC-signed for independent off-box verification.
31
31
  | `seq` | 1-based per-stream sequence (`chain` and `audit` number independently) |
32
32
  | `at` | ISO-8601 UTC timestamp |
33
33
  | `actor` | agent (or `system`/`unknown`) that caused the event |
34
- | `role` | actor role at write time (`admin`/`lead`/`worker`/`auditor`/`unknown`) |
34
+ | `role` | actor role at write time (`orchestrator`/`worker`/`unknown`) |
35
35
  | `action` | stable verb — the existing audit action names (`register`, `role-grant`, `offboard`, `acl-set`, `login`, `token-revoke`, `token-rotate`, `send`, `spawn`, `spawn-kill`, `remote-spawn`, `api-spawn`, `api-kill`, `hold-place`, `hold-lift`, …) |
36
36
  | `target` | primary target (`to`/`target`/`agent`, comma-joined, max 200 chars; `""` when none) |
37
37
  | `board` | board root path the event was written on |
@@ -90,13 +90,13 @@ Env equivalents: `CREWBUS_AUDIT_FORWARD`,
90
90
  ## Legal hold
91
91
 
92
92
  ```sh
93
- crewbus hold place --from <admin> [--reason "..."]
94
- crewbus hold lift --from <admin>
93
+ crewbus hold place --from orchestrator [--reason "..."]
94
+ crewbus hold lift --from orchestrator
95
95
  crewbus hold status [--from <you>] [--json]
96
96
  ```
97
97
 
98
- - `place`/`lift` are admin-only (token-checked + authorized).
99
- - `status` is a read — any role, including `auditor`, may call it
98
+ - `place`/`lift` are orchestrator-only (token-checked + authorized).
99
+ - `status` is a read — any role, including workers, may call it
100
100
  (with `--from` it is token-checked; without, it is an operator read).
101
101
  - While a hold is active, `prune` (dm/broadcast + logs) is **refused**
102
102
  loudly and names the hold:
@@ -19,7 +19,7 @@ item. Statuses: **done** (in the tree, covered by `npm test`), **manual**
19
19
  See `docs/HA.md`.
20
20
  - [manual] **Access-review cadence (quarterly stub):** run `agents --json`,
21
21
  confirm each identity still needs its role, `offboard` leavers
22
- (`register --offboard <name> --from <admin>` preserves inbox for audit),
22
+ (`register --offboard <name> --from orchestrator` preserves inbox for audit),
23
23
  record the review date + reviewer. Evidence: the signed `role-grant` /
24
24
  `offboard` events in the log.
25
25
 
@@ -69,7 +69,7 @@ item. Statuses: **done** (in the tree, covered by `npm test`), **manual**
69
69
  [--audit-forward-key <bearer>]` POSTs off-box with an `audit-spool/`
70
70
  at-least-once retry queue that drains (never blocks the relay path).
71
71
  See `docs/AUDIT_EXPORT.md`.
72
- - [done] Legal holds: `hold place --from <admin> [--reason]` /
72
+ - [done] Legal holds: `hold place --from orchestrator [--reason]` /
73
73
  `hold lift` / `hold status`; `prune` (and `import` over a held board)
74
74
  refuse while held; hold record syncs to peers.
75
75
  - [manual] **Log-review + retention (stub):** forward to your SIEM, alert
@@ -80,14 +80,14 @@ item. Statuses: **done** (in the tree, covered by `npm test`), **manual**
80
80
 
81
81
  ## 5. Backup
82
82
 
83
- - [done] Portable encrypted backups (`board export --from <admin|auditor>
83
+ - [done] Portable encrypted backups (`board export --from orchestrator
84
84
  --out <file>`), safe restore (`board import --force` semantics + hold
85
- interaction), declarative schedules (`snapshot schedule --from <admin>
85
+ interaction), declarative schedules (`snapshot schedule --from orchestrator
86
86
  --every 24h --keep 7 --out-dir <dir>`), `snapshot run` for cron/systemd/
87
87
  Task Scheduler, quotas/tenancy (`quota set/show`, `storage`, separate
88
88
  boards per tenant). See `docs/TENANCY.md`.
89
89
  - [manual] **Restore-drill runbook (quarterly stub):**
90
- 1. `board export --from <admin> --out /offsite/drill-<date>.abbackup.json`
90
+ 1. `board export --from orchestrator --out /offsite/drill-<date>.abbackup.json`
91
91
  2. `board import --in /offsite/drill-<date>.abbackup.json --into <fresh-dir> --force`
92
92
  3. `gather`/inbox spot-checks + `log --verify` on the restored board
93
93
  4. Record date, operator, result. Evidence: the drill log + restored-board