crewbus 10.0.12 → 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 (48) hide show
  1. package/AGENTS.template.md +4 -4
  2. package/CHANGELOG.md +135 -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 +49 -46
  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/LEAD_ASSIGN.md +2 -73
  29. package/docs/LONG_RUNS.md +3 -3
  30. package/docs/M1_CLI_DRAFT.md +7 -7
  31. package/docs/ORCHESTRATOR.md +87 -0
  32. package/docs/PAIRING.md +7 -7
  33. package/docs/QUICKSTART.md +81 -70
  34. package/docs/RBAC.md +84 -73
  35. package/docs/TENANCY.md +10 -10
  36. package/docs/THREAT_MODEL.md +3 -3
  37. package/docs/VERIFIER.md +10 -10
  38. package/docs/VERSION_SKEW.md +1 -1
  39. package/documentation.html +33 -24
  40. package/examples/hermes-pairing.md +3 -3
  41. package/examples/t3-pairing.md +1 -1
  42. package/index.html +6 -6
  43. package/opencode/plugins/dm-watch.js +1 -1
  44. package/opencode/tools/dm-send.js +1 -1
  45. package/package.json +27 -2
  46. package/packages/contracts/harness.json +15 -1
  47. package/packages/contracts/launch.json +2 -3
  48. package/packages/contracts/pairing.json +3 -3
