@drakon-systems/multi-clawd 1.8.11 → 1.9.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.
@@ -527,6 +527,14 @@ if (!pool) {
527
527
  "cli",
528
528
  );
529
529
  const poolId = pool.id ?? "clawd";
530
+ // v1.9: anthropic/* rungs are pooled when the direct route serves two accounts.
531
+ let directPooled = false;
532
+ try {
533
+ const dr = await importDist("direct-route.js", ["directRoutePools"], "cli");
534
+ directPooled = dr.directRoutePools(accounts, pluginConfig.directRoute);
535
+ } catch {
536
+ /* dist predates the direct route */
537
+ }
530
538
  // Session keys embed the operator's private channel id (e.g. a Telegram chat
531
539
  // id). Mask the id tail by default so doctor output is safe to paste into
532
540
  // issues/support threads; `--raw` (hoisted, shared with the login identities
@@ -536,7 +544,7 @@ if (!pool) {
536
544
  RAW ? surface : surface.replace(/^session (.+)$/, (_m, k) => `session ${maskSessionKey(k)}`);
537
545
 
538
546
  // ── case 1: config-level refs ──────────────────────────────────────────────
539
- const findings = auditEffectiveChain(config, poolId);
547
+ const findings = auditEffectiveChain(config, poolId, { directPooled });
540
548
  const warns = findings.filter((f) => f.severity === "warn");
541
549
  const notes = findings.filter((f) => f.severity === "note");
542
550
  for (const f of warns) warn(`${f.surface}: ${f.ref} ${f.reason}`);
@@ -593,7 +601,7 @@ if (!pool) {
593
601
  if (read.skippedRows > 0) {
594
602
  warn(`${location.path}: ${read.skippedRows} session row(s) unparseable — those sessions were not audited`);
595
603
  }
596
- const sessionFindings = auditSessionOverrides(read.entries, true);
604
+ const sessionFindings = auditSessionOverrides(read.entries, true, { directPooled });
597
605
  for (const f of sessionFindings) {
598
606
  warn(`${renderSurface(f.surface)}: ${f.ref} ${f.reason}`);
599
607
  sessionWarns++;
@@ -703,6 +711,113 @@ console.log("chain auth");
703
711
  }
704
712
  }
705
713
 
714
+
715
+ // ── 8b. direct route — anthropic/* served by the pool's accounts (v1.9) ────
716
+ //
717
+ // Only when an account opts in with `direct`; otherwise this prints nothing,
718
+ // so doctor output for CLI-only setups is unchanged. Everything is read
719
+ // through OpenClaw's own CLI (auth list / order get / models status); token
720
+ // files are shape-checked without ever printing their contents.
721
+ if (accounts.some((a) => a && a.direct !== undefined && a.direct !== false)) {
722
+ console.log("direct route (anthropic/*)");
723
+ try {
724
+ const dr = await importDist("direct-route.js", ["collectDirectMembers"], "cli");
725
+ const rep = await importDist("direct-report.js", ["gatherDirectStatus", "parseProbeResults", "probeArgs"], "cli");
726
+ const run = await importDist("openclaw-runner.js", ["createOpenclawRunner"], "cli");
727
+ const shim = await importDist("shim-core.js", ["parseStoredState"], "cli");
728
+ const hc = await importDist("hermes-core.js", ["parseClaudeSetupToken"], "cli");
729
+ const directRoute = pluginConfig.directRoute ?? {};
730
+ const agents = Array.isArray(directRoute.agents) && directRoute.agents.length > 0 ? directRoute.agents : ["main"];
731
+ const runner = run.createOpenclawRunner(directRoute.openclawCommand ?? "openclaw");
732
+ const { members } = dr.collectDirectMembers(accounts, pool?.accounts ?? []);
733
+ // Credential sources, checked locally: present, private, setup-token shaped.
734
+ for (const m of members) {
735
+ if (m.source.kind !== "file") continue;
736
+ const path = expandHome(m.source.path);
737
+ try {
738
+ const mode = statSync(path).mode & 0o777;
739
+ hc.parseClaudeSetupToken(readFileSync(path, "utf8"));
740
+ if (mode & 0o077) warn(`${m.accountId}: direct token file ${path} is mode ${mode.toString(8)} — chmod 600 it`);
741
+ else ok(`${m.accountId}: direct token file present, 600, setup-token shaped`);
742
+ } catch (err) {
743
+ bad(`${m.accountId}: direct token file ${path} unusable — ${String(err?.message ?? err).slice(0, 160)}`);
744
+ }
745
+ }
746
+ const readHealth = (id) => {
747
+ try {
748
+ return shim.parseStoredState(readFileSync(join(STATE_DIR, `${id}.json`), "utf8"));
749
+ } catch {
750
+ return undefined;
751
+ }
752
+ };
753
+ for (const agentId of agents) {
754
+ const status = await rep.gatherDirectStatus({
755
+ accounts,
756
+ poolAccounts: pool?.accounts ?? [],
757
+ agentId,
758
+ runner,
759
+ readHealth,
760
+ healthOptions: {
761
+ utilizationThreshold: pool?.utilizationThreshold,
762
+ staleAfterMs: pool?.staleAfterMs,
763
+ rotateOnOverage: pool?.rotateOnOverage,
764
+ },
765
+ configOrder: Array.isArray(config?.auth?.order?.anthropic) ? config.auth.order.anthropic : undefined,
766
+ sticky: readJson(join(STATE_DIR, "direct-order.sticky.json")),
767
+ minDwellMs: pool?.minDwellMs,
768
+ nowMs: Date.now(),
769
+ });
770
+ if (!status) continue;
771
+ for (const p of status.explain.problems) bad(`${p.accountId}: asked for the direct route but cannot join it — ${p.reason}`);
772
+ for (const e of status.errors) warn(`agent ${agentId}: direct-route check partly SKIPPED — ${e}`);
773
+ for (const m of status.explain.members) {
774
+ const v = status.verdicts.find((x) => x.accountId === m.accountId)?.verdict ?? "no_data";
775
+ if (m.stored === false) {
776
+ bad(
777
+ m.adopted
778
+ ? `${m.accountId}: adopted profile ${m.profileId} is NOT stored for agent ${agentId} — store it yourself (openclaw models auth paste-token --provider anthropic --profile-id ${m.profileId}) or fix direct.profileId`
779
+ : `${m.accountId}: ${m.profileId} is NOT stored for agent ${agentId} — run \`multi-clawd direct sync\``,
780
+ );
781
+ }
782
+ else if (m.stored === true) ok(`${m.accountId}: ${m.profileId} stored for agent ${agentId} (health: ${v})`);
783
+ if (m.cooldownUntil && m.cooldownUntil > Date.now()) {
784
+ note(`${m.profileId} is cooling down (${m.cooldownReason ?? "cooldown"}) for ~${Math.ceil((m.cooldownUntil - Date.now()) / 60000)}m — OpenClaw skips it until then`);
785
+ }
786
+ }
787
+ if (directRoute.manageOrder === false) {
788
+ note(`agent ${agentId}: order management is off (directRoute.manageOrder: false)`);
789
+ } else if (status.pendingOrder) {
790
+ warn(
791
+ `agent ${agentId}: anthropic order is not in pool-health order yet — the gateway applies ${status.pendingOrder.join(" → ")} within a minute once this version is loaded (or run \`multi-clawd direct sync\`)`,
792
+ );
793
+ } else if (status.errors.length === 0) {
794
+ ok(`agent ${agentId}: anthropic order is in pool-health order (${(status.explain.order ?? []).join(" → ")})`);
795
+ }
796
+ const unmanaged = (status.explain.order ?? []).filter((id) => !status.explain.members.some((m) => m.profileId === id));
797
+ if (unmanaged.length > 0) {
798
+ note(`agent ${agentId}: ${unmanaged.join(", ")} not managed by multi-clawd — kept after the pool's accounts`);
799
+ }
800
+ // Live probe: one tiny call per stored managed profile.
801
+ if (args.has("--probe") && !args.has("--probe-pool")) {
802
+ const ids = status.explain.members.filter((m) => m.stored).map((m) => m.profileId);
803
+ if (ids.length > 0) {
804
+ const r = await runner(rep.probeArgs(agentId, ids), { timeoutMs: 180000 });
805
+ const results = r.code === 0 ? rep.parseProbeResults(r.stdout) : undefined;
806
+ if (!results) warn(`agent ${agentId}: direct-route probe returned nothing parseable (exit ${r.code})`);
807
+ for (const id of ids) {
808
+ const res = results?.find((x) => x.profileId === id);
809
+ if (!res) continue;
810
+ if (res.status === "ok") ok(`${id}: live probe answered via the direct API`);
811
+ else bad(`${id}: live probe ${res.status}${res.error ? ` — ${res.error}` : ""}`);
812
+ }
813
+ }
814
+ }
815
+ }
816
+ } catch (err) {
817
+ warn(`direct-route check SKIPPED — ${String(err?.message ?? err).split("\n")[0].slice(0, 160)}`);
818
+ }
819
+ }
820
+
706
821
  // ── 9. watchdog ─────────────────────────────────────────────────────────────
707
822
  console.log("eviction watchdog");
708
823
  let watchdogFound = false;
package/scripts/setup.mjs CHANGED
@@ -41,7 +41,7 @@ try {
41
41
  console.error("setup: built dist/ modules are missing — run `npm run build` first (source checkout) or reinstall the plugin.");
42
42
  process.exit(1);
43
43
  }
44
- const { buildMainAccount, buildSecondAccount, buildPool, validateSecondConfigDir, planFromExisting, mergeSetupIntoConfig, existingAccountDefaults, looksLikeSecretRef } = core;
44
+ const { buildMainAccount, buildSecondAccount, buildPool, validateSecondConfigDir, planFromExisting, mergeSetupIntoConfig, existingAccountDefaults, looksLikeSecretRef, buildDirectSetting, canReuseCliTokenForDirect } = core;
45
45
 
46
46
  // Line-queued prompts: interactive AND pipe-safe. With piped stdin, readline
47
47
  // emits every buffered line immediately — a plain question() would capture one
@@ -210,6 +210,70 @@ if (accounts.length === 0 && state.accountIds.length === 0) {
210
210
  process.exit(0);
211
211
  }
212
212
 
213
+ // ── direct route (v1.9, optional) ────────────────────────────────────────────
214
+ // The gateway's own anthropic/* models call the Anthropic API directly with an
215
+ // OpenClaw auth profile. Opting accounts in lets the pool steer those turns too
216
+ // (by keeping the auth-profile order in pool-health order). Default NO: an
217
+ // account without `direct` behaves exactly as before.
218
+ let directConfigured = false;
219
+ if (typeof buildDirectSetting === "function" &&
220
+ (await yes("\nAlso serve anthropic/* models (OpenClaw's direct Anthropic route) from these accounts?", false))) {
221
+ const byId = new Map(accounts.map((a) => [a.id, a]));
222
+ const existingAccounts = existing?.plugins?.entries?.["multi-clawd"]?.config?.accounts ?? [];
223
+ for (const id of [...new Set([...accounts.map((a) => a.id), ...state.accountIds])]) {
224
+ const current = { ...(existingAccounts.find((a) => a?.id === id) ?? {}), ...(byId.get(id) ?? {}) };
225
+ if (current.direct !== undefined) {
226
+ console.log(` ${id}: already has a direct-route setting — kept.`);
227
+ continue;
228
+ }
229
+ if (!(await yes(` Add "${id}" to the direct route?`, true))) continue;
230
+ let setting;
231
+ if (canReuseCliTokenForDirect(current) && (await yes(` reuse ${id}'s existing setup-token for it?`, true))) {
232
+ setting = buildDirectSetting(current, { kind: "reuse" });
233
+ } else {
234
+ const how = current.configDir
235
+ ? `CLAUDE_CONFIG_DIR=${current.configDir} claude setup-token`
236
+ : "claude setup-token";
237
+ console.log(`
238
+ ${id} needs a setup-token of its own for the direct route — its Claude login
239
+ is a rotating grant that multi-clawd never copies. In your own terminal, run:
240
+
241
+ ${how}
242
+
243
+ signed in as ${id}'s account (NOT your other one), and store the printed token:
244
+ 1) in your secret manager (RECOMMENDED — OpenClaw stores only the reference)
245
+ 2) in a token file (chmod 600)
246
+ 3) it is ALREADY stored in OpenClaw as an anthropic profile (give its id)
247
+ 4) skip ${id} for now`);
248
+ const choice = await ask(" choice (1/2/3/4):", "1");
249
+ try {
250
+ if (choice === "1") {
251
+ const provider = await ask(" gateway secret provider name:", "onepassword");
252
+ const refId = await ask(" secret reference (e.g. op://Vault/Item/field):");
253
+ if (refId) setting = buildDirectSetting(current, { kind: "ref", ref: { source: "exec", provider, id: refId } });
254
+ } else if (choice === "2") {
255
+ setting = buildDirectSetting(current, { kind: "file", path: await ask(" token file path:", `~/.${id}-direct-token`) });
256
+ } else if (choice === "3") {
257
+ const profileId = await ask(" existing profile id (see `openclaw models auth list --provider anthropic`):");
258
+ if (profileId.startsWith("anthropic:")) setting = { profileId };
259
+ else console.log(" ✗ profile ids for this route start with anthropic: — skipped");
260
+ }
261
+ } catch (err) {
262
+ console.log(` ✗ ${err.message} — skipped`);
263
+ }
264
+ }
265
+ if (!setting) {
266
+ console.log(` ${id}: not added.`);
267
+ continue;
268
+ }
269
+ const planned = byId.get(id);
270
+ if (planned) planned.direct = setting;
271
+ else accounts.push({ id, direct: setting });
272
+ directConfigured = true;
273
+ console.log(` ✅ ${id} will serve anthropic/* as profile ${setting.profileId ?? `anthropic:${id}`}`);
274
+ }
275
+ }
276
+
213
277
  // ── pool ─────────────────────────────────────────────────────────────────────
214
278
  const poolMemberIds = [...new Set([...accounts.map((a) => a.id), ...state.accountIds])];
215
279
  let pool;
@@ -400,6 +464,15 @@ if (DRY_RUN || !wroteConfig) {
400
464
  }
401
465
 
402
466
  // ── next steps ───────────────────────────────────────────────────────────────
467
+ if (directConfigured) {
468
+ console.log(`
469
+ Direct route: store the profiles in OpenClaw and set the order now with
470
+
471
+ multi-clawd direct sync
472
+
473
+ (refs are stored as SecretRefs — the token is never copied; the gateway then
474
+ keeps the anthropic order in pool-health order on its own).`);
475
+ }
403
476
  console.log(`
404
477
  Done. Finish with:
405
478