trantor 0.18.152 → 0.18.154

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.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
9
- "version": "0.18.152"
9
+ "version": "0.18.154"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "trantor",
14
14
  "source": "./",
15
15
  "description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
16
- "version": "0.18.152",
16
+ "version": "0.18.154",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.152",
3
+ "version": "0.18.154",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
5
5
  "mcpServers": {
6
6
  "relay": {
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { stableNodeExec } from "../lib/launch-node.mjs";
8
+ import { reloadLaunchAgent } from "../lib/launchd.mjs";
9
+ import { busDir } from "../lib/project.mjs";
10
+ import { sessionContext } from "../hooks/lib/api.mjs";
11
+
12
+ export const BALANCES_LABEL = "com.trantor.balances";
13
+ const SELF = fileURLToPath(import.meta.url);
14
+ const BALANCES_SCRIPT = join(dirname(SELF), "balances.mjs");
15
+ const xml = value => String(value).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[c]);
16
+
17
+ export function balancesPlist({ bus, home = homedir(), script = SELF, path = process.env.PATH || "/usr/bin:/bin", context = sessionContext() }) {
18
+ const body = stableNodeExec(script, ["run"]);
19
+ const env = { AGENT_BUS_DIR: bus, HOME: home, PATH: path, RELAY_SESSION: context.session, RELAY_PROJECT: context.project };
20
+ return `<?xml version="1.0" encoding="UTF-8"?>
21
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
22
+ <plist version="1.0"><dict>
23
+ <key>Label</key><string>${BALANCES_LABEL}</string>
24
+ <key>ProgramArguments</key><array><string>/bin/bash</string><string>-c</string><string>${xml(body)}</string></array>
25
+ <key>EnvironmentVariables</key><dict>${Object.entries(env).map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join("")}</dict>
26
+ <key>RunAtLoad</key><true/>
27
+ <key>StartInterval</key><integer>240</integer>
28
+ <key>StandardOutPath</key><string>${xml(join(bus, "balances-launchd.log"))}</string>
29
+ <key>StandardErrorPath</key><string>${xml(join(bus, "balances-launchd.log"))}</string>
30
+ </dict></plist>
31
+ `;
32
+ }
33
+
34
+ // #14753: an empty project signs as "<host>:" and the shared hub answers 401, so up refuses it.
35
+ export function installContext(argv = [], context = sessionContext(), env = process.env) {
36
+ const at = argv.indexOf("--project");
37
+ const project = at >= 0 ? String(argv[at + 1] || "") : context.project;
38
+ if (!project || project.startsWith("-")) throw new Error("balances collector needs a project identity: run `up` from a project checkout or pass --project <name>");
39
+ const session = at >= 0 && !env.RELAY_SESSION ? `${context.session.split(":")[0]}:${project}` : context.session;
40
+ return { session, project };
41
+ }
42
+
43
+ function errorDetail(result) {
44
+ const detail = String(result.error?.message || result.stderr || result.stdout || `balances exited with status ${result.status ?? "unknown"}`).trim();
45
+ return detail.slice(0, 1000);
46
+ }
47
+
48
+ export function runBalancesOnce({
49
+ bus = busDir(),
50
+ script = BALANCES_SCRIPT,
51
+ runner = spawnSync,
52
+ log = message => console.error(message),
53
+ } = {}) {
54
+ mkdirSync(bus, { recursive: true });
55
+ const marker = join(bus, "balances-collector.failed");
56
+ const failedBefore = existsSync(marker);
57
+ const result = runner(process.execPath, [script, "--json", "--require-push"], {
58
+ encoding: "utf8",
59
+ env: process.env,
60
+ timeout: 120000,
61
+ maxBuffer: 4 * 1024 * 1024,
62
+ stdio: ["ignore", "pipe", "pipe"],
63
+ });
64
+ if (result.status === 0 && !result.error) {
65
+ if (failedBefore) {
66
+ rmSync(marker, { force: true });
67
+ log(`${BALANCES_LABEL}: collector recovered`);
68
+ }
69
+ return 0;
70
+ }
71
+ if (!failedBefore) {
72
+ writeFileSync(marker, `${errorDetail(result)}\n`, { mode: 0o600 });
73
+ log(`${BALANCES_LABEL}: ${errorDetail(result)}`);
74
+ }
75
+ return Number.isInteger(result.status) && result.status !== 0 ? result.status : 1;
76
+ }
77
+
78
+ function launchctl(args) {
79
+ return execFileSync("launchctl", args, { encoding: "utf8", timeout: 8000, stdio: ["ignore", "pipe", "ignore"] });
80
+ }
81
+
82
+ async function main() {
83
+ const cmd = process.argv[2] || "status";
84
+ const bus = busDir();
85
+ const plist = join(homedir(), "Library", "LaunchAgents", `${BALANCES_LABEL}.plist`);
86
+ const service = `gui/${process.getuid?.() ?? 0}/${BALANCES_LABEL}`;
87
+ if (cmd === "run") {
88
+ process.exitCode = runBalancesOnce({ bus });
89
+ } else if (cmd === "up") {
90
+ if (process.platform !== "darwin") throw new Error("balances collector requires launchd");
91
+ const context = installContext(process.argv.slice(3));
92
+ mkdirSync(bus, { recursive: true });
93
+ mkdirSync(dirname(plist), { recursive: true });
94
+ writeFileSync(plist, balancesPlist({ bus, context }), { mode: 0o600 });
95
+ const reloaded = reloadLaunchAgent({ label: BALANCES_LABEL, plist, domain: `gui/${process.getuid?.() ?? 0}` });
96
+ if (!reloaded.ok) throw new Error(reloaded.error);
97
+ console.log(`${BALANCES_LABEL} installed${reloaded.pid ? ` (pid ${reloaded.pid})` : ""}; collecting every 4 minutes`);
98
+ } else if (cmd === "down") {
99
+ try { launchctl(["bootout", service]); } catch {}
100
+ rmSync(plist, { force: true });
101
+ rmSync(join(bus, "balances-collector.failed"), { force: true });
102
+ console.log(`${BALANCES_LABEL} stopped`);
103
+ } else if (cmd === "status") {
104
+ console.log(existsSync(plist) ? launchctl(["print", service]) : `${BALANCES_LABEL} not installed`);
105
+ } else {
106
+ throw new Error("usage: node bin/balances-agent.mjs up [--project <name>]|down|status|run");
107
+ }
108
+ }
109
+
110
+ if (process.argv[1] && resolve(process.argv[1]) === SELF) {
111
+ main().catch(error => { console.error(error.message); process.exitCode = 1; });
112
+ }
package/bin/balances.mjs CHANGED
@@ -2,8 +2,8 @@
2
2
  /* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: config.json is user-editable external input; thresholds validates its optional number/object fields at that I/O boundary. */
3
3
  // trantor balances: how much credit is left on each provider, so you can refill before a build
4
4
  // stalls. Queries each provider with the env keys and pushes the snapshot to the hub.
5
- // Usage: trantor balances [--json] [--no-push]
6
- import { readFileSync, existsSync } from "node:fs";
5
+ // Usage: trantor balances [--json] [--no-push] [--require-push]
6
+ import { readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { homedir } from "node:os";
9
9
  import { fetchBalances, isLow, fmtBalance, snapshotPayload, DEFAULT_LOW, DEFAULT_LOW_QUOTA_PCT } from "../lib/balances.mjs";
@@ -12,18 +12,18 @@ import { detectedCliBalanceRows } from "../lib/providers.mjs";
12
12
  import { loadProfile } from "./profile.mjs";
13
13
  import { resolveKeys } from "../lib/provider-keys.mjs";
14
14
  import { publishUsageEnabled } from "../hooks/lib/balance-check.mjs";
15
+ import { publishBalanceSnapshot } from "../lib/balance-publish.mjs";
15
16
 
16
17
  const args = process.argv.slice(2);
17
18
  const asJson = args.includes("--json");
18
19
  const noPush = args.includes("--no-push");
20
+ const requirePush = args.includes("--require-push");
19
21
 
20
22
  // API-key providers stay profile-scoped so ambient keys are never scraped. Claude and Codex are
21
23
  // machine CLI logins: the registry admits them from binary + credential + live-probe detection.
22
24
  const profileProviders = loadProfile().providers || {};
23
25
  const configured = Object.keys(profileProviders);
24
26
 
25
- // Signed via the shared client: an unsigned POST is rejected under enforce.
26
- import { signedPost } from "../hooks/lib/api.mjs";
27
27
  let _qpct = DEFAULT_LOW_QUOTA_PCT;
28
28
  function thresholds() {
29
29
  try { const c = JSON.parse(readFileSync(join(homedir(), ".agent-bus", "config.json"), "utf8")); if (typeof c.lowQuotaPct === "number") _qpct = c.lowQuotaPct; if (c.lowBalance && typeof c.lowBalance === "object") return { ...DEFAULT_LOW, ...c.lowBalance }; } catch {}
@@ -36,16 +36,17 @@ const profileScoped = await fetchBalances(env, { only: configured.filter((provid
36
36
  const balances = [...detected, ...profileScoped];
37
37
  const low = thresholds();
38
38
 
39
- // Push the snapshot to the project hub and the LOCAL hub (best-effort); the machine key and
40
- // profile let a shared hub keep one snapshot per machine. #13919: "publishUsage": false in
41
- // config.json means a seats-only machine — skip both pushes; the report above still prints.
39
+ // Push to the project and LOCAL hubs. Manual reports are best-effort;
40
+ // --require-push makes the scheduled collector fail unless the project hub accepts the snapshot.
41
+ // "publishUsage": false means a seats-only machine: skip both pushes but still print the report.
42
+ let publishFailed = false;
42
43
  if (!noPush && publishUsageEnabled()) {
43
44
  const snap = snapshotPayload(balances, { machine: hostId(), profile: profileProviders });
44
- try { await signedPost("/balances", snap, { timeoutMs: 2500 }); } catch {}
45
- try { await signedPost("http://127.0.0.1:4477/balances", snap, { timeoutMs: 2500 }); } catch {}
45
+ try { await publishBalanceSnapshot(snap, { required: requirePush }); }
46
+ catch (error) { publishFailed = true; console.error(`balances: ${error.message}`); }
46
47
  }
47
48
 
48
- if (asJson) { console.log(JSON.stringify({ balances, low: balances.filter((b) => isLow(b, low, _qpct)).map((b) => b.provider) }, null, 2)); process.exit(0); }
49
+ if (asJson) { console.log(JSON.stringify({ balances, low: balances.filter((b) => isLow(b, low, _qpct)).map((b) => b.provider) }, null, 2)); process.exit(publishFailed ? 1 : 0); }
49
50
 
50
51
  if (!balances.length) {
51
52
  if (!configured.length) {
@@ -55,7 +56,7 @@ if (!balances.length) {
55
56
  console.log(`configured providers: ${configured.join(", ")} — but none expose a balance/quota API with a key present.`);
56
57
  console.log("(subscriptions like claude/codex/gemini have nothing to refill; prepaid/coding-plan providers need their key in the env.)");
57
58
  }
58
- process.exit(0);
59
+ process.exit(publishFailed ? 1 : 0);
59
60
  }
60
61
  console.log("PROVIDER CREDITS\n");
61
62
  for (const b of balances) {
@@ -65,3 +66,4 @@ for (const b of balances) {
65
66
  }
66
67
  const lows = balances.filter((b) => isLow(b, low, _qpct));
67
68
  if (lows.length) console.log(`\n⚠ ${lows.length} provider(s) low — top up / pace: ${lows.map((b) => b.label).join(", ")}`);
69
+ if (publishFailed) process.exitCode = 1;
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // trantor crew runner — keeps a crew agent alive without burning tokens: it long-polls the bus
3
3
  // (zero tokens) and resumes the CLI with each message. Usage: node crew-runner.mjs <agent> [dir]
4
+ import { resolveKeys } from "../lib/provider-keys.mjs";
5
+ import { runnerAccountIdentity } from "../lib/dispatcher/accounts.mjs";
4
6
  import { execSync, spawnSync, spawn } from "node:child_process";
5
7
  import { randomUUID } from "node:crypto";
6
8
  import { readFileSync, writeFileSync, unlinkSync, existsSync, appendFileSync, mkdirSync, realpathSync, statSync, rmSync } from "node:fs";
@@ -547,7 +549,7 @@ async function reportFailure(exit, trigger, undelivered = 0, reasonOverride = ""
547
549
  // queue kept, ladder stopped, room told once with the reset time. `trantor up` resumes.
548
550
  let parkAnnounced = false;
549
551
  // #7914: the park this seat is currently sitting in, or null. Read by the poll loop, which ends a
550
- // bounded one the moment somebody sends a direct message, and cleared by any turn that lands.
552
+ // bounded one the moment somebody sends a waking direct message, and cleared by any turn that lands.
551
553
  let parkState = null;
552
554
  // #13949: unpark already told the room the episode ended, so the next reportHealthy must not echo
553
555
  // a second "recovered" for the same landing. Consumed on every reportHealthy call, used or not.
@@ -561,7 +563,7 @@ const sameParkEpisode = (reason) => !!(parkState && parkState.reason === reason)
561
563
  // names the resume clock (and the shortcut), a wall says it holds. Read after parkSeat sets it.
562
564
  function parkLifts() {
563
565
  return parkState?.bounded
564
- ? ` · resumes ${new Date(parkState.until).toLocaleTimeString()} (a direct message ends it now)`
566
+ ? ` · resumes ${new Date(parkState.until).toLocaleTimeString()} (a waking direct message ends it now)`
565
567
  : " — not retrying";
566
568
  }
567
569
  // #13474: uncommitted work in the seat worktree is saved on the seat branch when a turn is cut or
@@ -596,7 +598,7 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", ann
596
598
  // #7914: the notice carries its own evidence. A reader who has to open three logs to learn
597
599
  // which turns died and how is a reader who does not look, which is how 46 minutes passed.
598
600
  const why = evidence ? ` · ${evidence}` : "";
599
- const text = redactKeys(`⛔ ${SESSION} PARKED (${reason}${named}) — holding ${undelivered} message(s), redelivery stopped ${when ? `until ${when}` : `until \`trantor up ${AGENT}\``}${bounded ? " · a direct message ends the park now" : ""}${why}`);
601
+ const text = redactKeys(`⛔ ${SESSION} PARKED (${reason}${named}) — holding ${undelivered} message(s), redelivery stopped ${when ? `until ${when}` : `until \`trantor up ${AGENT}\``}${bounded ? " · a waking direct message ends the park now" : ""}${why}`);
600
602
  await api("/send", { from: SESSION, to: "all", text, project: PROJ, kind: "status" }).catch(() => {});
601
603
  const orch = `${hostId()}:${PROJ}`;
602
604
  if (orch !== SESSION) await api("/send", { from: SESSION, to: orch, text, project: PROJ, kind: "alert" }).catch(() => {});
@@ -616,7 +618,7 @@ async function parkSeat(reason, undelivered, resetHint = 0, { evidence = "", ann
616
618
  return until;
617
619
  }
618
620
 
619
- // #7914: the park is over — because a direct message asked for a turn now, or because one landed.
621
+ // #7914: the park is over — because a waking direct message asked for a turn now, or because one landed.
620
622
  // The record goes with it, and the announce latch reopens so the NEXT park is heard too (a latch
621
623
  // that never reopens turns a repeating park into one message and then silence).
622
624
  // #13949: the END is an event too, once — one "recovered" each to the room and the orchestrator.
@@ -675,6 +677,16 @@ async function balanceRows() {
675
677
  } catch { return []; }
676
678
  }
677
679
 
680
+ // Identity refresh runs outside presence: keychain lookups must not scale with beat frequency.
681
+ const ACCOUNT_IDENTITY_REFRESH_MS = 5 * 60_000;
682
+ let cachedAccountIdentity;
683
+ function refreshAccountIdentity() {
684
+ cachedAccountIdentity = runnerAccountIdentity({ harness: AGENT, model: MODEL,
685
+ env: resolveKeys(process.env, [cli.env, join(homedir(), ".agent-bus", ".env")].filter(Boolean), resolveSecrets(process.env)) });
686
+ }
687
+ refreshAccountIdentity();
688
+ setInterval(refreshAccountIdentity, ACCOUNT_IDENTITY_REFRESH_MS).unref();
689
+
678
690
  // ---- activity truth (#5965): the RUNNER is the source for this seat ----------------
679
691
  // The runner reports `working · <trigger>` at start and `idle` on a clean landing, bounded to 5s.
680
692
  // #7749: the live phase + its start ride the same call, so /peers answers what the seat does NOW.
@@ -688,6 +700,7 @@ async function registerStatus(status, extra = {}) {
688
700
  const url = HUB + "/register";
689
701
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
690
702
  payload.machine = MACHINE_LABEL || hostId().toLowerCase();
703
+ payload.accountIdentity = cachedAccountIdentity;
691
704
  const body = JSON.stringify(payload);
692
705
  try {
693
706
  const opts = { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body };
@@ -1052,6 +1065,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
1052
1065
  const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
1053
1066
  agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
1054
1067
  presencePayload.machine = MACHINE_LABEL || hostId().toLowerCase();
1068
+ presencePayload.accountIdentity = cachedAccountIdentity;
1055
1069
  writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
1056
1070
  presence: { intervalMs: PRESENCE_MS, payload: presencePayload },
1057
1071
  worktree: { cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: presencePayload.machine } }));
@@ -1954,10 +1968,10 @@ async function resolveWakeCard(messages, { session }) {
1954
1968
  savePending(pendingWake, pendingBcast);
1955
1969
  }
1956
1970
  if (awaitingAsk) { log(`holding for the answer to ask #${awaitingAsk.id} — ${wake.length} new message(s) queued behind it`); continue; }
1957
- // #7914: a fresh DIRECT message to a parked seat is somebody asking for a turn now, so it ends
1958
- // a bounded park instead of queueing behind the window; a mention does not, because the room
1959
- // talking is not a request. An exhausted or auth park is a wall and stands anyway (#6134).
1960
- const directWake = wake.filter(m => m.to === SESSION);
1971
+ // #7914: a fresh waking DIRECT message to a parked seat is somebody asking for a turn now, so
1972
+ // it ends a bounded park instead of queueing behind the window; a mention or wake:false note
1973
+ // does not. An exhausted or auth park is a wall and stands anyway (#6134).
1974
+ const directWake = wake.filter(m => m.to === SESSION && m.wake !== false);
1961
1975
  // #10197: no-delivery owes the old contract, but its retry delay must not batch away
1962
1976
  // fresh contracts. Only actual CLI failures impose backoff on a new wake.
1963
1977
  if (noDeliveryRetry) {
@@ -249,11 +249,14 @@ export async function runDuty(args) {
249
249
  const wakeArgs = [cmd, "--hub", fleetHub(args)];
250
250
  const supported = ["up", "down", "status"].includes(cmd) && process.platform === "darwin";
251
251
  const wakeCode = supported && cmd === "down" ? await execute("wake-nudge.mjs", wakeArgs) : 0;
252
+ const balancesStopCode = supported && cmd === "down" ? await execute("balances-agent.mjs", [cmd]) : 0;
252
253
  const dutyCode = await execute("duty.mjs", args);
253
254
  if (supported && (cmd === "status" || (cmd === "up" && dutyCode === 0))) {
254
- return (await execute("wake-nudge.mjs", wakeArgs)) || dutyCode;
255
+ const wakeServiceCode = await execute("wake-nudge.mjs", wakeArgs);
256
+ const balancesServiceCode = await execute("balances-agent.mjs", [cmd]);
257
+ return wakeServiceCode || balancesServiceCode || dutyCode;
255
258
  }
256
- return dutyCode || wakeCode;
259
+ return dutyCode || wakeCode || balancesStopCode;
257
260
  }
258
261
 
259
262
  const xml = value => String(value).replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" })[c]);
package/hub/events.mjs CHANGED
@@ -31,7 +31,7 @@ function touch(session, status, project, hookVersion, auth, machine) {
31
31
  // channels their own harness controls (hooks/inbox-deliver.mjs and hooks/stop-inbox.mjs).
32
32
  delete p.tty; delete p.windowId; delete p.host;
33
33
  // Keep only an operator-chosen short label. Never retain the full host field.
34
- if (typeof machine === "string" && /^[a-z0-9-]{1,24}$/.test(machine)) p.machine = machine;
34
+ if (typeof machine === "string" && /^[a-z0-9-]{1,24}$/i.test(machine)) p.machine = machine;
35
35
  const wasOnline = p._on === true; // explicit flag, so the log gets ONE event per transition
36
36
  p.lastSeen = now();
37
37
  if (status !== undefined) p.status = String(status).slice(0, 280);
@@ -55,8 +55,8 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
55
55
  const cpg = crossProjectGuard(auth, P, b);
56
56
  if (!cpg.ok) return json(res, cpg.code, { error: cpg.error });
57
57
  touch(b.session, b.status, b.project, b.hookVersion, auth, b.machine);
58
- // WHO is this, really: the LLM brand + the exact model currently loaded. In-memory like the
59
- // rest of presence — the next heartbeat re-supplies it after a restart.
58
+ // WHO is this, really: the LLM brand + the exact model currently loaded. These runner-owned
59
+ // fields persist with the peer so an idle seat survives a hub restart without another turn.
60
60
  const pr = state.peers[b.session];
61
61
  if (pr && b.gitRoot) {
62
62
  pr.gitRoot = String(b.gitRoot).slice(0, 2000);
@@ -68,6 +68,15 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
68
68
  // #6148: WHAT a session is rides its peer row (kind "genesis" = the CLI's brief-poster,
69
69
  // "agent" = a crew seat) — /peers hands it to the app so the seat strip can tell them apart.
70
70
  if (pr) { if (b.model) pr.model = String(b.model).slice(0, 80); if (b.llm) pr.llm = String(b.llm).slice(0, 40); if (b.kind) pr.kind = String(b.kind).slice(0, 40); }
71
+ // Hooks and MCP beats share the runner's session name; only the runner may rotate or clear its account binding.
72
+ const fromRunner = typeof b.persona === "string" && b.persona.length > 0 && typeof b.agent === "string" && b.agent.length > 0;
73
+ if (pr && fromRunner && Object.hasOwn(b, 'accountIdentity')) {
74
+ const identity = b.accountIdentity;
75
+ const provider = typeof identity?.provider === "string" && /^[a-z0-9-]{1,60}$/.test(identity.provider) ? identity.provider : 'unknown';
76
+ const subject = typeof identity?.subject === "string" && /^s-[a-f0-9]{32}$/.test(identity.subject) ? identity.subject : null;
77
+ pr.accountIdentity = { provider, subject, reason: subject ? null : `subject_unavailable:${provider}` };
78
+ markDirty();
79
+ }
71
80
  // #7749: the runner's live turn phase (working/idle/cut/stalled/parked) + its start ride the
72
81
  // presence row, so /peers answers "what is the seat doing now" without inferring it from durations.
73
82
  if (pr && b.phase) { pr.phase = String(b.phase).slice(0, 20); pr.phaseSince = Number(b.phaseSince) || now(); }
@@ -445,7 +454,8 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
445
454
  const entries = (snap?.entries || []).filter(e => detectedCli.has(e.provider) || profByCanon[canonP(e.provider)]).map(e => {
446
455
  const pv = profByCanon[canonP(e.provider)];
447
456
  if (!e.ok && isSub(pv?.tier)) return { provider: e.provider, label: e.label, kind: "subscription", plan: pv.plan, ok: true, remaining: null, low: false };
448
- return { ...e, low: lowOf(e) };
457
+ const { subject: _subject, billingSubject: _billingSubject, ...entry } = e;
458
+ return { ...entry, low: lowOf(e) };
449
459
  });
450
460
  // List configured non-CLI subscriptions not already fetched. Claude/Codex may only come from
451
461
  // live registry detection above; a stale profile declaration cannot manufacture either row.
package/hub/store.mjs CHANGED
@@ -153,10 +153,8 @@ function normalizeState(loaded = {}) {
153
153
  // migrate old numeric form
154
154
  s.peers[session] = typeof v === "number"
155
155
  ? { lastSeen: v, status: "", project: "" }
156
- // #6170: `kind` rides the load. This normalizer rebuilds every peer from an explicit field
157
- // list, so a field missing here is dropped however faithfully the store returned it (the kinds
158
- // came back empty on the first live restart). llm/model stay out: they are in-memory presence.
159
- : { lastSeen: v.lastSeen || 0, status: v.status || "", project: v.project || "", pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "", hookVersion: v.hookVersion || "", kind: v.kind || "", gitRoot: v.gitRoot || loaded.overseerState?.roots?.[session] || "", deliveredUpTo: v.deliveredUpTo || v.delivered_up_to || 0, _on: v._on === true || v.online === true };
156
+ // #6170/#14760: this explicit projection must retain every durable peer field.
157
+ : { lastSeen: v.lastSeen || 0, status: v.status || "", project: v.project || "", pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "", hookVersion: v.hookVersion || "", kind: v.kind || "", machine: v.machine || "", llm: v.llm || "", model: v.model || "", accountIdentity: v.accountIdentity || null, gitRoot: v.gitRoot || loaded.overseerState?.roots?.[session] || "", deliveredUpTo: v.deliveredUpTo || v.delivered_up_to || 0, _on: v._on === true || v.online === true };
160
158
  }
161
159
  return s;
162
160
  }
@@ -454,7 +452,8 @@ setInterval(persist, persistTickMs).unref?.();
454
452
  const nowMs = Date.now();
455
453
  return seatsView({ peers: state.peers, messages: state.messages, nowMs,
456
454
  onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000),
457
- lastRows: turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 }) });
455
+ lastRows: turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 }) })
456
+ .map(seat => ({ ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity }));
458
457
  },
459
458
  discovery: () => {
460
459
  if (!discovery || Date.now() - discoveryAt >= CACHE_TTL_MS) {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.152",
3
+ "version": "0.18.154",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
5
5
  "interface": {
6
6
  "displayName": "Trantor",
@@ -0,0 +1,22 @@
1
+ import { signedPost } from "../hooks/lib/api.mjs";
2
+
3
+ export async function publishBalanceSnapshot(snapshot, { post = signedPost, required = false } = {}) {
4
+ const failures = [];
5
+ let accepted = false;
6
+ let projectAccepted = false;
7
+ for (const target of ["/balances", "http://127.0.0.1:4477/balances"]) {
8
+ try {
9
+ const result = await post(target, snapshot, { timeoutMs: 2500 });
10
+ if (result?.ok) {
11
+ accepted = true;
12
+ if (target === "/balances") projectAccepted = true;
13
+ continue;
14
+ }
15
+ failures.push(`${target}: hub ${result?.status ?? 0}`);
16
+ } catch (error) {
17
+ failures.push(`${target}: ${error.message}`);
18
+ }
19
+ }
20
+ if (required && !projectAccepted) throw new Error(`snapshot was not accepted by the project hub (${failures.join("; ")})`);
21
+ return accepted;
22
+ }
package/lib/balances.mjs CHANGED
@@ -5,6 +5,8 @@ import { readFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { homedir } from "node:os";
7
7
 
8
+ import { readProviderIdentity } from "./dispatcher/accounts.mjs";
9
+
8
10
  const TIMEOUT = 8000;
9
11
 
10
12
  async function getJSON(url, key, extraHeaders = {}) {
@@ -113,12 +115,16 @@ export const ADAPTERS = [
113
115
  },
114
116
  {
115
117
  provider: "kimi", label: "Kimi Code", kind: "quota", match: ["kimi"], envKeys: ["KIMI_API_KEY"], keyless: true,
116
- async fetch(key, env = {}) {
118
+ async fetch(key, env = {}, options = {}) {
117
119
  // Prefer the explicit API key; OAuth is read-only and never refreshes Kimi's credentials.
118
120
  let oauthCredentials = null;
119
121
  if (!key) {
120
122
  try {
121
- oauthCredentials = JSON.parse(readFileSync(join(homedir(), ".kimi-code", "credentials", "kimi-code.json"), "utf8"));
123
+ for (const directory of [".kimi-code", ".kimi"]) {
124
+ try { oauthCredentials = JSON.parse(readFileSync(join(options.home ?? homedir(), directory, "credentials", "kimi-code.json"), "utf8")); }
125
+ catch { continue; }
126
+ if (oauthCredentials?.access_token) break;
127
+ }
122
128
  key = oauthCredentials?.access_token;
123
129
  } catch { /* absent or unreadable login is handled as no token below */ }
124
130
  }
@@ -255,26 +261,30 @@ async function claudeOAuthToken() {
255
261
  }
256
262
 
257
263
  export async function fetchBalances(env = process.env, opts = {}) {
264
+ const identities = new Map();
265
+ const identityFor = provider => readProviderIdentity({ provider, env, home: opts.home ?? homedir() });
258
266
  const only = Array.isArray(opts.only) ? new Set(opts.only.map((s) => String(s).toLowerCase())) : null;
259
267
  const jobs = ADAPTERS.map(async (a) => {
260
268
  const names = (a.match || [a.provider]).map((s) => s.toLowerCase());
261
269
  if (!only || !names.some((n) => only.has(n))) return null; // not a Trantor-configured provider → skip
262
270
  const envKey = a.envKeys.find((k) => env[k]);
263
271
  if (!envKey && !a.keyless) return null; // configured but no key in env → can't query
272
+ identities.set(a.provider, identityFor(a.provider));
264
273
  const base = { provider: a.provider, label: a.label, kind: a.kind, via: envKey || "oauth" };
265
274
  // `env` rides along for adapters that read more than a key (Qwen's base URL); the rest ignore it.
266
- try { return { ...base, ok: true, ...(await a.fetch(envKey ? env[envKey] : undefined, env)) }; }
275
+ try { return { ...base, ok: true, ...(await a.fetch(envKey ? env[envKey] : undefined, env, opts)) }; }
267
276
  catch (e) { return { ...base, ok: false, error: String(e?.message || e) }; }
268
277
  });
269
278
  const rows = (await Promise.all(jobs)).filter(Boolean);
270
279
  // Codex: no public balance API, so the CLI's own token reads the ChatGPT usage windows (#5570);
271
280
  // unreachable → the flat subscription row. Profile-gated like every adapter: no profile, no row.
272
281
  if (only && (only.has("codex") || only.has("openai"))) {
282
+ identities.set("codex", identityFor("codex"));
273
283
  try {
274
284
  const { existsSync, readFileSync } = await import("node:fs");
275
285
  const { join } = await import("node:path");
276
286
  const { homedir } = await import("node:os");
277
- const authPath = join(homedir(), ".codex", "auth.json");
287
+ const authPath = join(env.CODEX_HOME || join(opts.home ?? homedir(), ".codex"), "auth.json");
278
288
  if (existsSync(authPath)) {
279
289
  const base = { provider: "codex", label: "Codex", via: "codex login", ok: true };
280
290
  try {
@@ -308,7 +318,14 @@ export async function fetchBalances(env = process.env, opts = {}) {
308
318
  }
309
319
  } catch { /* no fs access → no row, never an error */ }
310
320
  }
311
- return rows;
321
+ return rows.map(row => {
322
+ const identity = identityFor(row.provider);
323
+ const subject = identities.get(row.provider)?.subject === identity.subject ? identity.subject : null;
324
+ const entry = { ...row, subjectReason: subject ? null : `subject_unavailable:${row.provider}` };
325
+ // Public CLI/provider JSON must omit subjects; only snapshotPayload publishes them to the bridge.
326
+ Object.defineProperty(entry, 'subject', { value: subject, enumerable: false });
327
+ return entry;
328
+ });
312
329
  }
313
330
 
314
331
  // human one-liner for a credit entry (CLI + warning line)
@@ -346,7 +363,12 @@ export function fmtReset(t) {
346
363
  // The snapshot a machine pushes to a hub: its balances plus the machine key and the provider
347
364
  // profile, so a shared hub can keep one snapshot per machine and filter by that machine's profile.
348
365
  export function snapshotPayload(balances, { machine, profile, by, ts = Date.now() }) {
349
- const snap = { balances, ts, machine: String(machine || ""), profile: profile ?? {} };
366
+ const entries = balances.map(entry => {
367
+ const row = { ...entry };
368
+ if (Object.hasOwn(entry, 'subject')) row.subject = entry.subject;
369
+ return row;
370
+ });
371
+ const snap = { balances: entries, ts, machine: String(machine || ""), profile: profile ?? {} };
350
372
  if (by) snap.by = by;
351
373
  return snap;
352
374
  }
@@ -1,9 +1,87 @@
1
1
  // #14671 (B1): dispatcher accounts — the pure accounting core for §5 of docs/TDD-dispatcher.md:
2
2
  // binding provider subjects to opaque account IDs, window freshness, the shared protected
3
3
  // reserve, the admission inequality, watermark-less epochs, daily/reset rollover, escrow.
4
- // Pure: callers pass nowMs. USD is integer microdollars, quota millionths; unknown stays null.
4
+ // Accounting callers pass nowMs. USD is integer microdollars, quota millionths; unknown stays null.
5
5
 
6
6
  import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
7
+ import { readFileSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { homedir } from 'node:os';
10
+
11
+ // Stable IDs and internal key fingerprints become subjects; credentials never leave the reader.
12
+ // no zod here: lib/balances.mjs pulls this into the hook snapshot, which ships no node_modules (#14754)
13
+ const isLoginId = value => typeof value === 'string' && value.length >= 1 && value.length <= 512
14
+ && value === value.trim() && !value.includes('@');
15
+ export function providerSubject({ provider, loginId }) {
16
+ if (!isLoginId(loginId) || !provider) return null;
17
+ return `s-${createHash('sha256').update(`${provider}\u0000${loginId}`).digest('hex').slice(0, 32)}`;
18
+ }
19
+
20
+ function loginFile(path) {
21
+ try { return JSON.parse(readFileSync(path, 'utf8')); }
22
+ catch { return null; }
23
+ }
24
+
25
+ function oneLoginId(values) {
26
+ const ids = [...new Set(values.filter(value => value != null && value !== ''))];
27
+ return ids.length === 1 ? ids[0] : null;
28
+ }
29
+
30
+ function tokenIdentity(token) {
31
+ if (typeof token !== 'string') return null;
32
+ try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); }
33
+ catch { return null; }
34
+ }
35
+
36
+ function credentialLogin(key) {
37
+ return typeof key === 'string' && key.length > 0 ? `key:${createHash('sha256').update(key).digest('hex')}` : null;
38
+ }
39
+
40
+ export function readProviderIdentity({ provider, home = homedir(), env = process.env }) {
41
+ let loginId = null;
42
+ const keyNames = { zai: ['ZAI_API_KEY', 'GLM_API_KEY'], kimi: ['KIMI_API_KEY'],
43
+ deepseek: ['DEEPSEEK_API_KEY'], openrouter: ['OPENROUTER_API_KEY'],
44
+ moonshot: ['MOONSHOT_API_KEY'], qwen: ['QWEN_API_KEY'] };
45
+ const key = (keyNames[provider] || []).map(name => env[name]).find(Boolean);
46
+ if (key) {
47
+ loginId = credentialLogin(key);
48
+ } else if (provider === 'codex') {
49
+ const auth = loginFile(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json'));
50
+ if (!auth?.OPENAI_API_KEY && auth?.tokens?.access_token) {
51
+ loginId = auth.tokens.account_id || tokenIdentity(auth.tokens.id_token)?.sub;
52
+ }
53
+ } else if (provider === 'claude') {
54
+ if (!env.ANTHROPIC_API_KEY && !env.ANTHROPIC_AUTH_TOKEN) {
55
+ const auth = loginFile(join(env.CLAUDE_CONFIG_DIR || join(home, '.claude'), '.credentials.json'));
56
+ const config = loginFile(env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'));
57
+ loginId = oneLoginId([auth?.claudeAiOauth?.accountUuid, config?.oauthAccount?.accountUuid]);
58
+ }
59
+ } else if (provider === 'kimi' && !env.KIMI_API_KEY) {
60
+ const auth = ['.kimi-code', '.kimi'].map(directory => loginFile(join(home, directory, 'credentials', 'kimi-code.json')))
61
+ .find(value => value?.access_token);
62
+ if (auth) {
63
+ const token = tokenIdentity(auth.access_token);
64
+ const ids = [auth.user_id, auth.userId, auth.user?.id, token?.user_id].filter(value => value != null && value !== '');
65
+ loginId = ids.length ? oneLoginId(ids) : token?.sub;
66
+ }
67
+ } else {
68
+ const auth = loginFile(join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode', 'auth.json'));
69
+ const names = provider === 'zai' ? ['zai', 'zai-coding-plan'] : [provider];
70
+ const entries = names.map(name => auth?.[name]).filter(Boolean);
71
+ if (entries.length === 1) {
72
+ const ids = [entries[0].userId, entries[0].user_id, entries[0].accountId].filter(value => value != null && value !== '');
73
+ loginId = ids.length ? oneLoginId(ids) : credentialLogin(entries[0].key);
74
+ }
75
+ }
76
+ const subject = providerSubject({ provider, loginId });
77
+ return { provider, subject, reason: subject ? null : `subject_unavailable:${provider}` };
78
+ }
79
+
80
+ export function runnerAccountIdentity({ harness, model = '', ...options }) {
81
+ const selected = harness === 'opencode' ? model.split('/')[0] : harness;
82
+ const provider = ({ glm: 'zai', dsh: 'deepseek', 'zai-coding-plan': 'zai' })[selected] || selected;
83
+ return readProviderIdentity({ ...options, provider });
84
+ }
7
85
 
8
86
  const compare = (a, b) => Buffer.compare(Buffer.from(String(a)), Buffer.from(String(b)));
9
87
 
@@ -56,6 +134,18 @@ export function bindAccounts({ org, bindings = [], orchestrators = [] }) {
56
134
  return { accounts, unmapped };
57
135
  }
58
136
 
137
+ export function resolveSeatAccount({ identity, accounts }) {
138
+ const provider = identity?.provider || 'unknown';
139
+ if (!/^s-[a-f0-9]{32}$/.test(identity?.subject)) {
140
+ return { accountId: null, reason: `subject_unavailable:${provider}` };
141
+ }
142
+ const matching = accounts.filter(account => account.status === 'verified'
143
+ && account.provider === provider && account.subject === identity.subject);
144
+ if (matching.length !== 1) return { accountId: null,
145
+ reason: `${matching.length ? 'subject_ambiguous' : 'subject_unmatched'}:${provider}` };
146
+ return { accountId: matching[0].id, reason: null };
147
+ }
148
+
59
149
  // Freshness of a remaining observation (§5: admission uses a shorter balance TTL than display).
60
150
  // A null value stays unknown regardless of age — Number(null) must never read as a zero balance.
61
151
  // A source-declared status wins; an ok observation older than the TTL is stale by age.
@@ -1,4 +1,5 @@
1
- import { bindAccounts } from './accounts.mjs';
1
+ import { bindAccounts, resolveSeatAccount } from './accounts.mjs';
2
+ import { canonicalHash } from './snapshot.mjs';
2
3
  import { heldLiability } from './spend.mjs';
3
4
  import { DEFAULT_POLICY } from './policy.mjs';
4
5
  import { loadCatalog, lookup } from '../model-catalog.mjs';
@@ -176,7 +177,13 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
176
177
  return evidence;
177
178
  }
178
179
 
179
- function seatEvidence({ rows, nowMs, policy }) {
180
+ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
181
+ const bindings = balances.filter(snapshot => fresh(timestamp(snapshot?.ts), nowMs, policy.balanceTtlMs))
182
+ .flatMap(snapshot => (Array.isArray(snapshot.entries) ? snapshot.entries : []).map(entry => ({
183
+ provider: entry?.provider, subject: entry?.subject ?? entry?.billingSubject,
184
+ machine: snapshot.machine, bindingRevision: String(snapshot.ts),
185
+ })));
186
+ const { accounts } = bindAccounts({ org: orgId, bindings });
180
187
  const evidence = [];
181
188
  for (const row of Array.isArray(rows) ? rows : []) {
182
189
  const id = text(row?.session, 200);
@@ -185,11 +192,15 @@ function seatEvidence({ rows, nowMs, policy }) {
185
192
  const observedAtMs = timestamp(row?.lastSeen);
186
193
  if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
187
194
  const lastTurnMs = timestamp(row?.lastTurn?.ts);
195
+ const binding = resolveSeatAccount({ identity: row.accountIdentity, accounts });
196
+ const record = { id, machine, accountId: binding.accountId, accountBindingReason: binding.reason,
197
+ harness, model: text(row.model, 512) || null,
198
+ busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
199
+ lastBeatMs: observedAtMs, lastTurnMs };
200
+ if (row.project) record.project = text(row.project, 200);
188
201
  evidence.push({ kind: 'seat', id, source: 'presence', sourceRef: `presence:${id}:${observedAtMs}`,
189
202
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
190
- record: { id, machine, accountId: null, harness, model: text(row.model, 512) || null,
191
- busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
192
- lastBeatMs: observedAtMs, lastTurnMs } });
203
+ record });
193
204
  }
194
205
  return evidence;
195
206
  }
@@ -255,16 +266,36 @@ export function buildEvidence({ balances = [], machines = [], seats = [], discov
255
266
  return [
256
267
  ...balanceEvidence({ snapshots: balances, orgId, nowMs, policy }),
257
268
  ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
258
- ...seatEvidence({ rows: presentSeats, nowMs, policy }),
269
+ ...seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy }),
259
270
  ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
260
271
  ];
261
272
  }
262
273
 
274
+ const bridgeStates = new WeakMap();
275
+
276
+ function bridgeState(service, orgId, grantId) {
277
+ if (!bridgeStates.has(service)) bridgeStates.set(service, new Map());
278
+ const states = bridgeStates.get(service);
279
+ const key = JSON.stringify([orgId, grantId]);
280
+ if (!states.has(key)) states.set(key, { accepted: new Map(), failures: new Set() });
281
+ return states.get(key);
282
+ }
283
+
284
+ function contentHash(envelope) {
285
+ const record = structuredClone(envelope.record);
286
+ const observations = envelope.kind === 'account' ? record.windows.map(window => window.remaining)
287
+ : envelope.kind === 'machine' ? [record.health]
288
+ : envelope.kind === 'model' ? [record.catalog, record.entitlement, record.invocation] : [];
289
+ for (const item of observations) delete item.receivedAtMs;
290
+ return canonicalHash({ source: envelope.source, sourceRef: envelope.sourceRef, record });
291
+ }
292
+
263
293
  export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
264
- clock = Date.now, policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
294
+ clock = Date.now, policy = DEFAULT_POLICY, catalog = loadCatalog(), log = console.warn }) {
265
295
  if (!service || !orgId || !grantId || !sources) {
266
296
  throw new TypeError('evidence bridge requires service, orgId, grant and sources');
267
297
  }
298
+ const state = bridgeState(service, orgId, grantId);
268
299
  async function tick() {
269
300
  const nowMs = clock();
270
301
  const [balances, machines, seats, discovery] = await Promise.all([
@@ -273,11 +304,41 @@ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
273
304
  const pending = buildEvidence({ balances, machines, seats, discovery, orgId, nowMs, policy, catalog })
274
305
  .filter(envelope => envelope.expiresAtMs > clock());
275
306
  let written = 0;
307
+ let rejected = 0;
308
+ const keys = new Set(pending.map(envelope => JSON.stringify([envelope.kind, envelope.id])));
309
+ for (const key of state.accepted.keys()) if (!keys.has(key)) state.accepted.delete(key);
310
+ for (const key of state.failures) if (!keys.has(key)) state.failures.delete(key);
276
311
  for (const envelope of pending) {
277
- const result = await service.registerEvidence(orgId, envelope, { grant: grantId });
278
- if (!result.replayed) written++;
312
+ const key = JSON.stringify([envelope.kind, envelope.id]);
313
+ const sourceTime = envelope.observedAtMs;
314
+ const hash = contentHash(envelope);
315
+ const previous = state.accepted.get(key);
316
+ if (previous && sourceTime >= previous.sourceTime && sourceTime <= previous.observedAtMs) {
317
+ envelope.observedAtMs = hash === previous.hash ? previous.observedAtMs : nowMs;
318
+ }
319
+ try {
320
+ let result;
321
+ try {
322
+ result = await service.registerEvidence(orgId, envelope, { grant: grantId });
323
+ } catch (error) {
324
+ // A restarted bridge can encounter a derived observation already persisted by its predecessor.
325
+ if (previous || !['evidence_conflict', 'evidence_stale'].includes(error.code)
326
+ || envelope.observedAtMs >= nowMs) throw error;
327
+ envelope.observedAtMs = nowMs;
328
+ result = await service.registerEvidence(orgId, envelope, { grant: grantId });
329
+ }
330
+ state.accepted.set(key, { sourceTime, hash, observedAtMs: envelope.observedAtMs });
331
+ state.failures.delete(key);
332
+ if (!result.replayed) written++;
333
+ } catch (error) {
334
+ rejected++;
335
+ if (!state.failures.has(key)) {
336
+ state.failures.add(key);
337
+ log(`[trantor] evidence bridge rejected ${envelope.kind}:${envelope.id}: ${error.code || error.message}`);
338
+ }
339
+ }
279
340
  }
280
- return { observed: pending.length, written, skipped: pending.length - written };
341
+ return { observed: pending.length, written, skipped: pending.length - written - rejected, rejected };
281
342
  }
282
343
  return { tick, build: input => buildEvidence({ ...input, orgId, nowMs: clock(), policy, catalog }) };
283
344
  }
@@ -269,7 +269,8 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
269
269
  return store.locked(orgId, async client => {
270
270
  const identity = await requireRole(client, orgId, actor, request.project, ['read', 'write', 'approver', 'owner']);
271
271
  const { snapshot } = await readAdvice(client, { orgId, request });
272
- const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project)))];
272
+ const projects = [...new Set(snapshot.projectScheduling.map(p => p.project).concat(snapshot.readyQueue.map(c => c.project),
273
+ snapshot.seats.map(seat => seat.project).filter(Boolean)))];
273
274
  return projectSnapshot(snapshot, projects.filter(p => storedScopeAllows(identity, p, ['read', 'write', 'approver', 'owner'])));
274
275
  });
275
276
  },
@@ -103,6 +103,7 @@ export const MachineSchema = object({
103
103
  credentialBindings: strings, maxSeats: integer, activeSeats: integer, adapterVersions: strings,
104
104
  });
105
105
  export const SeatSchema = object({
106
+ project: text.optional(), accountBindingReason: nullable(text).optional(),
106
107
  id: text, machine: text, accountId: nullable(text), harness: text, model: nullable(text),
107
108
  busy: z.boolean(), lastBeatMs: nullable(integer), lastTurnMs: nullable(integer),
108
109
  });
@@ -129,17 +129,22 @@ export async function buildStoredSnapshot(client, orgId, nowMs, degraded = []) {
129
129
  export function projectSnapshot(snapshot, readableProjects) {
130
130
  const projects = [...new Set(readableProjects)].sort(compare);
131
131
  const visible = project => projects.includes(project);
132
- const payload = { accounts: snapshot.accounts, models: snapshot.models.map(({ invocation: _invocation, liveUse: _liveUse, ...model }) => model),
132
+ const visibleSeats = snapshot.seats.filter(seat => visible(seat.project));
133
+ const bound = seat => seat.accountId != null && snapshot.accounts.some(account =>
134
+ account.id === seat.accountId && account.status === 'verified');
135
+ const degraded = [...new Set([...snapshot.degraded, ...visibleSeats.filter(seat => !bound(seat))
136
+ .map(seat => seat.accountBindingReason || 'account_unmapped')])];
137
+ const payload = { accounts: snapshot.accounts.map(({ subject: _subject, billingSubject: _billingSubject, ...account }) => account), models: snapshot.models.map(({ invocation: _invocation, liveUse: _liveUse, ...model }) => model),
133
138
  machines: snapshot.machines.map(({ id, health, maxSeats, activeSeats }) => ({ id, health, maxSeats, activeSeats })),
134
- seats: [], claims: [], readyQueue: snapshot.readyQueue.filter(card => visible(card.project))
139
+ seats: visibleSeats.filter(bound), claims: [], readyQueue: snapshot.readyQueue.filter(card => visible(card.project))
135
140
  .map(card => ({ ...card, deps: card.deps.filter(dep => visible(dep.project)) })),
136
141
  projectScheduling: snapshot.projectScheduling.filter(row => visible(row.project)),
137
- acceptedDependencies: snapshot.acceptedDependencies.filter(row => visible(row.project)), degraded: snapshot.degraded };
142
+ acceptedDependencies: snapshot.acceptedDependencies.filter(row => visible(row.project)), degraded };
138
143
  const visibility = { projects, aggregates: ['budgets', 'machine-headroom'], redactionVersion: 1 };
139
144
  const hashed = { schemaVersion: 1, projectionVersion: 1, snapshotId: snapshot.id, asOfMs: snapshot.asOfMs,
140
145
  policyVersion: snapshot.policyVersion, plannerVersion: snapshot.plannerVersion, visibility, payload };
141
146
  const projectionHash = canonicalHash(hashed);
142
147
  return { schemaVersion: 1, snapshotId: snapshot.id, snapshotHash: projectionHash, projectionHash,
143
148
  hashKind: 'projection', projectionVersion: 1, visibility, asOfMs: snapshot.asOfMs,
144
- policyVersion: snapshot.policyVersion, localOnly: false, snapshot: payload, degraded: snapshot.degraded };
149
+ policyVersion: snapshot.policyVersion, localOnly: false, snapshot: payload, degraded };
145
150
  }
package/lib/git-guard.mjs CHANGED
@@ -98,13 +98,36 @@ export function cacheGitPolicy(repo, project, policy, now = Date.now()) {
98
98
  atomicJson(cachePath(repo), { project, policy: gitPolicy(policy), fetchedAtMs: now });
99
99
  }
100
100
 
101
- export function cachedGitPolicy(repo, now = Date.now()) {
101
+ function freshCachedGitPolicy(repo, now) {
102
102
  try {
103
103
  const config = readGuard(repo);
104
104
  const cached = cacheSchema.parse(JSON.parse(readFileSync(cachePath(repo), "utf8")));
105
- if (!config || cached.project !== config.project || cached.fetchedAtMs > now || now - cached.fetchedAtMs > GIT_POLICY_CACHE_MS) return gitPolicy(null);
105
+ if (!config || cached.project !== config.project || cached.fetchedAtMs > now || now - cached.fetchedAtMs > GIT_POLICY_CACHE_MS) return null;
106
106
  return gitPolicy(cached.policy);
107
107
  } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ export function cachedGitPolicy(repo, now = Date.now()) {
113
+ return freshCachedGitPolicy(repo, now) || gitPolicy(null);
114
+ }
115
+
116
+ function hookGitPolicy(repo) {
117
+ const cached = freshCachedGitPolicy(repo, Date.now());
118
+ if (cached) return cached;
119
+ try {
120
+ const project = readGuard(repo)?.project;
121
+ if (!project) return gitPolicy(null);
122
+ const output = execFileSync(process.execPath, [modulePath, "refresh-hook", project], {
123
+ cwd: repo, encoding: "utf8", timeout: 2000, killSignal: "SIGKILL",
124
+ stdio: ["ignore", "pipe", "pipe"],
125
+ });
126
+ const policy = gitPolicy(JSON.parse(output));
127
+ cacheGitPolicy(repo, project, policy);
128
+ return policy;
129
+ } catch {
130
+ // An unavailable hub or timed-out child must not reuse expired permissions.
108
131
  return gitPolicy(null);
109
132
  }
110
133
  }
@@ -131,7 +154,7 @@ export function installGitGuard(repo, project) {
131
154
  renameSync(hook, backup);
132
155
  }
133
156
  atomicJson(configPath(repo), { project, checkout });
134
- const script = `#!/bin/sh\n${marker}\nif [ "$1" = prepared ] && [ -n "\${TRANTOR_AGENT_IDENTITY:-}\${RELAY_SESSION:-}" ]; then\n ${shellQuote(process.execPath)} ${shellQuote(modulePath)} hook "$1" || exit $?\nfi\nif [ -x ${shellQuote(backup)} ]; then exec ${shellQuote(backup)} "$@"; fi\n`;
157
+ const script = `#!/bin/sh\n${marker}\nif [ "$1" = prepared ] && [ -n "\${TRANTOR_AGENT_IDENTITY:-}\${RELAY_SESSION:-}" ]; then\n updates=$(cat)\n printf '%s\\n' "$updates" | ${shellQuote(process.execPath)} ${shellQuote(modulePath)} hook "$1" || exit $?\n if [ -x ${shellQuote(backup)} ]; then printf '%s\\n' "$updates" | ${shellQuote(backup)} "$@"; exit $?; fi\nfi\nif [ -x ${shellQuote(backup)} ]; then exec ${shellQuote(backup)} "$@"; fi\n`;
135
158
  const temp = `${hook}.${process.pid}.tmp`;
136
159
  writeFileSync(temp, script, { mode: 0o755 });
137
160
  renameSync(temp, hook);
@@ -155,10 +178,12 @@ export function landingVerdict(policy, { action = "land", review = null, tip = n
155
178
  return { allowed: true };
156
179
  }
157
180
 
158
- export function referenceVerdict(repo, phase, env = process.env) {
181
+ export function referenceVerdict(repo, phase, env = process.env, updates = "") {
159
182
  if (phase !== "prepared" || !(env.TRANTOR_AGENT_IDENTITY || env.RELAY_SESSION)) return { allowed: true };
160
183
  if (checkoutRole(repo) !== "operator") return { allowed: true };
161
- const policy = cachedGitPolicy(repo);
184
+ const refs = updates.trim().split("\n");
185
+ if (updates.trim() && refs.every(line => /^[0-9a-f]+ [0-9a-f]+ refs\/remotes\/\S+$/.test(line))) return { allowed: true };
186
+ const policy = hookGitPolicy(repo);
162
187
  if (policy.effective.land === "click") return landingVerdict(policy);
163
188
  return { allowed: true };
164
189
  }
@@ -167,8 +192,12 @@ async function main() {
167
192
  const [command, phase] = process.argv.slice(2);
168
193
  const repo = process.cwd();
169
194
  if (command === "hook") {
170
- const result = referenceVerdict(repo, phase);
195
+ const result = referenceVerdict(repo, phase, process.env, readFileSync(0, "utf8"));
171
196
  if (!result.allowed) { console.error(result.reason); process.exitCode = 1; }
197
+ } else if (command === "refresh-hook") {
198
+ const project = phase;
199
+ const policy = await readGitPolicy({ hub: resolveHub(project), project, identity: ownerIdentity() });
200
+ console.log(JSON.stringify(policy));
172
201
  } else if (command === "refresh") {
173
202
  const project = resolveProject(repo);
174
203
  const policy = await readGitPolicy({ hub: resolveHub(project), project, identity: ownerIdentity() });
@@ -141,17 +141,25 @@ CREATE TABLE IF NOT EXISTS peers (
141
141
  -- 'orch', 'genesis', 'tool'. The overseer's crew
142
142
  -- exemption reads it (#6075/#6148), so when a restart
143
143
  -- forgot it the hub warned about its own crew.
144
+ machine TEXT,
145
+ llm TEXT,
146
+ model TEXT,
147
+ account_identity JSONB,
144
148
  PRIMARY KEY (org_id, session)
145
149
  );
146
- -- additive migration for hubs whose peers table predates the kind column (#6170)
150
+ -- additive migrations for hubs whose peers table predates these columns
147
151
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS kind TEXT;
152
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS machine TEXT;
153
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS llm TEXT;
154
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS model TEXT;
155
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS account_identity JSONB;
148
156
  -- DELIBERATELY no CHECK on peers.kind, unlike identities.kind above. The hub accepts whatever a
149
157
  -- client stamps (hub.mjs /register takes any string up to 40 chars) and the vocabulary grows with
150
158
  -- the product — 'genesis' arrived in #6068, 'orch' in #6075. #6169 is the cost of getting this
151
159
  -- wrong in the other direction: a CHECK narrower than the values in flight poisoned every persist
152
160
  -- delta for 13 minutes. A column that stores what it is given cannot fail that way.
153
161
 
154
- -- The fields that currently ride in-memory and are LOST on restart. This is the debt being paid.
162
+ -- State projections without dedicated columns ride in kv so they survive restart.
155
163
  CREATE TABLE IF NOT EXISTS kv (
156
164
  org_id TEXT NOT NULL,
157
165
  key TEXT NOT NULL, -- 'verifyGates'|'balances'|'handoffLog'|'aliases'|'phaseMeta'|'focus'|'projectMeta'|'lessons'|'orgPolicy'|'meta'|'contractReap'
package/lib/store-pg.mjs CHANGED
@@ -162,6 +162,10 @@ function peerFromRow(row) {
162
162
  online: !!row.online,
163
163
  deliveredUpTo: row.delivered_up_to == null ? 0 : Number(row.delivered_up_to),
164
164
  kind: row.kind || "", // #6170: survives the restart that used to forget who was crew
165
+ machine: row.machine || "",
166
+ llm: row.llm || "",
167
+ model: row.model || "",
168
+ accountIdentity: row.account_identity || null,
165
169
  };
166
170
  }
167
171
 
@@ -469,8 +473,8 @@ export class PgStore {
469
473
  async touchPeer(orgId, session, patch = {}) {
470
474
  if (!session || session === "all") return;
471
475
  await this.pool.query(
472
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind)
473
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
476
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
477
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
474
478
  ON CONFLICT(org_id, session) DO UPDATE SET
475
479
  pubkey=COALESCE(EXCLUDED.pubkey, peers.pubkey),
476
480
  project=COALESCE(NULLIF(EXCLUDED.project,''), peers.project),
@@ -483,12 +487,17 @@ export class PgStore {
483
487
  -- (the MCP one only learns it under TRANTOR_ORCH), and plain last_seen refreshes are the
484
488
  -- majority of writes here — overwriting on every one is how the orchestrator kept
485
489
  -- reverting to a nameless agent between registrations.
486
- kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind)`,
490
+ kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind),
491
+ machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
492
+ llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
493
+ model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
494
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
487
495
  [
488
496
  session, orgId, patch.pubkey || null, patch.project || "", patch.status ?? null,
489
497
  patch.hookVersion || patch.hook_version || "", ms(patch.lastSeen || patch.last_seen),
490
498
  patch.online ?? true, Number(patch.deliveredUpTo || patch.delivered_up_to || 0),
491
- patch.kind || "",
499
+ patch.kind || "", patch.machine || "", patch.llm || "", patch.model || "",
500
+ patch.accountIdentity ? JSON.stringify(patch.accountIdentity) : null,
492
501
  ],
493
502
  );
494
503
  }
@@ -618,15 +627,19 @@ export class PgStore {
618
627
  );
619
628
  for (const [session, p] of Object.entries(state.peers || {})) {
620
629
  await c.query(
621
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind)
622
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
630
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
631
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
623
632
  ON CONFLICT(org_id, session) DO UPDATE SET pubkey=EXCLUDED.pubkey, project=EXCLUDED.project, status=EXCLUDED.status,
624
633
  hook_version=EXCLUDED.hook_version, last_seen=EXCLUDED.last_seen, online=EXCLUDED.online, delivered_up_to=GREATEST(peers.delivered_up_to, EXCLUDED.delivered_up_to),
625
634
  -- #6170: same non-demoting rule as touchPeer. A snapshot is written from MEMORY, and
626
635
  -- memory is exactly where the kind was being lost, so a blank in the snapshot means
627
636
  -- "not known right now", never "this peer is nothing".
628
- kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind)`,
629
- [session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || ""],
637
+ kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind),
638
+ machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
639
+ llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
640
+ model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
641
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
642
+ [session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null],
630
643
  );
631
644
  }
632
645
  await c.query(
@@ -759,15 +772,19 @@ export class PgStore {
759
772
  for (const raw of peers.upserts) {
760
773
  const p = stripNulDeep(raw);
761
774
  await c.query(
762
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind)
763
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
775
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
776
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
764
777
  ON CONFLICT(org_id, session) DO UPDATE SET pubkey=EXCLUDED.pubkey, project=EXCLUDED.project, status=EXCLUDED.status,
765
778
  hook_version=EXCLUDED.hook_version, last_seen=EXCLUDED.last_seen, online=EXCLUDED.online, delivered_up_to=GREATEST(peers.delivered_up_to, EXCLUDED.delivered_up_to),
766
779
  -- #6170: THIS is the path a running hub actually persists through — saveDelta on the
767
780
  -- persist tick, not touchPeer or saveSnapshot. Adding the column to the other two and
768
781
  -- not this one is why the first live restart still came back with empty kinds.
769
- kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind)`,
770
- [p.session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || ""],
782
+ kind=COALESCE(NULLIF(EXCLUDED.kind,''), peers.kind),
783
+ machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
784
+ llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
785
+ model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
786
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
787
+ [p.session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null],
771
788
  );
772
789
  }
773
790
  if (peers.deletes.length) await c.query("DELETE FROM peers WHERE org_id=$1 AND session = ANY($2::text[])", [orgId, peers.deletes]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.152",
3
+ "version": "0.18.154",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"