@@ -107,7 +107,7 @@ export function mirrorToGroupChannels(d, { groups, from, body, subject, replyTo,
107
107
  const skipped = [];
108
108
  for (const g of groups || []) {
109
109
  // Member-scoped mirrors (C4): a worker's brief lands on grp-<g> channel
110
- // only if it is a member of <g> (or lead/admin). Non-members' DMs still
110
+ // only if it is a member of <g> (or orchestrator). Non-members' DMs still
111
111
  // deliver — the channel mirror is skipped with a visible note.
112
112
  const gate = authorizeCheck(d, from, "channel-post", { channelGroup: g });
113
113
  if (!gate || !gate.ok) {
package/bin/lib/export.js CHANGED
@@ -56,7 +56,7 @@ export function holdRefusal(d) { // line 5588
56
56
  const who = h.placedBy || "unknown";
57
57
  const when = h.placedAt || "unknown time";
58
58
  const why = h.reason ? `: ${h.reason}` : "";
59
- return `prune REFUSED — legal hold ACTIVE (placed by ${who} at ${when}${why}) [board ${d.root}] — lift with: hold lift --from <admin>`;
59
+ return `prune REFUSED — legal hold ACTIVE (placed by ${who} at ${when}${why}) [board ${d.root}] — lift with: hold lift --from orchestrator`;
60
60
  }
61
61
 
62
62
  // readBoardMeta/writeBoardMeta/writeAtomicFile live in store.js (canonical home).
package/bin/lib/groups.js CHANGED
@@ -324,9 +324,5 @@ export function findFirstVerifiedReply(d, items) {
324
324
  }
325
325
 
326
326
  export function heuristicSenderType(d, from) { // line 1188
327
- try {
328
- const g = readGroup(d, "lead");
329
- if (g && Array.isArray(g.members) && g.members.includes(from)) return "lead";
330
- } catch {}
331
- return "peer";
327
+ return String(from || "") === "orchestrator" ? "orchestrator" : "peer";
332
328
  }
@@ -162,11 +162,11 @@ export function checkToken(d, agent, token) { // line 361
162
162
  // as register, zero extra round-trip). Returns { created } so callers can
163
163
  // print the token exactly once — it is never shown again via send.
164
164
  export function ensureSender(d, agent, token) { // line 387
165
- const sentinel = reservedNameReason(agent);
166
- if (sentinel) fail(sentinel);
167
165
  const rec = readAgent(d, agent);
168
166
  if (!rec) {
169
- if (isBoardFrozen(d)) fail(`board is frozen — new registrations refused (ask an admin to register --from <admin> --for ${agent})`);
167
+ const sentinel = reservedNameReason(agent);
168
+ if (sentinel) fail(sentinel);
169
+ if (isBoardFrozen(d)) fail(`board is frozen — new registrations refused (ask the orchestrator to register --from orchestrator --for ${agent})`);
170
170
  const fresh = mintToken();
171
171
  const salt = newSalt();
172
172
  // Fresh claims race (parallel first sends): exactly one may win, via
@@ -325,46 +325,41 @@ export const RESERVED_SENTINELS = ["unknown", "me", "you"];
325
325
 
326
326
  export function reservedNameReason(agent) {
327
327
  const s = String(agent || "").trim().toLowerCase();
328
+ if (s === ORCHESTRATOR_NAME) {
329
+ return `"${agent}" is reserved for the board orchestrator (auto-provisioned by spawn; do not register it)`;
330
+ }
328
331
  return RESERVED_SENTINELS.includes(s)
329
- ? `"${agent}" is a reserved sentinel name (amnesia-throwaway) — identity lost? run: crewbus recover, then re-register/claim your real name`
332
+ ? `"${agent}" is a reserved sentinel name (amnesia-throwaway) - identity lost? run: crewbus recover, then re-register/claim your real name`
330
333
  : null;
331
- }
334
+ }
332
335
 
333
336
  // ---------------------------------------------------------------------------
334
- // Phase 1b RBAC + per-board ACLs + group-scoped send permissions.
337
+ // RBAC: two roles only.
335
338
  //
336
- // Composes with the token crew: call authorize() AFTER checkToken() passes
337
- // (never before, never instead). checkToken proves WHO you are; authorize
338
- // decides WHAT your role may do. Do not merge into checkToken.
339
+ // orchestrator — the board's single control-plane identity. Reads and writes
340
+ // everything: spawn/respawn/kill, approvals, groups, channels,
341
+ // ACLs, pairing, admin operations. The board bootstraps exactly
342
+ // one, named `orchestrator` (see ensureOrchestrator).
343
+ // worker — the data plane. send/inbox/ack/redeliver/lock, artifacts,
344
+ // lessons, member-scoped channel posts. No control-plane acts.
339
345
  //
340
- // Roles (agent record `role` in {admin, lead, worker, auditor}):
341
- // - first-registered agent on a board becomes admin, everyone else gets
342
- // acl.defaultRole (default "worker"). `register --role` is only honored
343
- // when the caller is admin, else ignored-with-warning.
344
- // - legacy records without `role` map to `lead` so existing crews keep
345
- // working (documented in docs/RBAC.md).
346
- // Permission matrix (minimal):
347
- // - admin: all, incl. role grants / offboard / prune / acl set /
348
- // group restrict / serve --allow-remote-spawn.
349
- // - lead: send / spawn / respawn / pool / spawn-kill (OWN crew only:
350
- // target.spawnedBy must equal caller, or target never spawned;
351
- // respawn --force reuses the spawn-kill scope check) / group manage /
352
- // result record / race close / channel post / lock / inbox / ack /
353
- // redeliver + all reads.
354
- // - worker: send / inbox / ack / redeliver / lock (scoped: release still
355
- // requires ownership) / channel tail (read) + all reads. No spawn,
356
- // no kills, no group mgmt, no channel post, no result/race writes.
357
- // - auditor: read-only everything (inbox / gather / thread / log /
358
- // channel tail / group show / result show / spawn-status, ...). Zero
359
- // writes: send/spawn/kill/prune/ack/lock/channel-post all refused.
360
- // Reads not listed above default-allow (fail-closed only for writes).
346
+ // Records with any other/missing role are treated as workers (safe fallback:
347
+ // an unknown role can never gain orchestrator powers).
348
+ // Reads that are not routed through authorize() stay default-open.
361
349
  // ---------------------------------------------------------------------------
362
350
 
363
- export const VALID_ROLES = ["admin", "lead", "worker", "auditor"]; // line 470
351
+ export const ORCHESTRATOR_NAME = "orchestrator";
352
+ export const VALID_ROLES = ["orchestrator", "worker"];
353
+
354
+ // Worker-allowed write/read actions. Everything else is orchestrator-only.
355
+ const WORKER_ACTIONS = new Set([
356
+ "send", "inbox", "ack", "redeliver", "lock", "artifact-write", "lesson-write",
357
+ "hold-status",
358
+ ]);
364
359
 
365
360
  export function cleanRole(raw) { // line 472
366
361
  const r = String(raw || "").trim().toLowerCase();
367
- if (!VALID_ROLES.includes(r)) fail(`invalid --role "${raw}" (want admin|lead|worker|auditor)`);
362
+ if (!VALID_ROLES.includes(r)) fail(`invalid --role "${raw}" (want orchestrator|worker)`);
368
363
  return r;
369
364
  }
370
365
 
@@ -372,7 +367,7 @@ export function roleOfRecord(rec) { // line 478
372
367
  if (rec && typeof rec.role === "string" && VALID_ROLES.includes(String(rec.role).toLowerCase())) {
373
368
  return String(rec.role).toLowerCase();
374
369
  }
375
- return "lead"; // back-compat: boards/agents predating roles act as lead
370
+ return "worker"; // unknown/missing role: never grant control-plane powers
376
371
  }
377
372
 
378
373
  export function getRole(d, agent) { // line 485
@@ -395,10 +390,7 @@ export function readBoardAcl(d) { // line 497
395
390
  meta = null;
396
391
  }
397
392
  const acl = (meta && typeof meta.acl === "object" && meta.acl) || {};
398
- const def = typeof acl.defaultRole === "string" && VALID_ROLES.includes(String(acl.defaultRole).toLowerCase())
399
- ? String(acl.defaultRole).toLowerCase()
400
- : "worker";
401
- return { defaultRole: def, frozen: acl.frozen === true };
393
+ return { defaultRole: "worker", frozen: acl.frozen === true };
402
394
  }
403
395
 
404
396
  export function writeBoardAcl(d, acl) { // line 511
@@ -417,75 +409,46 @@ export function isBoardFrozen(d) { // line 523
417
409
  return readBoardAcl(d).frozen === true;
418
410
  }
419
411
 
420
- // Role for a brand-new agent record: first agent on the board becomes admin,
421
- // everyone else gets acl.defaultRole (default "worker").
412
+ // Every self-registering identity is a worker. The orchestrator is minted only
413
+ // by ensureOrchestrator (spawn/bootstrap) or an explicit orchestrator grant.
422
414
  export function defaultRoleForNew(d) { // line 529
423
- return countAgentRecords(d) === 0 ? "admin" : readBoardAcl(d).defaultRole;
415
+ return "worker";
424
416
  }
425
417
 
426
418
  // Core RBAC decision: returns { ok, reason }. Never exits (CLI authorize()
427
419
  // turns !ok into fail(); relay/MCP turn it into 403/throw). Restricted-group
428
- // scope is checked here too when scope.toGroups is present: a send/spawn
429
- // addressing a restricted group is allowed only for admin/lead or a member.
420
+ // scope is checked here too when scope.toGroups is present.
430
421
  export function authorizeCheck(d, agent, action, scope) { // line 537
431
422
  const role = getRole(d, agent);
432
423
  const act = String(action || "");
433
- const ADMIN_ONLY = new Set(["prune", "acl-set", "role-grant", "offboard", "group-restrict", "serve-remote", "import", "snapshot-schedule", "quota-set", "hold-place", "hold-lift", "pairing"]);
434
- const LEAD_PLUS = new Set(["spawn", "respawn", "pool", "group-manage", "result-record", "race-close"]);
435
- const WORKER_WRITES = new Set(["send", "ack", "redeliver", "lock", "artifact-write", "lesson-write"]);
436
- const EXPORT_ROLES = new Set(["admin", "auditor"]);
437
- if (act === "export") {
438
- if (!EXPORT_ROLES.has(role)) return { ok: false, reason: `role "${role}" cannot export (need admin|auditor)` };
439
- } else if (role === "admin") {
440
- // admins still honor restricted groups? No: admin/lead bypass membership.
441
- } else if (ADMIN_ONLY.has(act)) {
442
- return { ok: false, reason: `role "${role}" cannot ${act} (need admin)` };
443
- } else if (LEAD_PLUS.has(act)) {
444
- if (role !== "lead") return { ok: false, reason: `role "${role}" cannot ${act} (need lead|admin)` };
445
- } else if (act === "channel-post") {
446
- // Member-scoped channel posting (C4, default-on): workers may post to the
447
- // channels of groups they are a MEMBER of (scope.channelGroup); lead/admin
448
- // post anywhere (board channels + every group channel). Everyone else,
449
- // and workers targeting a foreign group's channel or a board channel with
450
- // no member mapping, are refused.
451
- if (role === "admin" || role === "lead") {
452
- // board-wide + group channels
453
- } else if (role !== "worker") {
454
- return { ok: false, reason: `role "${role}" cannot ${act} (member-posting is scoped to group members; need lead|admin)` };
455
- } else {
424
+ if (role === "orchestrator") {
425
+ // Full control plane.
426
+ } else if (role === "worker") {
427
+ if (act === "channel-post") {
428
+ // Member-scoped: a worker may post only to a group channel it belongs to.
456
429
  const targetGroup = scope && scope.channelGroup ? String(scope.channelGroup) : undefined;
457
430
  if (!targetGroup) {
458
- return { ok: false, reason: `role "worker" may post only to a group channel it belongs to (${targetGroup === undefined ? "board channels are lead|admin" : "need lead|admin"})` };
431
+ return { ok: false, reason: `role "worker" may post only to a group channel it belongs to (board channels are orchestrator-only)` };
459
432
  }
460
433
  const gdoc = readGroup(d, targetGroup);
461
- if (!gdoc) return { ok: false, reason: `channel group "${targetGroup}" not found (groups register their channels — board channels are lead|admin)` };
434
+ if (!gdoc) return { ok: false, reason: `channel group "${targetGroup}" not found (board channels are orchestrator-only)` };
462
435
  const members = Array.isArray(gdoc.members) ? gdoc.members : [];
463
- if (!members.includes(agent)) return { ok: false, reason: `group channel "${targetGroup}" — members only (member or lead|admin)` };
464
- }
465
- } else if (act === "spawn-kill") {
466
- if (role !== "lead") return { ok: false, reason: `role "${role}" cannot spawn-kill (need lead|admin)` };
467
- const targets = (scope && Array.isArray(scope.targets)) ? scope.targets : [];
468
- for (const t of targets) {
469
- const rec = readAgent(d, t);
470
- if (rec && rec.spawnedBy && rec.spawnedBy !== agent) {
471
- return { ok: false, reason: `lead "${agent}" cannot kill "${t}" (spawned by ${rec.spawnedBy}; own crew only)` };
472
- }
436
+ if (!members.includes(agent)) return { ok: false, reason: `group channel "${targetGroup}" — members only` };
437
+ } else if (!WORKER_ACTIONS.has(act)) {
438
+ return { ok: false, reason: `role "worker" cannot ${act} (orchestrator only)` };
473
439
  }
474
- } else if (WORKER_WRITES.has(act)) {
475
- if (role !== "lead" && role !== "worker") return { ok: false, reason: `role "${role}" cannot ${act} (auditor is read-only)` };
476
440
  } else {
477
- // reads (inbox/gather/thread/log/channel-tail/group-show/result-show/
478
- // race-start/spawn-status/agents/...) default-allow for all roles.
441
+ return { ok: false, reason: `unknown role "${role}" (want orchestrator|worker)` };
479
442
  }
480
- // Group-scoped sends: restricted groups need admin/lead or membership.
443
+ // Group-scoped sends: restricted groups need the orchestrator or membership.
481
444
  const toGroups = (scope && Array.isArray(scope.toGroups)) ? scope.toGroups : [];
482
445
  if ((act === "send" || act === "spawn" || act === "pool") && toGroups.length > 0) {
483
446
  for (const g of toGroups) {
484
447
  const doc = readGroup(d, g);
485
448
  if (doc && doc.restricted === true) {
486
449
  const members = Array.isArray(doc.members) ? doc.members : [];
487
- if (role !== "admin" && role !== "lead" && !members.includes(agent)) {
488
- return { ok: false, reason: `group "${g}" is restricted (member or lead|admin only)` };
450
+ if (role !== "orchestrator" && !members.includes(agent)) {
451
+ return { ok: false, reason: `group "${g}" is restricted (member or orchestrator only)` };
489
452
  }
490
453
  }
491
454
  }
@@ -526,65 +489,64 @@ export function mergeAgentDoc(prev, patch) {
526
489
  return base;
527
490
  }
528
491
 
529
- // Loopback operator auto-provision (desktop plug-and-play):
530
- // `serve`/`web` on 127.0.0.1 auto-creates an operator identity on first boot so
531
- // the dashboard can launch without any terminal step. First agent on the
532
- // board becomes admin (see defaultRoleForNew), so this is the board owner.
533
- // Under the 3-lane model (boss / lead / peers), fresh boards mint `boss` as the
534
- // desktop human operator, allowing crew bursts to auto-provision `lead` as the
535
- // autonomous coordinator. Existing boards that already claimed `lead` (or `boss`)
536
- // are kept without disruption.
537
- // CLI boards are untouched: this only fires when operator is missing AND the
538
- // bind is loopback. Returns { from, token } or null when not applicable.
539
- export function ensureLoopbackOperator(d, host) {
540
- const loop = String(host || "127.0.0.1");
541
- if (loop !== "127.0.0.1" && loop !== "localhost" && loop !== "::1") return null;
542
- let recBoss = null, recLead = null;
543
- try { recBoss = readAgent(d, "boss"); } catch { recBoss = null; }
544
- try { recLead = readAgent(d, "lead"); } catch { recLead = null; }
545
- if (recBoss && (recBoss.tokenHash || recBoss.token)) return null; // already provisioned
546
- if (recLead && recLead.tokenHash) return null; // already provisioned (legacy board)
547
- if (countAgentRecords(d) > 0) return null; // board already has registered agents
492
+ // One standing control-plane identity per board. Called by spawn and by the
493
+ // local web/serve servers. Reads the existing token file when it still matches
494
+ // the record; otherwise mints (or rotates) and persists logs/orchestrator.token.
495
+ // Never fails for bookkeeping reasons; returns { from, token, created }.
496
+ export function ensureOrchestrator(d) {
497
+ const name = ORCHESTRATOR_NAME;
498
+ const tokenPath = path.join(d.root, "logs", `${name}.token`);
499
+ const readTokenFile = () => {
500
+ try {
501
+ const t = fs.readFileSync(tokenPath, "utf8").trim();
502
+ return t || null;
503
+ } catch { return null; }
504
+ };
505
+ const writeTokenFile = (token) => {
506
+ try {
507
+ fs.mkdirSync(path.dirname(tokenPath), { recursive: true });
508
+ fs.writeFileSync(tokenPath, token + "\n", "utf8");
509
+ try { fs.chmodSync(tokenPath, 0o600); } catch {}
510
+ } catch {}
511
+ };
512
+ let prev = null;
513
+ try { prev = readAgent(d, name); } catch { prev = null; }
514
+ if (prev && prev.tokenHash) {
515
+ const tok = readTokenFile();
516
+ if (tok && agentTokenMatches(prev, tok)) return { from: name, token: tok, created: false };
517
+ }
548
518
  const fresh = mintToken();
549
519
  const salt = newSalt();
550
520
  const now = new Date().toISOString();
551
- let prev = null;
552
- try { prev = readJson(path.join(d.agents, "boss.json")); } catch { prev = null; }
553
521
  const { v, hlc } = stampSyncDoc(prev);
554
522
  const doc = mergeAgentDoc(prev, {
555
- name: "boss",
523
+ name,
556
524
  firstSeen: (prev && prev.firstSeen) || now,
557
525
  lastSeen: now,
558
526
  tokenHash: hashToken(fresh, salt),
559
527
  salt,
560
528
  revokedAt: undefined,
561
529
  offboarded: undefined,
562
- role: "admin",
530
+ role: "orchestrator",
563
531
  v, hlc,
564
532
  });
565
- // Atomic first-claim: exactly one boot may win. Losers re-read below.
566
- let won = false;
567
- try {
568
- if (!prev) {
569
- won = writeExclusiveJson(path.join(d.agents, "boss.json"), doc);
570
- } else {
571
- writeAgentFile(d, "boss", doc);
572
- won = true;
533
+ // Fresh record: atomic first claim. Existing record (or lost race): rewrite
534
+ // only when the token file is missing/stale, otherwise reuse the winner.
535
+ if (!prev) {
536
+ let won = false;
537
+ try { won = writeExclusiveJson(path.join(d.agents, `${name}.json`), doc); } catch { won = false; }
538
+ if (!won) {
539
+ const again = readAgent(d, name);
540
+ const tok = readTokenFile();
541
+ if (again && again.tokenHash && tok && agentTokenMatches(again, tok)) {
542
+ return { from: name, token: tok, created: false };
543
+ }
573
544
  }
574
- } catch { won = false; }
575
- if (!won && !prev) {
576
- // Lost the race (parallel boot): read the winner, no token to return.
577
- return null;
578
- }
579
- if (won) {
580
- try { chmodAgentFile(path.join(d.agents, "boss.json")); } catch {}
581
- try {
582
- fs.mkdirSync(path.join(d.root, "logs"), { recursive: true });
583
- fs.writeFileSync(path.join(d.root, "logs", "boss.token"), fresh + "\n", "utf8");
584
- try { fs.chmodSync(path.join(d.root, "logs", "boss.token"), 0o600); } catch {}
585
- } catch {}
545
+ } else {
546
+ writeAgentFile(d, name, doc);
586
547
  }
587
- return won ? { from: "boss", token: fresh } : null;
548
+ writeTokenFile(fresh);
549
+ return { from: name, token: fresh, created: true };
588
550
  }
589
551
 
590
552
  export function touchAgent(d, name, extra) { // line 2647
package/bin/lib/launch.js CHANGED
@@ -28,6 +28,7 @@ export const LAUNCH_DRIVER_FALLBACK = [
28
28
  { driver: "grok", displayName: "grok-build", binary: "grok", briefDelivery: "file", sessionCapture: "preassigned", resume: true, spawnArgs: "--prompt-file <brief> -s <uuid>", resumeArgs: "--prompt-file <catchup> -r <id>" },
29
29
  { driver: "antigravity", displayName: "Antigravity", binary: "agy", briefDelivery: "inline", sessionCapture: "none", resume: false, spawnArgs: "--print --mode accept-edits \"<brief>\"", resumeArgs: "unsupported (no stable conversation id)" },
30
30
  { driver: "cursor", displayName: "Cursor", binary: "cursor-agent", briefDelivery: "inline", sessionCapture: "none", resume: false, spawnArgs: "cursor-agent -p --force --trust \"<brief>\"", resumeArgs: "unsupported (id lives in stream-json)" },
31
+ { driver: "qwen", displayName: "Qwen Code", binary: "qwen", briefDelivery: "inline", sessionCapture: "preassigned", resume: true, spawnArgs: "--output-format json -y --approval-mode yolo \"<brief>\"", resumeArgs: "--resume <id> \"<catchup>\"" },
31
32
  ];
32
33
  // Resolve the driver table: contracts file wins, fallback otherwise.
33
34
  export function launchDrivers() {
@@ -35,7 +36,7 @@ export function launchDrivers() {
35
36
  const here = path.dirname(new URL(import.meta.url).pathname);
36
37
  const p = path.join(here, "..", "..", "packages", "contracts", "harness.json");
37
38
  const doc = JSON.parse(fs.readFileSync(p, "utf8"));
38
- if (doc && Array.isArray(doc.drivers) && doc.drivers.length === 6) return doc.drivers;
39
+ if (doc && Array.isArray(doc.drivers) && doc.drivers.length >= 7) return doc.drivers;
39
40
  } catch {}
40
41
  return LAUNCH_DRIVER_FALLBACK;
41
42
  }
@@ -150,6 +151,13 @@ export const HARNESS_MODELS = {
150
151
  { id: "claude-3.7-sonnet", label: "Claude 3.7 Sonnet (Legacy)", tier: "standard" },
151
152
  { id: "gpt-4o", label: "GPT-4o (Legacy)", tier: "standard" },
152
153
  ],
154
+ qwen: [
155
+ { id: "qwen3.8-max", label: "Qwen 3.8 Max (Flagship Reasoning & Coding)", tier: "frontier" },
156
+ { id: "qwen3.7-plus", label: "Qwen 3.7 Plus (Balanced Agentic Reasoning)", tier: "standard" },
157
+ { id: "qwen3.8-flash", label: "Qwen 3.8 Flash (Fast / High-Throughput)", tier: "fast" },
158
+ { id: "deepseek-v4-pro-0813", label: "DeepSeek v4 Pro (Coding & Math)", tier: "frontier" },
159
+ { id: "qwen-coder-plus", label: "Qwen Coder Plus (Code Specialist)", tier: "standard" },
160
+ ],
153
161
  };
154
162
 
155
163
  // Dynamic discovered model cache for harnesses capable of live discovery (e.g., opencode).
@@ -247,6 +255,33 @@ export function refreshDiscoveredModels(timeoutMs = 15000) {
247
255
  _cachedDiscoveredModels.antigravity = aLines;
248
256
  }
249
257
  } catch {}
258
+
259
+ // qwen model discovery
260
+ try {
261
+ const homeDir = os.homedir();
262
+ const settingsPath = path.join(homeDir, ".qwen", "settings.json");
263
+ const qModels = [];
264
+ if (fs.existsSync(settingsPath)) {
265
+ const sObj = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
266
+ if (sObj && sObj.modelProviders && typeof sObj.modelProviders === "object") {
267
+ for (const list of Object.values(sObj.modelProviders)) {
268
+ if (Array.isArray(list)) {
269
+ for (const item of list) {
270
+ if (item && item.id) {
271
+ const tier = /max|pro|plus|r1/i.test(item.id) ? "frontier" : /flash|mini|fast/i.test(item.id) ? "fast" : "standard";
272
+ qModels.push({ id: item.id, label: `${item.name || item.id} (Configured)`, tier });
273
+ }
274
+ }
275
+ }
276
+ }
277
+ }
278
+ }
279
+ if (qModels.length > 0) {
280
+ if (!_cachedDiscoveredModels) _cachedDiscoveredModels = {};
281
+ _cachedDiscoveredModels.qwen = qModels;
282
+ }
283
+ } catch {}
284
+
250
285
  } catch {
251
286
  // Ignore discovery errors — static catalog remains available
252
287
  } finally {
@@ -321,22 +356,42 @@ export function validateLaunchPlan(raw) {
321
356
  }
322
357
  }
323
358
 
324
- const model = r.model === undefined || r.model === null || String(r.model).trim() === "" ? undefined : String(r.model).trim();
325
- if (model && model.length > 100) errors.push("model name too long (max 100 chars)");
326
-
327
- const lead = r.lead === undefined || r.lead === null || String(r.lead).trim() === "" ? "auto" : String(r.lead).trim().toLowerCase();
328
- if (lead !== "auto") errors.push(`bad lead mode "${r.lead}" (only "auto" supported)`);
359
+ // Per-worker models: "--model a,b,c" (or a models[] array over the RPC)
360
+ // applies a/b/c to workers in order, cycling when there are more workers
361
+ // than models — same semantics as --harness. A single value applies to all.
362
+ const modelList = Array.isArray(r.models)
363
+ ? r.models
364
+ : (r.model === undefined || r.model === null ? [] : String(r.model).split(","));
365
+ const models = modelList
366
+ .map((m) => (m === undefined || m === null ? "" : String(m).trim()))
367
+ .filter(Boolean);
368
+ if (models.length === 0 && r.model !== undefined && r.model !== null && String(r.model).trim() !== "") {
369
+ errors.push("invalid model (empty after splitting on commas)");
370
+ }
371
+ for (const m of models) {
372
+ if (m.length > 100) errors.push("model name too long (max 100 chars)");
373
+ }
374
+ const model = models.length > 0 ? models.join(",") : undefined;
375
+
376
+ // The orchestrator lane is one process, so it takes one model (not a list).
377
+ const orchestratorModelRaw = r.orchestratorModel;
378
+ let orchestratorModel;
379
+ if (orchestratorModelRaw !== undefined && orchestratorModelRaw !== null && String(orchestratorModelRaw).trim() !== "") {
380
+ orchestratorModel = String(orchestratorModelRaw).trim();
381
+ if (orchestratorModel.includes(",")) errors.push("orchestratorModel takes one model (not a comma list)");
382
+ if (orchestratorModel.length > 100) errors.push("orchestrator model name too long (max 100 chars)");
383
+ }
329
384
 
330
385
  const plan = {
331
386
  harness, harnesses: harnesses.length > 0 ? harnesses : ["opencode"],
332
- model, body, count: Number.isInteger(count) && count > 0 ? count : 1,
387
+ model, models, orchestratorModel, body, count: Number.isInteger(count) && count > 0 ? count : 1,
333
388
  prefix: r.prefix === undefined ? undefined : String(r.prefix),
334
389
  to: r.to === undefined ? undefined : String(r.to),
335
390
  subject: r.subject === undefined ? undefined : String(r.subject),
336
391
  priority: r.priority === undefined ? undefined : String(r.priority),
337
392
  maxTurns: r.maxTurns === undefined ? undefined : String(r.maxTurns),
338
393
  allowTools: r.allowTools === undefined ? undefined : String(r.allowTools),
339
- permission, lifetime, lead,
394
+ permission, lifetime,
340
395
  isolate: !!r.isolate, worktree: r.worktree, branch: r.branch,
341
396
  budgetTokens: r.budgetTokens, budgetMinutes: r.budgetMinutes, timeout: r.timeout,
342
397
  target: r.target === undefined ? "local" : r.target,
package/bin/lib/relay.js CHANGED
@@ -40,9 +40,9 @@ import crypto from "node:crypto";
40
40
  import http from "node:http";
41
41
  import https from "node:https";
42
42
  import { readJson, writeJson, listJson, getFlag, cleanWebName, gitRevForBoard, MAX_BODY_CHARS, MAX_FWD_DEPTH, webErr } from "./store.js";
43
- import { readAgent, agentTokenMatches, mintToken, newSalt, hashToken, timingSafeEqualStr, writeAgentFile, isBoardFrozen, defaultRoleForNew, authorizeThrow, authorizeCheck, touchAgent } from "./identity.js";
43
+ import { readAgent, agentTokenMatches, mintToken, newSalt, hashToken, timingSafeEqualStr, writeAgentFile, isBoardFrozen, defaultRoleForNew, authorizeThrow, authorizeCheck, touchAgent, ensureOrchestrator, ORCHESTRATOR_NAME } from "./identity.js";
44
44
  import { httpJson } from "./sync.js";
45
- import { killWorkers, pidAlive, bootWorker, parseAllowEnv, isPidStale } from "./spawn.js";
45
+ import { killWorkers, pidAlive, bootWorker, parseAllowEnv, isPidStale, parseModelList, modelForIndex, modelListErrors } from "./spawn.js";
46
46
  import { expandGroups, heuristicSenderType } from "./groups.js";
47
47
  import { deliverDMs, findMessageById } from "./mail.js";
48
48
  import { appendChainRecord } from "./export.js";
@@ -133,10 +133,12 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
133
133
  return s !== undefined && s.trim() !== "" ? s : undefined;
134
134
  };
135
135
  const rawFrom = cleanStr(a.from);
136
- if (!rawFrom || !rawFrom.trim()) throw webErr(400, "missing from (your agent name)");
137
- const from = rawFrom.trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 40);
138
- if (!from) throw webErr(400, "invalid agent name");
139
- const token = cleanStr(a.token) || undefined;
136
+ if (!rawFrom || !rawFrom.trim()) throw webErr(400, "missing from (requester name)");
137
+ // Remote control-plane actions run as the relay board's single orchestrator.
138
+ // The relay secret (or a device credential with launch:spawn) is the auth
139
+ // boundary; `from` is kept only as audit metadata by the route.
140
+ ensureOrchestrator(d);
141
+ const from = ORCHESTRATOR_NAME;
140
142
  // Recipients: to (string|array) + to_group + count/prefix, same as CLI.
141
143
  const toParts = [];
142
144
  if (a.to !== undefined && a.to !== null) {
@@ -198,7 +200,7 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
198
200
  return s;
199
201
  }).filter(Boolean);
200
202
  if (harnesses.length === 0) harnesses.push("opencode");
201
- const validHarnesses = ["opencode", "claude", "codex", "grok", "antigravity", "cursor"];
203
+ const validHarnesses = ["opencode", "claude", "codex", "grok", "antigravity", "cursor", "qwen"];
202
204
  for (const h of harnesses) {
203
205
  if (!validHarnesses.includes(h)) {
204
206
  throw webErr(400, `unknown harness "${h}" (want ${validHarnesses.join("|")})`);
@@ -206,9 +208,9 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
206
208
  }
207
209
  let harness = harnesses.join(",");
208
210
  const cmd = cleanOpt(a.cmd);
209
- const maxTurns = a.maxTurns === undefined || a.maxTurns === null || String(a.maxTurns).trim() === "" ? ((harness === "claude" || harness === "grok") ? 50 : undefined) : Number(a.maxTurns);
211
+ const maxTurns = a.maxTurns === undefined || a.maxTurns === null || String(a.maxTurns).trim() === "" ? ((harness === "claude" || harness === "grok" || harness === "qwen") ? 50 : undefined) : Number(a.maxTurns);
210
212
  if (maxTurns !== undefined && !(maxTurns > 0)) throw webErr(400, "maxTurns must be a positive number");
211
- if (maxTurns !== undefined && harness !== "claude" && harness !== "grok") throw webErr(400, `maxTurns only applies to claude/grok (got ${harness})`);
213
+ if (maxTurns !== undefined && harness !== "claude" && harness !== "grok" && harness !== "qwen") throw webErr(400, `maxTurns only applies to claude/grok/qwen (got ${harness})`);
212
214
  const allowTools = cleanOpt(a.allowTools);
213
215
  if (allowTools !== undefined && harness !== "claude") throw webErr(400, `allowTools only applies to claude (got ${harness})`);
214
216
  const body = cleanStr(a.body);
@@ -218,7 +220,14 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
218
220
  const cleanSub = subject ? subject.slice(0, 120) : undefined;
219
221
  const replyTo = cleanOpt(a.replyTo);
220
222
  const cleanRep = replyTo ? replyTo.slice(0, 80) : undefined;
221
- const model = cleanOpt(a.model);
223
+ const modelList = parseModelList(a.models !== undefined ? a.models : a.model);
224
+ if (a.models === undefined && a.model !== undefined && a.model !== null && String(a.model).trim() !== "" && modelList.length === 0) {
225
+ throw webErr(400, "invalid model (empty after splitting on commas)");
226
+ }
227
+ const modelErr = modelListErrors(modelList)[0];
228
+ if (modelErr) throw webErr(400, modelErr);
229
+ const models = modelList;
230
+ const model = models[0];
222
231
  const auto = a.auto === true;
223
232
  const lifetime = a.lifetime === "persistent" ? "persistent" : "oneshot";
224
233
  if (a.lifetime !== undefined && a.lifetime !== null && !["oneshot", "persistent"].includes(String(a.lifetime))) throw webErr(400, "lifetime must be oneshot|persistent");
@@ -241,35 +250,9 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
241
250
  }
242
251
 
243
252
  if (auto && !(a.iUnderstandDanger === true || a.i_understand_danger === true)) throw webErr(400, "--auto remotely needs iUnderstandDanger:true plus an isolated relay (see docs/ISOLATION.md)");
244
- // Pre-verify: CLI ensureSender calls fail() (process exit) on mismatch,
245
- // which must never run inside a request handler. Hashed + legacy accepted.
246
- const existing = readAgent(d, from);
247
- if (existing && (existing.tokenHash || existing.token) && !agentTokenMatches(existing, token)) throw webErr(403, `bad token for "${from}"`);
248
- let minted = { created: false };
249
- if (!existing) {
250
- if (isBoardFrozen(d)) throw webErr(403, `board is frozen — new registrations refused (ask an admin to register --from <admin> --for ${from})`);
251
- const fresh = mintToken();
252
- const salt = newSalt();
253
- writeAgentFile(d, from, { name: from, firstSeen: new Date().toISOString(), lastSeen: new Date().toISOString(), lastDir: process.cwd(), tokenHash: hashToken(fresh, salt), salt, role: defaultRoleForNew(d) });
254
- minted = { created: true, token: fresh };
255
- } else if (existing.token && !existing.tokenHash) {
256
- const salt = newSalt();
257
- existing.tokenHash = hashToken(String(token), salt);
258
- existing.salt = salt;
259
- delete existing.token;
260
- if (!existing.role) existing.role = "lead"; // back-compat backfill
261
- writeAgentFile(d, from, existing);
262
- } else if (!existing.tokenHash && !existing.token) {
263
- const fresh = mintToken();
264
- const salt = newSalt();
265
- existing.tokenHash = hashToken(fresh, salt);
266
- existing.salt = salt;
267
- if (!existing.role) existing.role = defaultRoleForNew(d);
268
- writeAgentFile(d, from, existing);
269
- minted = { created: true, token: fresh };
270
- }
253
+
271
254
  // Phase 1b: relay spawn honors the same matrix as CLI spawn (worker/auditor
272
- // refused; restricted --to-group needs admin/lead/member). Throwing twin so
255
+ // refused; restricted --to-group needs orchestrator/member). Throwing twin so
273
256
  // a denial is a 403, never a process exit.
274
257
  authorizeThrow(d, from, "spawn", {
275
258
  toGroups: String(a.to_group === undefined || a.to_group === null ? "" : a.to_group).split(",").map((s) => String(s).trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 40)).filter(Boolean),
@@ -279,10 +262,10 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
279
262
  const at = new Date().toISOString();
280
263
  const logDir = path.join(d.root, "logs");
281
264
  fs.mkdirSync(logDir, { recursive: true });
282
- const spawnOpts = { harness, cmd, model, auto, maxTurns, allowTools, cwd, root: d.root, prompt: null, keepEnv: a.keepEnv === true, allowEnv: parseAllowEnv(a.allowEnv) };
265
+ const spawnOpts = { harness, cmd, model, models, auto, maxTurns, allowTools, cwd, root: d.root, prompt: null, keepEnv: a.keepEnv === true, allowEnv: parseAllowEnv(a.allowEnv) };
283
266
  const senderType = (() => {
284
267
  const t = a.senderType !== undefined ? String(a.senderType).toLowerCase() : (a.sender_type !== undefined ? String(a.sender_type).toLowerCase() : undefined);
285
- if (t !== undefined && !["human", "lead", "peer"].includes(t)) throw webErr(400, "senderType must be human|lead|peer");
268
+ if (t !== undefined && !["human", "orchestrator", "peer"].includes(t)) throw webErr(400, "senderType must be human|orchestrator|peer");
286
269
  return t || heuristicSenderType(d, from);
287
270
  })();
288
271
  const fwd = (() => {
@@ -305,10 +288,11 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
305
288
  for (let i = 0; i < res.items.length; i++) {
306
289
  const { to, id } = res.items[i];
307
290
  const driver = harnesses[i % harnesses.length];
308
- const itemMaxTurns = maxTurns === undefined ? ((driver === "claude" || driver === "grok") ? 50 : undefined) : Number(maxTurns);
291
+ const itemMaxTurns = maxTurns === undefined ? ((driver === "claude" || driver === "grok" || driver === "qwen") ? 50 : undefined) : Number(maxTurns);
309
292
  const itemSpawnOpts = {
310
293
  ...spawnOpts,
311
294
  harness: driver,
295
+ model: modelForIndex(models, i),
312
296
  maxTurns: itemMaxTurns,
313
297
  allowTools: driver === "claude" ? allowTools : undefined,
314
298
  };
@@ -320,7 +304,6 @@ export async function remoteSpawn(d, a, serveOpts) { // line 6770
320
304
  }
321
305
  }
322
306
  const out = { results };
323
- if (minted.created) out.senderToken = minted.token;
324
307
  return out;
325
308
  }
326
309