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.
Files changed (53) hide show
  1. package/AGENTS.template.md +4 -4
  2. package/CHANGELOG.md +151 -0
  3. package/README.md +713 -706
  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 +486 -355
  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 +92 -152
  12. package/bin/lib/launch.js +128 -30
  13. package/bin/lib/qrcode.js +2971 -0
  14. package/bin/lib/relay.js +26 -54
  15. package/bin/lib/spawn.js +241 -194
  16. package/bin/lib/store.js +2 -2
  17. package/bin/lib/web.js +277 -59
  18. package/claude-plugin/skills/crewbus/SKILL.md +1 -1
  19. package/docs/APPROVALS.md +8 -8
  20. package/docs/AUDIT_EXPORT.md +7 -7
  21. package/docs/CERT_READINESS.md +120 -120
  22. package/docs/COMPATIBILITY.md +196 -194
  23. package/docs/CONSOLIDATOR.md +6 -6
  24. package/docs/CONTROL_PLANE_SPEC.md +12 -14
  25. package/docs/CREWS.md +16 -13
  26. package/docs/DELIVERY.md +213 -210
  27. package/docs/GROUPS.md +8 -8
  28. package/docs/HA.md +151 -151
  29. package/docs/IDENTITY.md +6 -6
  30. package/docs/LEAD_ASSIGN.md +3 -85
  31. package/docs/LONG_RUNS.md +3 -3
  32. package/docs/M1_CLI_DRAFT.md +9 -9
  33. package/docs/ORCHESTRATOR.md +87 -0
  34. package/docs/PAIRING.md +7 -7
  35. package/docs/QUICKSTART.md +24 -13
  36. package/docs/RBAC.md +84 -73
  37. package/docs/SPLIT.md +82 -82
  38. package/docs/TENANCY.md +10 -10
  39. package/docs/THREAT_MODEL.md +68 -69
  40. package/docs/VERIFIER.md +10 -10
  41. package/docs/VERSION_SKEW.md +57 -57
  42. package/documentation.html +37 -29
  43. package/examples/hermes-pairing.md +3 -3
  44. package/examples/t3-pairing.md +1 -1
  45. package/index.html +13 -14
  46. package/opencode/plugins/dm-watch.js +1 -1
  47. package/opencode/tools/dm-send.js +4 -13
  48. package/package.json +75 -50
  49. package/packages/client-runtime/README.md +40 -40
  50. package/packages/contracts/harness.json +108 -111
  51. package/packages/contracts/launch.json +2 -3
  52. package/packages/contracts/pairing.json +3 -3
  53. package/docs/DESKTOP_SPIKE.md +0 -223
package/bin/lib/store.js CHANGED
@@ -219,7 +219,7 @@ export function getFlag(args, flag) { // line 658
219
219
 
220
220
  // Positional args with flag values removed (so `send --from alice --to bob`
221
221
  // with no body doesn't mistake "alice bob" for a message).
222
- export const VALUE_FLAGS = new Set(["--from", "--to", "--to-file", "--to-group", "--body", "--subject", "--reply", "--replyTo", "--session", "--board", "--limit", "--after", "--timeout", "--id", "--harness", "--cmd", "--cwd", "--model", "--max-turns", "--allow-tools", "--window", "--older-than", "--lines", "--token", "--port", "--host", "--group", "--add", "--batch", "--with", "--interval", "--count", "--prefix", "--max-spawn", "--pool-size", "--pool", "--queue", "--agents", "--iters", "--scope", "--ttl", "--worktree", "--branch", "--grep", "--priority", "--max-chars", "--cursor", "--verify", "--msg", "--artifact"]); // line 665
222
+ export const VALUE_FLAGS = new Set(["--from", "--to", "--to-file", "--to-group", "--body", "--subject", "--reply", "--replyTo", "--session", "--board", "--limit", "--after", "--timeout", "--id", "--harness", "--cmd", "--cwd", "--model", "--orchestrator-model", "--max-turns", "--allow-tools", "--window", "--older-than", "--lines", "--token", "--port", "--host", "--group", "--add", "--batch", "--with", "--interval", "--count", "--prefix", "--max-spawn", "--pool-size", "--pool", "--queue", "--agents", "--iters", "--scope", "--ttl", "--worktree", "--branch", "--grep", "--priority", "--max-chars", "--cursor", "--verify", "--msg", "--artifact", "--registry"]); // line 665
223
223
 
224
224
  // Comma-separated recipients: `--to alice,bob,carol` fans out one DM per
225
225
  // recipient (same body/subject, unique id each). Keeps the DM-only model
@@ -232,7 +232,7 @@ for (const _f of ["--sender-type", "--fwd", "--secret", "--device", "--pair-toke
232
232
  export function cleanSenderType(raw) { // line 1181
233
233
  if (raw === undefined || raw === null || String(raw).trim() === "") return undefined;
234
234
  const t = String(raw).trim().toLowerCase();
235
- if (!["human", "lead", "peer"].includes(t)) fail(`--sender-type must be human|lead|peer (got "${raw}")`);
235
+ if (!["human", "orchestrator", "peer"].includes(t)) fail(`--sender-type must be human|orchestrator|peer (got "${raw}")`);
236
236
  return t;
237
237
  }
238
238
 
package/bin/lib/web.js CHANGED
@@ -13,13 +13,15 @@
13
13
  // monolith lines ~692-1010) — export crew must add them for web.js to link.
14
14
 
15
15
  import fs from "node:fs";
16
+ import { spawn } from "node:child_process";
16
17
  import path from "node:path";
17
18
  import http from "node:http";
18
19
  import { fileURLToPath } from "node:url";
19
20
  import { boardDir, requireBoard, getFlag, fail, writeJson, listJson, cleanWebName, readJson, readBoardMeta, writeBoardMeta, gitRevForBoard, newId, MAX_SPAWN, MAX_BODY_CHARS } from "./store.js";
20
- import { readAgent, agentTokenMatches, authorizeCheck, ensureLoopbackOperator, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
21
+ import { readAgent, agentTokenMatches, authorizeCheck, ensureOrchestrator, mintToken, newSalt, hashToken, touchAgent } from "./identity.js";
21
22
  import { readDMs, readVisible, ackedIds, ackedIdSet, findMessageById, deliverDMs, parseRecipients } from "./mail.js";
22
- import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim, buildCoordinatorPrompt, provisionAutoLead, LEAD_NAME, isPidStale } from "./spawn.js";
23
+ import { workerStatus, pidAlive, killWorkers, bootWorker, buildSpawnPrompt, buildSpawnTarget, formatSpawnCmd, installCliToUserPath, ensureBoardCliShim, buildOrchestratorPrompt, provisionOrchestrator,
24
+ ORCHESTRATOR_NAME, isPidStale, parseModelList, modelForIndex } from "./spawn.js";
23
25
  import { groupTelemetryData, collectBatch, gatherTelemetry, listBatches } from "./groups.js";
24
26
  import { httpJson } from "./sync.js";
25
27
  import { readChainRecords, verifyChainRecords, appendChainRecord, readHold, readBoardQuotas } from "./export.js";
@@ -783,10 +785,9 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
783
785
  <button type="button" data-perm="auto">auto</button>
784
786
  <button type="button" data-perm="full">full</button>
785
787
  </span>
786
- <span class="dim" style="margin-left:8px">Coordinator:</span>
787
- <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">
788
- <option value="auto">auto (Observer coordinator)</option>
789
- <option value="none">none (direct to me)</option>
788
+ <span class="dim" style="margin-left:8px">Orchestrator:</span>
789
+ <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">
790
+ <option value="auto">auto (board orchestrator)</option>
790
791
  </select>
791
792
  <label class="dim" style="cursor:pointer;margin-left:6px"><input id="launch-dry" type="checkbox" checked> Dry-run</label>
792
793
  </div>
@@ -807,7 +808,7 @@ details.tech-details summary{cursor:pointer;font-weight:500;user-select:none}
807
808
 
808
809
  <div class="composer-bottom">
809
810
  <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>
811
+ <span class="dim">launching as <b id="launch-as">orchestrator</b> (auto)</span>
811
812
  <input id="launch-from" type="hidden" value="">
812
813
  <input id="launch-token" type="password" style="display:none" value="">
813
814
  </div>
@@ -1015,7 +1016,7 @@ function markIdent(){
1015
1016
  try{
1016
1017
  var man=document.getElementById('launch-from-manual');
1017
1018
  var lbl=document.getElementById('launch-as');
1018
- if(lbl)lbl.textContent=(man&&man.value.trim())||lf.value.trim()||c.from||'lead';
1019
+ if(lbl)lbl.textContent=(man&&man.value.trim())||lf.value.trim()||c.from||'orchestrator';
1019
1020
  }catch(_){}
1020
1021
  }
1021
1022
  async function autoLoadOperatorCreds(){
@@ -1211,9 +1212,9 @@ async function refresh(){
1211
1212
  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
1213
  }).join('')||'<tr><td colspan="4" class="dim">inbox zero for '+esc(c.from)+'</td></tr>';
1213
1214
  var ap=(tj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
1214
- if(c.from!=='lead'){
1215
+ if(c.from!=='orchestrator'){
1215
1216
  try{
1216
- var lr=await fetch('/api/inbox?agent=lead&unacked=1&limit=50',{cache:'no-store'});
1217
+ var lr=await fetch('/api/inbox?agent=orchestrator&unacked=1&limit=50',{cache:'no-store'});
1217
1218
  if(lr.ok){
1218
1219
  var lj=await lr.json();
1219
1220
  var lap=(lj.items||[]).filter(function(m){return m.subject&&m.subject.indexOf('approval: ')===0;});
@@ -1225,7 +1226,7 @@ async function refresh(){
1225
1226
  }catch(_){}
1226
1227
  }
1227
1228
  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>':'';
1229
+ 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
1230
  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
1231
  }).join('')||'<tr><td colspan="5" class="dim">no approval requests for '+esc(c.from)+'</td></tr>';
1231
1232
  }else{
@@ -1512,19 +1513,19 @@ async function doLaunch(dry){
1512
1513
  if(j.dryRun){
1513
1514
  var warn=(j.warnings||[]).length?('warnings: '+j.warnings.join('; ')+'\\n'):'';
1514
1515
  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||'')+')'))):'';
1516
+ 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
1517
  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
1518
  }else{
1518
1519
  try{showUndoToast((j.workers||[]).map(function(w){return w.name;}));}catch(_){}
1519
1520
  var cwdNotice=j.cwd?(' [cwd: '+j.cwd+']'):'';
1520
1521
  var coordNotice='';
1521
1522
  if(j.coordinator){
1522
- if(j.coordinator.action==='minted'&&j.coordinator.pid){
1523
- coordNotice=' · coordinator: lead (pid '+j.coordinator.pid+')';
1523
+ if(j.coordinator.action==='created'&&j.coordinator.pid){
1524
+ coordNotice=' · orchestrator: pid '+j.coordinator.pid;
1524
1525
  }else if(j.coordinator.action==='reused'){
1525
- coordNotice=' · coordinator: lead (reused'+(j.coordinator.pid?' pid '+j.coordinator.pid:'')+')';
1526
+ coordNotice=' · orchestrator: reused'+(j.coordinator.pid?' pid '+j.coordinator.pid:'');
1526
1527
  }else if(j.coordinator.reason){
1527
- coordNotice=' · coordinator: skipped ('+j.coordinator.reason+')';
1528
+ coordNotice=' · orchestrator: skipped ('+j.coordinator.reason+')';
1528
1529
  }
1529
1530
  }
1530
1531
  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;
@@ -1657,7 +1658,7 @@ function paletteActivate(m){
1657
1658
  else if(m.action==='openfolder'){document.getElementById('open-folder-btn').click();}
1658
1659
  else if(m.action==='pairmobile'){
1659
1660
  try{window.parent.postMessage({type:'crewbus:open-pair', dashboard: location.origin},'*');}catch(_){}
1660
- try{window.open('./pair.html','_blank','width=420,height=560');}catch(_){}
1661
+ try{window.open('/pair','_blank','width=420,height=560');}catch(_){}
1661
1662
  }
1662
1663
  else if(m.action==='refresh'){refresh();}
1663
1664
  else if(m.action==='installcli'){document.getElementById('pop-install-cli-btn').click();}
@@ -1889,7 +1890,7 @@ document.getElementById('copy-board-btn').onclick=copyBoardPath;
1889
1890
  var ppb=document.getElementById('pop-pair-btn');
1890
1891
  if(ppb){ppb.onclick=function(){
1891
1892
  try{window.parent.postMessage({type:'crewbus:open-pair', dashboard: location.origin},'*');}catch(_){}
1892
- try{window.open('./pair.html','_blank','width=420,height=560');}catch(_){}
1893
+ try{window.open('/pair','_blank','width=420,height=560');}catch(_){}
1893
1894
  };}
1894
1895
  var picb=document.getElementById('pop-install-cli-btn');
1895
1896
  if(picb){picb.onclick=async function(){
@@ -2107,7 +2108,215 @@ export const readKillBody = (req) =>
2107
2108
 
2108
2109
  // Shared web dashboard API routes for both `crewbus web` and `crewbus serve`
2109
2110
  // (embedded Tauri webview). Returns true if the route was handled, false otherwise.
2111
+
2112
+ let _qrSrc = null;
2113
+ function getQrSrc() {
2114
+ if (_qrSrc === null) {
2115
+ try {
2116
+ _qrSrc = fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "qrcode.js"), "utf8");
2117
+ } catch {
2118
+ _qrSrc = "";
2119
+ }
2120
+ }
2121
+ return _qrSrc;
2122
+ }
2123
+
2124
+ export function renderPairHtml(root) {
2125
+ const qrCodeSrc = getQrSrc();
2126
+ return `<!DOCTYPE html>
2127
+ <html lang="en">
2128
+ <head>
2129
+ <meta charset="utf-8">
2130
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2131
+ <title>Pair Mobile Client — CrewBus</title>
2132
+ <script>
2133
+ try{var __t=null;try{__t=localStorage.getItem('crewbus-theme')||localStorage.getItem('crewbus-desktop-theme');}catch(_){}if(__t==='light'||__t==='dark'){document.documentElement.setAttribute('data-theme',__t);}}catch(_){}
2134
+ </script>
2135
+ <style>
2136
+ :root{
2137
+ --bg:#f4f6f3;
2138
+ --panel:#ffffff;
2139
+ --ink:#14201a;
2140
+ --dim:#5b6a62;
2141
+ --acc:#5b6a62;
2142
+ --acc-ink:#ffffff;
2143
+ --warn:#b86e00;
2144
+ --line:#d5ddd7;
2145
+ --scroll:rgba(0,0,0,.18);
2146
+ --scroll-hi:rgba(0,0,0,.32);
2147
+ --danger:#f85149;
2148
+ --danger-bg:rgba(248,81,73,0.12);
2149
+ --ok:#3d8f66;
2150
+ }
2151
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
2152
+ --bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#8b98a5;--acc-ink:#07130d;--warn:#ffb454;--line:#2a343e;
2153
+ --scroll:rgba(255,255,255,.16);
2154
+ --scroll-hi:rgba(255,255,255,.32);
2155
+ --ok:#4fb07f;
2156
+ }}
2157
+ :root[data-theme="light"]{--bg:#f4f6f3;--panel:#ffffff;--ink:#14201a;--dim:#5b6a62;--acc:#5b6a62;--acc-ink:#ffffff;--warn:#b86e00;--line:#d5ddd7;--scroll:rgba(0,0,0,.18);--scroll-hi:rgba(0,0,0,.32);--ok:#3d8f66}
2158
+ :root[data-theme="dark"]{--bg:#0f1419;--panel:#182028;--ink:#e3e9ee;--dim:#8b98a5;--acc:#8b98a5;--acc-ink:#07130d;--warn:#ffb454;--line:#2a343e;--scroll:rgba(255,255,255,.16);--scroll-hi:rgba(255,255,255,.32);--ok:#4fb07f}
2159
+ * {
2160
+ box-sizing:border-box;
2161
+ scrollbar-width: thin;
2162
+ scrollbar-color: var(--scroll) transparent;
2163
+ }
2164
+ body{margin:0;background:var(--bg);color:var(--ink);font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;padding:20px}
2165
+ h2{margin:0 0 6px;font-size:17px;font-weight:700;color:var(--ink)}
2166
+ .dim{color:var(--dim);font-size:12px;line-height:1.4}
2167
+ #qr-wrap{width:220px;height:220px;margin:16px auto;border:1px solid var(--line);background:var(--panel);border-radius:12px;display:flex;align-items:center;justify-content:center;text-align:center;padding:10px;overflow:hidden}
2168
+ #qr-wrap svg{width:100%;height:100%;display:block;border-radius:6px}
2169
+ #qr{color:var(--dim);font-size:12px}
2170
+ textarea{width:100%;background:var(--panel);border:1px solid var(--line);color:var(--ink);border-radius:8px;padding:8px 10px;font-size:12px;resize:vertical;font-family:monospace}
2171
+ textarea:focus{border-color:var(--acc);outline:none}
2172
+ .btn-row{display:flex;gap:8px;margin-top:10px}
2173
+ button{background:var(--panel);border:1px solid var(--line);color:var(--ink);border-radius:6px;padding:7px 14px;font-size:12px;font-weight:600;cursor:pointer;transition:all .15s}
2174
+ button:hover{border-color:var(--acc);color:var(--acc)}
2175
+ button.primary{background:var(--acc);border-color:var(--acc);color:var(--acc-ink)}
2176
+ button.primary:hover{filter:brightness(1.1)}
2177
+ #msg{min-height:1.5em;margin-top:10px;font-size:12px}
2178
+ .warn{color:var(--danger)}
2179
+ .ok{color:var(--ok)}
2180
+ </style>
2181
+ </head>
2182
+ <body>
2183
+ <h2>Pair Mobile Client</h2>
2184
+ <p class="dim">A one-time pairing link is minted automatically from the local
2185
+ board — scan the QR with CrewBus Mobile. (Advanced: paste a
2186
+ <code>crewbus://pair</code> URL from <code>relay pair qr</code> or
2187
+ <code>serve --pair-qrcode</code> to render it instead.)</p>
2188
+
2189
+ <div id="qr-wrap">
2190
+ <div id="qr" aria-label="pairing QR">QR code will appear here after rendering</div>
2191
+ </div>
2192
+
2193
+ <label class="dim" for="pair-url">Pairing URL (in-memory only, secret in #fragment never saved):</label>
2194
+ <textarea id="pair-url" rows="3" placeholder="crewbus://pair?env=…&amp;routes=…&amp;caps=…#abp-…"></textarea>
2195
+
2196
+ <div class="btn-row">
2197
+ <button id="pair-render" class="primary">Render QR</button>
2198
+ <button id="pair-clear">Clear</button>
2199
+ </div>
2200
+
2201
+ <div id="msg" class="dim" role="status"></div>
2202
+ <script type="module">
2203
+ ${qrCodeSrc}
2204
+
2205
+ var box = document.getElementById('pair-url');
2206
+ var qr = document.getElementById('qr');
2207
+ var qrWrap = document.getElementById('qr-wrap') || (qr ? qr.parentElement : null);
2208
+ var msg = document.getElementById('msg');
2209
+ var renderBtn = document.getElementById('pair-render');
2210
+ var clearBtn = document.getElementById('pair-clear');
2211
+
2212
+ function say(t, isErr) {
2213
+ if (!msg) return;
2214
+ msg.textContent = t;
2215
+ msg.className = isErr ? 'warn' : 'ok';
2216
+ }
2217
+
2218
+ function qrThemeColors() {
2219
+ var theme = null;
2220
+ try { theme = localStorage.getItem('crewbus-theme') || localStorage.getItem('crewbus-desktop-theme'); } catch (_) {}
2221
+ if (theme !== 'light' && theme !== 'dark') {
2222
+ try { theme = document.documentElement.getAttribute('data-theme'); } catch (_) {}
2223
+ }
2224
+ if (theme !== 'light' && theme !== 'dark') {
2225
+ try { theme = (window.matchMedia && window.matchMedia('(prefers-color-scheme:dark)').matches) ? 'dark' : 'light'; }
2226
+ catch (_) { theme = 'light'; }
2227
+ }
2228
+ if (theme === 'dark') return { dark: '#e3e9ee', light: '#182028' };
2229
+ return { dark: '#14201a', light: '#ffffff' };
2230
+ }
2231
+
2232
+ function validatePairUrl(raw) {
2233
+ var s = String(raw == null ? '' : raw).trim();
2234
+ if (!s.startsWith('crewbus://pair')) throw new Error('not a crewbus pair URL');
2235
+ var u = new URL(s);
2236
+ for (var p of u.searchParams) {
2237
+ var k = p[0].toLowerCase();
2238
+ var v = p[1];
2239
+ if (['secret', 'token', 'pairtoken', 'pair_token', 'pair-token', 'credential'].indexOf(k) !== -1 || v.startsWith('abp-')) {
2240
+ throw new Error('pairing secret in query — secrets travel in #fragment only');
2241
+ }
2242
+ }
2243
+ var frag = u.hash ? decodeURIComponent(u.hash.slice(1)) : '';
2244
+ if (!frag) throw new Error('missing #fragment pairing secret');
2245
+ if (!frag.startsWith('abp-')) throw new Error('fragment is not a pairing secret (want abp-...)');
2246
+ return { env: u.searchParams.get('env') || '(local)', pairToken: frag };
2247
+ }
2248
+
2249
+ function describeForDisplay(u) {
2250
+ return String(u).split('#')[0];
2251
+ }
2252
+
2253
+ function clearAll() {
2254
+ if (box) box.value = '';
2255
+ if (qrWrap) qrWrap.innerHTML = '<div id="qr" aria-label="pairing QR">QR code will appear here after rendering</div>';
2256
+ qr = document.getElementById('qr');
2257
+ say('');
2258
+ }
2259
+
2260
+ function renderUrl(raw) {
2261
+ var parsed = validatePairUrl(raw);
2262
+ var svg = renderQrSvg(raw.trim(), {
2263
+ width: 200,
2264
+ margin: 1,
2265
+ color: qrThemeColors(),
2266
+ });
2267
+ if (qrWrap) qrWrap.innerHTML = svg;
2268
+ say('QR code ready for ' + describeForDisplay(raw) + ' — scan with CrewBus Mobile.');
2269
+ }
2270
+
2271
+ if (renderBtn) {
2272
+ renderBtn.addEventListener('click', function () {
2273
+ var raw = box ? box.value : '';
2274
+ if (!raw.trim()) { say('paste a pair URL first', true); return; }
2275
+ try {
2276
+ renderUrl(raw);
2277
+ } catch (e) {
2278
+ say('rejected: ' + String((e && e.message) || e), true);
2279
+ }
2280
+ });
2281
+ }
2282
+
2283
+ if (clearBtn) {
2284
+ clearBtn.addEventListener('click', clearAll);
2285
+ }
2286
+
2287
+ async function autoMint() {
2288
+ say('minting a one-time pairing link…');
2289
+ try {
2290
+ var r = await fetch('/api/pair-qr', { method: 'POST' });
2291
+ var j = null;
2292
+ try { j = await r.json(); } catch (_) {}
2293
+ if (!r.ok || !j || !j.ok || !j.pairUrl) {
2294
+ say('auto-mint failed (' + (j && j.error ? j.error : ('HTTP ' + r.status)) + ') — paste a pair URL manually', true);
2295
+ return;
2296
+ }
2297
+ if (box) box.value = j.pairUrl;
2298
+ renderUrl(j.pairUrl);
2299
+ var exp = j.expiresAt ? new Date(j.expiresAt) : null;
2300
+ say('QR ready — scan with CrewBus Mobile.' + (exp ? ' Link expires ' + exp.toLocaleTimeString() + ' (single-use).' : ''));
2301
+ } catch (e) {
2302
+ say('auto-mint failed: ' + String((e && e.message) || e) + ' — paste a pair URL manually', true);
2303
+ }
2304
+ }
2305
+
2306
+ autoMint();
2307
+ </script>
2308
+ </body>
2309
+ </html>`;
2310
+ }
2311
+
2110
2312
  export async function handleWebDashboardRoute(req, res, url, d) {
2313
+ if (req.method === "GET" && url.pathname === "/pair") {
2314
+ const body = renderPairHtml(d.root);
2315
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
2316
+ res.end(body);
2317
+ return true;
2318
+ }
2319
+
2111
2320
  if (req.method === "GET" && url.pathname === "/api/board") {
2112
2321
  const body = JSON.stringify(boardSnapshot(d, 300));
2113
2322
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
@@ -2255,7 +2464,7 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2255
2464
  res.end(JSON.stringify({ error: "loopback only" }));
2256
2465
  return true;
2257
2466
  }
2258
- for (const name of ["boss", "lead"]) {
2467
+ for (const name of [ORCHESTRATOR_NAME]) {
2259
2468
  const tokenFile = path.join(d.root, "logs", `${name}.token`);
2260
2469
  let tok = "";
2261
2470
  try { tok = fs.readFileSync(tokenFile, "utf8").trim(); } catch {}
@@ -2358,12 +2567,12 @@ export async function handleWebDashboardRoute(req, res, url, d) {
2358
2567
  const ttlMs = 10 * 60 * 1000;
2359
2568
  const doc = {
2360
2569
  tokenHash: hashToken(token, salt), salt, label: "dashboard-oneclick",
2361
- createdBy: "lead", createdAt: new Date(now).toISOString(),
2570
+ createdBy: ORCHESTRATOR_NAME, createdAt: new Date(now).toISOString(),
2362
2571
  expiresAt: new Date(now + ttlMs).toISOString(),
2363
2572
  };
2364
2573
  fs.mkdirSync(path.join(d.root, "pairing"), { recursive: true });
2365
2574
  writeJson(pairingPath(d, doc.tokenHash), doc);
2366
- try { appendChainRecord(d, "lead", "pair", { label: "dashboard-oneclick", expiresAt: doc.expiresAt }); } catch {}
2575
+ try { appendChainRecord(d, ORCHESTRATOR_NAME, "pair", { label: "dashboard-oneclick", expiresAt: doc.expiresAt }); } catch {}
2367
2576
  const envId = (readRelayState(d) && readRelayState(d).envId) || ("board:" + path.basename(d.root));
2368
2577
  const pairUrl = buildPairUrl({ envId, routes: [], caps: ["hlc", "tombstones", "channels", "revoked", "holds", "launch"], pairToken: token });
2369
2578
  res.writeHead(200, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
@@ -2383,9 +2592,9 @@ export async function cmdWeb(args) {
2383
2592
  ensureBoardCliShim(d);
2384
2593
  const host = getFlag(args, "--host") || "127.0.0.1";
2385
2594
  const port = Number(getFlag(args, "--port") || 0);
2386
- // Desktop plug-and-play: same loopback auto-provision as `serve` (see
2387
- // ensureLoopbackOperator in identity.js). First loopback boot mints `lead`.
2388
- try { ensureLoopbackOperator(d, host); } catch {}
2595
+ // Same local auto-provision as `serve`: the board's single orchestrator is
2596
+ // ensured on boot (minted on first use, token at logs/orchestrator.token).
2597
+ try { ensureOrchestrator(d); } catch {}
2389
2598
  if (!(port >= 0 && port < 65536)) fail("--port must be 0-65535 (0 = random)");
2390
2599
  if (host !== "127.0.0.1" && host !== "localhost" && host !== "::1") {
2391
2600
  process.stderr.write(`crewbus: warning: binding non-local ${host} — the dashboard has no auth, anyone who can reach it can read the board\n`);
@@ -2484,6 +2693,12 @@ export async function cmdWeb(args) {
2484
2693
  res.end(body);
2485
2694
  return;
2486
2695
  }
2696
+ if (req.method === "GET" && url.pathname === "/pair") {
2697
+ const body = renderPairHtml(d.root);
2698
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
2699
+ res.end(body);
2700
+ return;
2701
+ }
2487
2702
  res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
2488
2703
  res.end("not found (try / or /api/board /api/fleet /api/channels /api/results /api/audit /api/holds /api/quotas /api/inbox /api/harnesses /api/routes)");
2489
2704
  } catch (e) {
@@ -2499,7 +2714,15 @@ export async function cmdWeb(args) {
2499
2714
  server.listen(port, host, () => {
2500
2715
  const a = server.address();
2501
2716
  const shown = a && typeof a === "object" ? `${a.address}:${a.port}` : `${host}:${port}`;
2502
- console.log(`crewbus web at http://${shown} [board ${d.root}]`);
2717
+ const webUrl = `http://${shown}`;
2718
+ console.log(`crewbus web at ${webUrl} [board ${d.root}]`);
2719
+ if (args.includes("--open")) {
2720
+ try {
2721
+ if (process.platform === "win32") spawn("cmd.exe", ["/c", "start", webUrl], { detached: true, stdio: "ignore" }).unref();
2722
+ else if (process.platform === "darwin") spawn("open", [webUrl], { detached: true, stdio: "ignore" }).unref();
2723
+ else spawn("xdg-open", [webUrl], { detached: true, stdio: "ignore" }).unref();
2724
+ } catch {}
2725
+ }
2503
2726
  resolve();
2504
2727
  });
2505
2728
  });
@@ -2549,11 +2772,13 @@ export async function handleApiKill(d, body) {
2549
2772
  // CLI); dryRun previews exact commands without booting; live delivers the
2550
2773
  // brief + boots via bootWorker (same core as CLI spawn/remoteSpawn).
2551
2774
  export async function handleApiLaunch(d, body) {
2552
- const from = cleanWebName(body && body.from);
2775
+ const from = ORCHESTRATOR_NAME;
2553
2776
  const token = body && body.token !== undefined && body.token !== null && String(body.token) !== "" ? String(body.token) : undefined;
2554
- if (!from) return { status: 400, payload: { error: "missing from (your agent name)" } };
2555
- const rec = readAgent(d, from);
2556
- if (!rec || !(rec.tokenHash || rec.token) || !agentTokenMatches(rec, token)) return { status: 403, payload: { error: "bad token" } };
2777
+ ensureOrchestrator(d);
2778
+ if (token) {
2779
+ const rec = readAgent(d, from);
2780
+ if (!rec || !(rec.tokenHash || rec.token) || !agentTokenMatches(rec, token)) return { status: 403, payload: { error: "bad token" } };
2781
+ }
2557
2782
  {
2558
2783
  const r = authorizeCheck(d, from, "spawn");
2559
2784
  if (!r.ok) return { status: 403, payload: { error: r.reason } };
@@ -2562,15 +2787,11 @@ export async function handleApiLaunch(d, body) {
2562
2787
  if (!v.ok) return { status: 400, payload: { error: "launch plan invalid", errors: v.errors, warnings: v.warnings } };
2563
2788
  const p = v.plan;
2564
2789
  const harnesses = Array.isArray(p.harnesses) && p.harnesses.length > 0 ? p.harnesses : [p.harness || "opencode"];
2565
- const hasCodingHarness = harnesses.some((h) => h !== "generic");
2566
- let leadMode = p.lead || "auto";
2567
- if (leadMode === "auto") {
2568
- leadMode = hasCodingHarness ? "board" : "none";
2569
- }
2570
- if (leadMode === "board" && !hasCodingHarness) {
2571
- return { status: 400, payload: { error: 'lead "board" needs a coding harness for the auto-coordinator (add a harness like opencode, or use lead "none")' } };
2572
- }
2573
- const leadTarget = leadMode === "board" ? LEAD_NAME : from;
2790
+ const models = Array.isArray(p.models) ? p.models : parseModelList(p.model);
2791
+ const coordModel = p.orchestratorModel !== undefined && p.orchestratorModel !== null && String(p.orchestratorModel).trim() !== ""
2792
+ ? String(p.orchestratorModel).trim() : modelForIndex(models, 0);
2793
+ const orchestratorMode = "auto";
2794
+ const orchestratorTarget = ORCHESTRATOR_NAME;
2574
2795
  const names = p.to ? String(p.to).split(",").map((s) => cleanWebName(s)).filter(Boolean)
2575
2796
  : Array.from({ length: p.count }, (_, i) => `${cleanWebName(p.prefix || "w") || "w"}-${i + 1}`);
2576
2797
  if (names.length === 0) return { status: 400, payload: { error: "no worker names (pass to or count)" } };
@@ -2579,16 +2800,13 @@ export async function handleApiLaunch(d, body) {
2579
2800
  let cwdOk = false;
2580
2801
  try { cwdOk = fs.statSync(cwd).isDirectory(); } catch {}
2581
2802
  if (!cwdOk) return { status: 400, payload: { error: `cwd is not a directory: ${cwd}` } };
2582
- if (harnesses.includes("generic") && !(body && body.cmd && String(body.cmd).trim())) {
2583
- return { status: 400, payload: { error: 'generic harness needs cmd "..."' } };
2584
- }
2585
2803
  if (v.plan.dryRun) {
2586
2804
  const previewBatch = names.length > 1 ? newId("batch") : undefined;
2587
2805
  const rows = names.map((to, i) => {
2588
2806
  const driver = harnesses[i % harnesses.length];
2589
- 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 });
2807
+ 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 });
2590
2808
  const t = buildSpawnTarget({
2591
- harness: driver, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model,
2809
+ harness: driver, model: modelForIndex(models, i),
2592
2810
  auto: p.permission === "auto" || p.permission === "full" ? true : undefined,
2593
2811
  maxTurns: p.maxTurns, allowTools: p.allowTools, cwd,
2594
2812
  name: to, promptPath: path.join("<board>", "logs", `${to}-<stamp>.prompt.md`), prompt: previewPrompt,
@@ -2596,24 +2814,24 @@ export async function handleApiLaunch(d, body) {
2596
2814
  return { to, harness: driver, command: formatSpawnCmd(t) };
2597
2815
  });
2598
2816
  let coordinator = undefined;
2599
- if (leadMode === "board") {
2600
- const existingLead = readAgent(d, LEAD_NAME);
2817
+ if (orchestratorMode === "auto") {
2818
+ const existingLead = readAgent(d, ORCHESTRATOR_NAME);
2601
2819
  // Stale-pid guard (C2): reuse only a live, non-stale coordinator; a
2602
2820
  // pid-recycled after reboot record gets the fresh-provision branch.
2603
2821
  const standing = existingLead && typeof existingLead.spawnedPid === "number" && pidAlive(existingLead.spawnedPid) && !isPidStale(existingLead.spawnedPid, existingLead.spawnedAt);
2604
2822
  if (standing) {
2605
- coordinator = { name: LEAD_NAME, action: "reused", pid: existingLead.spawnedPid, note: "live coordinator already running" };
2823
+ coordinator = { name: ORCHESTRATOR_NAME, action: "reused", pid: existingLead.spawnedPid, note: "live coordinator already running" };
2606
2824
  } else if (existingLead && existingLead.offboarded) {
2607
- coordinator = { name: LEAD_NAME, action: "skipped", reason: "lane is offboarded" };
2825
+ coordinator = { name: ORCHESTRATOR_NAME, action: "skipped", reason: "lane is offboarded" };
2608
2826
  } else {
2609
- const coordDriver = harnesses.find((h) => h !== "generic") || "opencode";
2610
- const previewCoordPrompt = buildCoordinatorPrompt({
2611
- name: LEAD_NAME, from, subject: p.subject, body: p.body.trim(), batch: previewBatch,
2827
+ const coordDriver = harnesses[0] || "opencode";
2828
+ const previewCoordPrompt = buildOrchestratorPrompt({
2829
+ name: ORCHESTRATOR_NAME, subject: p.subject, body: p.body.trim(), batch: previewBatch,
2612
2830
  workers: names.map((name, i) => ({ name, id: previewBatch ? `${previewBatch}-${i + 1}` : "msg-<id>", harness: harnesses[i % harnesses.length] })),
2613
2831
  cwd, root: d.root, auto: p.permission === "auto" || p.permission === "full",
2614
2832
  });
2615
2833
  coordinator = {
2616
- name: LEAD_NAME, action: "minted", harness: coordDriver, wouldProvision: true,
2834
+ name: ORCHESTRATOR_NAME, action: "created", harness: coordDriver, model: coordModel, wouldProvision: true,
2617
2835
  promptPreview: previewCoordPrompt.slice(0, 400),
2618
2836
  };
2619
2837
  }
@@ -2635,27 +2853,27 @@ export async function handleApiLaunch(d, body) {
2635
2853
  for (let i = 0; i < res.items.length; i++) {
2636
2854
  const { to, id } = res.items[i];
2637
2855
  const driver = harnesses[i % harnesses.length];
2638
- 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 };
2856
+ 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 };
2639
2857
  try {
2640
- const r = bootWorker(d, spawnOpts, { to, id, from, lead: leadTarget, subject: p.subject, body: p.body.trim(), rev, logDir });
2858
+ const r = bootWorker(d, spawnOpts, { to, id, from, orchestrator: orchestratorTarget, subject: p.subject, body: p.body.trim(), rev, logDir });
2641
2859
  workers.push({ name: to, pid: r.pid, replyId: id, log: r.logPath, driver });
2642
2860
  } catch (e) {
2643
2861
  workers.push({ name: to, replyId: id, driver, error: String((e && e.message) || e) });
2644
2862
  }
2645
2863
  }
2646
2864
  let coordinator = undefined;
2647
- if (leadMode === "board") {
2648
- const coordHarness = harnesses.find((h) => h !== "generic") || "opencode";
2649
- const coordSpawnOpts = { harness: coordHarness, cmd: body && body.cmd ? String(body.cmd) : undefined, model: p.model, auto, cwd, root: d.root, prompt: null };
2865
+ if (orchestratorMode === "auto") {
2866
+ const coordHarness = harnesses[0] || "opencode";
2867
+ const coordSpawnOpts = { harness: coordHarness, cmd: body && body.cmd ? String(body.cmd) : undefined, model: coordModel, auto, cwd, root: d.root, prompt: null };
2650
2868
  try {
2651
- coordinator = provisionAutoLead(d, {
2869
+ coordinator = provisionOrchestrator(d, {
2652
2870
  spawnOpts: coordSpawnOpts,
2653
- from, subject: p.subject, body: p.body.trim(), rev, logDir,
2871
+ subject: p.subject, body: p.body.trim(), rev, logDir,
2654
2872
  workers: res.items.map((it, i) => ({ name: it.to, id: it.id, harness: harnesses[i % harnesses.length] })),
2655
2873
  batch: res.batch, auto,
2656
2874
  });
2657
2875
  } catch (e) {
2658
- coordinator = { action: "skipped", reason: `coordinator boot error: ${String((e && e.message) || e)}`, leadName: LEAD_NAME };
2876
+ coordinator = { action: "skipped", reason: `coordinator boot error: ${String((e && e.message) || e)}`, orchestratorName: ORCHESTRATOR_NAME };
2659
2877
  }
2660
2878
  }
2661
2879
  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