trantor 0.18.157 → 0.18.160

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.157"
9
+ "version": "0.18.160"
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.157",
16
+ "version": "0.18.160",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.157",
3
+ "version": "0.18.160",
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": {
package/bin/crew/open.mjs CHANGED
@@ -122,12 +122,16 @@ function orchestratorCommand(ctx, id) {
122
122
  return `${env} claude${harnessFlag(ctx)} ${action}`;
123
123
  }
124
124
 
125
- function reportOrchestrator(ctx, pane, id) {
125
+ export function orchestratorResumeArgv(ctx, id) {
126
126
  const resumeArgv = ["env", ...STRIP.flatMap(name => ["-u", name]), `TRANTOR_ORCH=${ctx.project}`, "claude"];
127
127
  // #14563: the reported resume argv must be the SAME command the pane runs, dial included.
128
128
  resumeArgv.push(...harnessFlag(ctx).trim().split(" "));
129
129
  resumeArgv.push("--resume", id);
130
- reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv });
130
+ return resumeArgv;
131
+ }
132
+
133
+ function reportOrchestrator(ctx, pane, id) {
134
+ reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv: orchestratorResumeArgv(ctx, id) });
131
135
  }
132
136
 
133
137
  export function paneHasAgent(ctx, pane) {
@@ -2,6 +2,7 @@
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
4
  import { resolveKeys } from "../lib/provider-keys.mjs";
5
+ import { CREW_ADAPTER_VERSION } from "../lib/dispatcher/harness/contract.mjs";
5
6
  import { runnerAccountIdentity } from "../lib/dispatcher/accounts.mjs";
6
7
  import { execSync, spawnSync, spawn } from "node:child_process";
7
8
  import { randomUUID } from "node:crypto";
@@ -502,7 +503,7 @@ async function reportFailure(exit, trigger, undelivered = 0, reasonOverride = ""
502
503
  const reason = reasonOverride || classify(exit);
503
504
  const down = consecFails >= 2;
504
505
  const status = down ? `down: ${reason} · ${consecFails} fails` : `errored: ${reason}`;
505
- await api("/register", { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
506
+ await api("/register", { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
506
507
  const hint = reason === "exhausted" ? " — needs `trantor swap`"
507
508
  : reason === "stalled" ? " — CLI silent for the whole watchdog window: check the provider, or `trantor swap`"
508
509
  : reason === "auth" ? " — check credentials"
@@ -701,6 +702,7 @@ async function registerStatus(status, extra = {}) {
701
702
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
702
703
  payload.machine = MACHINE_LABEL;
703
704
  payload.accountIdentity = cachedAccountIdentity;
705
+ payload.adapterVersion = CREW_ADAPTER_VERSION;
704
706
  const body = JSON.stringify(payload);
705
707
  try {
706
708
  const opts = { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body };
@@ -762,7 +764,7 @@ async function reportHealthy() {
762
764
  // Recovery is a change too, so the next failure is news again — a park included.
763
765
  announced = "";
764
766
  parkAnnounced = false;
765
- await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
767
+ await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
766
768
  // #13949: a landing that ended a park already said "recovered" once, with the reason and the
767
769
  // duration — the ladder's echo would be the second recovery message for one event.
768
770
  if (!saidParkRecovered) await api("/send", { from: SESSION, to: "all", text: `✅ ${SESSION} recovered`, project: PROJ, kind: "status" }).catch(() => {});
@@ -1066,6 +1068,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
1066
1068
  agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
1067
1069
  presencePayload.machine = MACHINE_LABEL;
1068
1070
  presencePayload.accountIdentity = cachedAccountIdentity;
1071
+ presencePayload.adapterVersion = CREW_ADAPTER_VERSION;
1069
1072
  writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
1070
1073
  presence: { intervalMs: PRESENCE_MS, payload: presencePayload },
1071
1074
  worktree: { cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: presencePayload.machine } }));
@@ -1664,7 +1667,7 @@ async function resolveWakeCard(messages, { session }) {
1664
1667
  // session is — the overseer's declared-crew exemption reads it, and on the remote hub there is
1665
1668
  // no crew-windows.txt to fall back to. /register preserves absent fields, so a seat running an
1666
1669
  // older runner never loses a kind an updated one stamped.
1667
- await api("/register", { session: SESSION, project: PROJ, status: "crew member booting", persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
1670
+ await api("/register", { session: SESSION, project: PROJ, status: "crew member booting", persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
1668
1671
  // Announce runner-side, signed as THIS seat: the runner process is per-seat by construction, so
1669
1672
  // its signature cannot be borrowed the way a shared opencode MCP daemon once borrowed identities.
1670
1673
  try {
package/bin/dispatch.mjs CHANGED
@@ -11,6 +11,10 @@ import {
11
11
  } from "../lib/dispatcher/preflight.mjs";
12
12
 
13
13
  const args = process.argv.slice(2);
14
+ if (args[0] === 'policy' && args[1] === 'draft') {
15
+ const { runPolicyDraft } = await import('./policy-draft.mjs');
16
+ process.exit(await runPolicyDraft(args.slice(2)));
17
+ }
14
18
  const asJson = args.includes("--json");
15
19
  const flag = (name) => { const i = args.indexOf(name); return i > -1 ? args[i + 1] : null; };
16
20
  const flags = (name) => args.flatMap((a, i) => (a === name ? [args[i + 1]] : []));
package/bin/duty.mjs CHANGED
@@ -15,7 +15,7 @@
15
15
  // same crew-runner as crew seats, with a triage doctrine instead of "work your card".
16
16
  import { spawn, execSync, execFileSync } from "node:child_process";
17
17
  import { readFileSync, writeFileSync, existsSync, mkdirSync, openSync, rmSync, unlinkSync } from "node:fs";
18
- import { join, dirname } from "node:path";
18
+ import { join, dirname, resolve } from "node:path";
19
19
  import { homedir } from "node:os";
20
20
  import { fileURLToPath } from "node:url";
21
21
  import { loadOrCreate } from "../lib/identity.mjs";
@@ -32,6 +32,7 @@ const DUTY_LABEL = "com.trantor.duty";
32
32
  const DUTY_PLIST = join(homedir(), "Library", "LaunchAgents", `${DUTY_LABEL}.plist`);
33
33
 
34
34
  const argv = process.argv.slice(2);
35
+ const IS_MAIN = process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1]);
35
36
  const cmd = argv[0] || "status";
36
37
  const val = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 ? (argv[i + 1] || d) : d; };
37
38
 
@@ -170,10 +171,15 @@ function keepalivePlistBody() {
170
171
  // a command line. Single-quote every value so bash 3.2 treats them literally. #14646: the node is
171
172
  // resolved at EXEC time (command -v node against the PATH exported above) — a pinned execPath is
172
173
  // a versioned Homebrew Cellar path that `brew upgrade node` deletes out from under launchd.
173
- function writeLauncher(env) {
174
+ export function launcherBody(env) {
174
175
  const shquote = (v) => `'${String(v).replace(/'/g, `'\\''`)}'`;
175
176
  const exports = Object.entries(env).map(([k, v]) => `export ${k}=${shquote(v)}`).join("\n");
176
- writeFileSync(LAUNCHER, `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\n${nodeResolverSnippet()}\nexec "$NODE_BIN" ${shquote(join(ROOT, "bin", "crew-runner.mjs"))} ${shquote(AGENT)} ${shquote(DIR)}\n`, { mode: 0o700 });
177
+ // #14774: launchd reruns this script; $$ remains the runner's pid across exec.
178
+ return `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\n${nodeResolverSnippet()}\nprintf '%s\\n' "$$" > ${shquote(PIDF)}\nexec "$NODE_BIN" ${shquote(join(ROOT, "bin", "crew-runner.mjs"))} ${shquote(AGENT)} ${shquote(DIR)}\n`;
179
+ }
180
+
181
+ function writeLauncher(env) {
182
+ writeFileSync(LAUNCHER, launcherBody(env), { mode: 0o700 });
177
183
  }
178
184
 
179
185
  // The old headless start: a detached child of whoever ran `up`. No keepalive — it dies with a
@@ -218,7 +224,7 @@ function closeDutyWorkspace() {
218
224
  return closed;
219
225
  }
220
226
 
221
- if (cmd === "up") {
227
+ if (IS_MAIN && cmd === "up") {
222
228
  const hub = fleetHub();
223
229
  mkdirSync(DIR, { recursive: true });
224
230
  const prior = alivePid();
@@ -309,7 +315,7 @@ if (cmd === "up") {
309
315
  process.exit(0); // the seat IS up; a hub that won't feed it is a warning, not a failed start
310
316
  }
311
317
 
312
- if (cmd === "down") {
318
+ if (IS_MAIN && cmd === "down") {
313
319
  const hadKeepalive = existsSync(DUTY_PLIST);
314
320
  // Unload the keepalive FIRST (bootout kills the job's process), then remove the plist so a
315
321
  // reboot cannot resurrect the seat behind a `down`. `up` rewrites both.
@@ -361,7 +367,7 @@ function dutyHealth() {
361
367
  }
362
368
 
363
369
  // status
364
- {
370
+ if (IS_MAIN) {
365
371
  const pid = alivePid();
366
372
  // Lead with what it IS. Someone running this because an unexplained window appeared should not
367
373
  // have to read source to find out what started on their machine.
@@ -14,12 +14,14 @@ const PLIST = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
14
14
  const LOG = "/tmp/trantor-herdr-server.log";
15
15
  const RESTORE_LOG = "/tmp/trantor-herdr-restore.log";
16
16
  const RESTORE_SCRIPT = join(homedir(), "Library", "LaunchAgents", "trantor-herdr-restore.sh");
17
+ const LAUNCHCTL = process.env.TRANTOR_LAUNCHCTL_BIN || "/bin/launchctl";
17
18
  const D = "\x1b[2m", R = "\x1b[0m";
18
19
 
19
20
  const shellQuote = value => `'${String(value).replaceAll("'", `'\\''`)}'`;
20
21
  const xmlEscape = value => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
21
22
 
22
23
  export function herdrBin() {
24
+ if (process.env.TRANTOR_HERDR_BIN) return process.env.TRANTOR_HERDR_BIN;
23
25
  // launchd runs with a minimal PATH, so the absolute path has to be baked in at install time.
24
26
  for (const p of [join(homedir(), ".local/bin/herdr"), "/opt/homebrew/bin/herdr", "/usr/local/bin/herdr"]) {
25
27
  if (existsSync(p)) return p;
@@ -131,25 +133,32 @@ if (cmd === "install") {
131
133
  writeFileSync(RESTORE_SCRIPT, restoreScriptBody({ herdr: bin }));
132
134
  chmodSync(RESTORE_SCRIPT, 0o755);
133
135
  writeFileSync(PLIST, plistBody(bin));
134
- // bootout first so a re-install replaces rather than stacks
135
- try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
136
- try {
137
- execFileSync("/bin/launchctl", ["bootstrap", `gui/${uid}`, PLIST], { stdio: "ignore" });
138
- } catch (e) {
139
- console.error(`wrote ${PLIST} but launchctl bootstrap failed: ${e?.message || e}`);
140
- process.exit(1);
136
+ let running = false;
137
+ try { running = /status:\s*running/.test(execFileSync(bin, ["status"], { encoding: "utf8" })); } catch { /* server down */ }
138
+ if (running) {
139
+ // #14774: this launchd job IS the running server; booting it out kills every restored pane.
140
+ console.log("herdr is already running; left the server and every pane alive — the updated plist takes effect at next login");
141
+ } else {
142
+ // bootout first so a re-install replaces rather than stacks
143
+ try { execFileSync(LAUNCHCTL, ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
144
+ try {
145
+ execFileSync(LAUNCHCTL, ["bootstrap", `gui/${uid}`, PLIST], { stdio: "ignore" });
146
+ } catch (e) {
147
+ console.error(`wrote ${PLIST} but launchctl bootstrap failed: ${e?.message || e}`);
148
+ process.exit(1);
149
+ }
141
150
  }
142
151
  console.log(`herdr's server now starts at login (${bin} server)`);
143
152
  console.log(`${D}plist: ${PLIST} log: ${LOG} restore log: ${RESTORE_LOG}${R}`);
144
153
  } else if (cmd === "remove") {
145
- try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
154
+ try { execFileSync(LAUNCHCTL, ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
146
155
  if (existsSync(PLIST)) { unlinkSync(PLIST); console.log("removed the herdr login agent"); }
147
156
  else console.log("no herdr login agent installed");
148
157
  } else if (cmd === "status") {
149
158
  const installed = existsSync(PLIST);
150
159
  let loaded = false;
151
160
  try {
152
- loaded = execFileSync("/bin/launchctl", ["list"], { encoding: "utf8" }).split("\n").some(l => l.includes(LABEL));
161
+ loaded = execFileSync(LAUNCHCTL, ["list"], { encoding: "utf8" }).split("\n").some(l => l.includes(LABEL));
153
162
  } catch { /* launchctl unavailable */ }
154
163
  let running = false;
155
164
  try { running = /status:\s*running/.test(execFileSync(herdrBin() || "herdr", ["status"], { encoding: "utf8" })); } catch { /* server down */ }
package/bin/patrol.mjs CHANGED
@@ -88,7 +88,7 @@ export function buildPatrolReport(rawInventory = {}, reaped = [], { bus = busDir
88
88
  orphans.push({ type: "live-runner-without-row", project: p, agent: runner.agent, pid: runner.pid, dir: runner.dir });
89
89
  }
90
90
  // #13474: the same rule the runner refuses a turn on.
91
- const mm = providerMismatch(String(runner?.agent || ""), runner?.model);
91
+ const mm = providerMismatch(String(runner?.agent || ""), runner?.model, runner?.modelSource);
92
92
  if (mm) {
93
93
  warnings.push({
94
94
  type: "seat-model-provider-mismatch",
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { pathToFileURL } from 'node:url';
3
+ import { signedPost, sessionContext } from '../hooks/lib/api.mjs';
4
+
5
+ export async function runPolicyDraft(args, { post = signedPost, context = sessionContext,
6
+ print = console.log, report = console.error } = {}) {
7
+ if (args.includes('--help')) {
8
+ print('trantor dispatch policy draft [--project <project>] [--version <new-version>] [--json]\nPrints the full policy JSON; summary goes to stderr. --json prints {policy,summary}. Does not activate.');
9
+ return 0;
10
+ }
11
+ const values = {};
12
+ for (let index = 0; index < args.length; index++) {
13
+ const arg = args[index];
14
+ if (arg === '--json') continue;
15
+ if (!['--project', '--version'].includes(arg) || !args[index + 1] || args[index + 1].startsWith('--')) {
16
+ report(`Invalid policy draft option: ${arg}`);
17
+ return 2;
18
+ }
19
+ values[arg.slice(2)] = args[++index];
20
+ }
21
+ const project = values.project || context().project;
22
+ if (!project) { report('Policy draft requires --project.'); return 2; }
23
+ const request = { project };
24
+ if (values.version) request.version = values.version;
25
+ const response = await post('/dispatcher/policy/draft', request,
26
+ { project, timeoutMs: 30_000 });
27
+ if (!response.ok) {
28
+ report(`Policy draft failed: ${response.json?.code || response.reason || `HTTP ${response.status}`}`);
29
+ return 1;
30
+ }
31
+ const { policy, summary } = response.json;
32
+ print(JSON.stringify(args.includes('--json') ? response.json : policy, null, 2));
33
+ report(`Draft ${policy.version} (parent ${summary.parentVersion}): ${summary.rosterEntries} bound seats, ${summary.priorsDerived} priors from ${summary.rowsRead} history rows.`);
34
+ report(JSON.stringify(summary, null, 2));
35
+ return 0;
36
+ }
37
+
38
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
39
+ process.exitCode = await runPolicyDraft(process.argv.slice(2));
40
+ }
@@ -13,6 +13,7 @@ const HERE = dirname(fileURLToPath(import.meta.url)); // <pkg>/hooks/
13
13
  const PKGROOT = join(HERE, "..", "..");
14
14
  const CMUX_APP_BIN = "/Applications/cmux.app/Contents/Resources/bin/cmux";
15
15
  const TIMEOUT = 2000; // contract: every subprocess ≤2s
16
+ const OPENCODE_BACKED = new Set(["glm", "deepseek", "qwen", "openrouter", "dsh", "opencode"]);
16
17
 
17
18
  const busDir = () => process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus");
18
19
 
@@ -97,8 +98,10 @@ export function liveRunners(project = null) {
97
98
  // never return the rest of `ps eww`, which can contain provider credentials.
98
99
  const envLine = run("ps", ["eww", "-p", String(pid), "-o", "command="]);
99
100
  const pinnedModel = (envLine.match(/(?:^|\s)CREW_MODEL=([^\s]*)/) || [])[1] || "";
100
- const model = pinnedModel || globalModel;
101
- const modelSource = pinnedModel ? "crew" : (globalModel ? "opencode-global" : "");
101
+ const base = agent.split(":").pop().replace(/-\d+$/, "");
102
+ const defaultModel = OPENCODE_BACKED.has(base) ? globalModel : "";
103
+ const model = pinnedModel || defaultModel;
104
+ const modelSource = pinnedModel ? "crew" : (defaultModel ? "opencode-global" : "cli-default");
102
105
  out.push({ pid, agent, dir, model, modelSource });
103
106
  }
104
107
  return out;
@@ -5,7 +5,7 @@
5
5
  import { readFileSync, existsSync, appendFileSync } from "node:fs";
6
6
  import { join, basename, dirname } from "node:path";
7
7
  import { homedir, hostname } from "node:os";
8
- import { execSync, spawn } from "node:child_process";
8
+ import { execSync, spawn, spawnSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, readConfig as readBusConfig, handoffDir, readOrchSession, writeOrchSession, busDirFor } from "../lib/project.mjs";
11
11
  import { formatSubagentManifest } from "../lib/subagent-manifest.mjs";
@@ -21,6 +21,8 @@ import { HUB_DOWN_LINE, loopbackUrl, shouldWarnUnpinned, wantsBuildDoctrine } fr
21
21
  import { memoryStartLine } from "./lib/memory-start.mjs";
22
22
  import { staleResumeLine } from "./lib/cc-signals.mjs";
23
23
  import { machineLabel } from "../lib/machine-label.mjs";
24
+ import { reportHerdrSessionResume } from "../lib/herdr-integration.mjs";
25
+ import { orchestratorResumeArgv } from "../bin/crew/open.mjs";
24
26
 
25
27
  // The build doctrine (docs/BUILD-DOCTRINE.md) in short form, one line per rule, injected for every
26
28
  // project's ORCHESTRATOR at boot (#6452): orchestrators that never opened the doc missed the ruling.
@@ -48,6 +50,22 @@ function buildDoctrineShortForm() {
48
50
 
49
51
  function nowSec() { try { return Number(execSync("date +%s", { encoding: "utf8" }).trim()) || 0; } catch { return 0; } }
50
52
 
53
+ async function reportRestoredHerdrSession({ source, project, sessionId, transcriptPath, isOrchPane, isPrintRun }) {
54
+ const pane = process.env.HERDR_PANE_ID || "";
55
+ if (source !== "startup" || !isOrchPane || isPrintRun || !sessionId || !process.env.HERDR_ENV || !pane) return;
56
+ try {
57
+ const listed = spawnSync("herdr", ["agent", "list"], { encoding: "utf8", timeout: 1500 });
58
+ if (listed.status !== 0) return;
59
+ const agents = JSON.parse(listed.stdout || "{}")?.result?.agents;
60
+ const restored = Array.isArray(agents) && agents.find(a => a?.pane_id === pane)?.agent_session?.value;
61
+ if (!restored || restored === sessionId) return;
62
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
63
+ const resumeArgv = orchestratorResumeArgv({ root, project, env: process.env }, sessionId);
64
+ const reported = await reportHerdrSessionResume({ pane, sessionId, transcriptPath, resumeArgv });
65
+ if (reported) process.stderr.write(`[trantor] restored herdr pane ${pane} now follows session ${sessionId}\n`);
66
+ } catch {}
67
+ }
68
+
51
69
  function readStdin() {
52
70
  return new Promise(res => { let d = ""; process.stdin.setEncoding("utf8");
53
71
  process.stdin.on("data", c => (d += c)); process.stdin.on("end", () => res(d));
@@ -448,6 +466,8 @@ try {
448
466
  const isPrintRun = String(process.env.CLAUDE_CODE_ENTRYPOINT || "cli").startsWith("sdk-");
449
467
  const orchEnv = process.env.TRANTOR_ORCH || "";
450
468
  const isOrchPane = !!orchEnv && (orchEnv === "1" || orchEnv === project); // project-matched: a child claude in another dir must not inherit the badge
469
+ await reportRestoredHerdrSession({ source, project, sessionId: String(stdinObj.session_id || ""),
470
+ transcriptPath: String(stdinObj.transcript_path || ""), isOrchPane, isPrintRun });
451
471
  const orchSid = readOrchSession(project);
452
472
  const holdMs = Number(process.env.TRANTOR_ORCH_HOLD_MS || 30 * 60 * 1000);
453
473
  const peek = loadPendingHandoff(basename(projectDir), { claim: false });
@@ -70,6 +70,10 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
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
71
  // Hooks and MCP beats share the runner's session name; only the runner may rotate or clear its account binding.
72
72
  const fromRunner = typeof b.persona === "string" && b.persona.length > 0 && typeof b.agent === "string" && b.agent.length > 0;
73
+ if (pr && fromRunner && typeof b.adapterVersion === 'string' && /^[a-zA-Z0-9._-]{1,80}$/.test(b.adapterVersion)) {
74
+ pr.adapterVersion = b.adapterVersion;
75
+ markDirty();
76
+ }
73
77
  if (pr && fromRunner && Object.hasOwn(b, 'accountIdentity')) {
74
78
  const identity = b.accountIdentity;
75
79
  const provider = typeof identity?.provider === "string" && /^[a-z0-9-]{1,60}$/.test(identity.provider) ? identity.provider : 'unknown';
@@ -361,7 +365,7 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
361
365
  return json(res, 200, { hubVersion: HUB_VERSION, authMode: AUTH_MODE, peers: peerRows.map(([s, v]) => ({ session: s, lastSeen: v.lastSeen, online: v.lastSeen > cutoff, status: v.status || "", health: healthOf(v.status), project: v.project || "", phase: v.phase || "", phaseSince: v.phaseSince || 0,
362
366
  pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "",
363
367
  kind: peerKindOf(v), // #8723 bounce-3: same resolver declaredCrewFor reads — never a roster-only answer
364
- llm: v.llm || "", model: v.model || "", machine: v.machine || undefined, hookVersion: v.hookVersion || "", staleHooks: !!(v.lastSeen > cutoff && v.hookVersion && HUB_VERSION && cmpSemver(v.hookVersion, HUB_VERSION) < 0) })) });
368
+ llm: v.llm || "", model: v.model || "", machine: v.machine || undefined, adapterVersion: v.adapterVersion || null, hookVersion: v.hookVersion || "", staleHooks: !!(v.lastSeen > cutoff && v.hookVersion && HUB_VERSION && cmpSemver(v.hookVersion, HUB_VERSION) < 0) })) });
365
369
  }
366
370
  // --- Provider balances (prepaid credit) ---
367
371
  // The hub runs under launchd with no provider keys, so it can't fetch balances itself. Env-having
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { reject } from '../../lib/dispatcher/admission.mjs';
3
3
  import { requireRole } from '../../lib/dispatcher/operations.mjs';
4
+ import { draftPolicyFromStore } from '../../lib/dispatcher/policy-draft.mjs';
4
5
 
5
6
  export function dispatcherEndpoint(method, path, query) {
6
7
  return path === '/dispatch' || path.startsWith('/dispatch/') || path.startsWith('/dispatcher/')
@@ -71,9 +72,15 @@ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
71
72
  if (req.method === 'POST' && P === '/dispatcher/bridge-grants') {
72
73
  return ctx.json(res, 200, await service.registerBridgeGrant(orgId, await ctx.body(req), actor));
73
74
  }
75
+ if (req.method === 'POST' && P === '/dispatcher/shadow-grants') {
76
+ return ctx.json(res, 200, await service.registerShadowGrant(orgId, await ctx.body(req), actor));
77
+ }
74
78
  if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
75
79
  return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
76
80
  }
81
+ if (req.method === 'POST' && P === '/dispatcher/policy/draft') {
82
+ return ctx.json(res, 200, await draftPolicyFromStore({ service, orgId, input: await ctx.body(req), actor, requireRole }));
83
+ }
77
84
  if (req.method === 'POST' && P === '/dispatcher/control') {
78
85
  return ctx.json(res, 200, await service.executor.kill(orgId, await ctx.body(req), actor));
79
86
  }
package/hub/store.mjs CHANGED
@@ -154,7 +154,7 @@ function normalizeState(loaded = {}) {
154
154
  s.peers[session] = typeof v === "number"
155
155
  ? { lastSeen: v, status: "", project: "" }
156
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 };
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, adapterVersion: v.adapterVersion || null, gitRoot: v.gitRoot || loaded.overseerState?.roots?.[session] || "", deliveredUpTo: v.deliveredUpTo || v.delivered_up_to || 0, _on: v._on === true || v.online === true };
158
158
  }
159
159
  return s;
160
160
  }
@@ -450,10 +450,16 @@ setInterval(persist, persistTickMs).unref?.();
450
450
  machines: () => machineHealthRows(Date.now()),
451
451
  seats: () => {
452
452
  const nowMs = Date.now();
453
+ const lastRows = turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 });
453
454
  return seatsView({ peers: state.peers, messages: state.messages, nowMs,
454
- onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000),
455
- lastRows: turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 }) })
456
- .map(seat => ({ ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity }));
455
+ onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000), lastRows })
456
+ .map(seat => {
457
+ const turn = lastRows.find(row => `${row.persona}:${row.project}` === seat.session && row.ts === seat.lastTurn?.ts);
458
+ return { ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity,
459
+ adapterVersion: state.peers[seat.session]?.adapterVersion,
460
+ lastTurn: seat.lastTurn ? { ...seat.lastTurn, attemptId: turn?.executionAttemptId ?? turn?.attempt?.id ?? null,
461
+ effort: turn?.attempt?.effort ?? 'default' } : null };
462
+ });
457
463
  },
458
464
  discovery: () => {
459
465
  if (!discovery || Date.now() - discoveryAt >= CACHE_TTL_MS) {
package/hub.mjs CHANGED
@@ -143,6 +143,7 @@ const context = {
143
143
  };
144
144
  if (store.dispatcher && AUTH_MODE !== 'off') {
145
145
  setInterval(createDispatcherTick({ dispatcher: store.dispatcher }), 1000).unref();
146
+ setInterval(() => store.dispatcher.tickShadow(), 1000).unref();
146
147
  }
147
148
  const sessionChat = createSessionRuntime({
148
149
  state: store.state, markDirty: store.markDirty,
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.157",
3
+ "version": "0.18.160",
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",
@@ -1,3 +1,4 @@
1
+ import { z } from 'zod';
1
2
  import { bindAccounts, resolveSeatAccount } from './accounts.mjs';
2
3
  import { canonicalHash } from './snapshot.mjs';
3
4
  import { heldLiability } from './spend.mjs';
@@ -136,6 +137,17 @@ function activeSeats(seats, id) {
136
137
  return seats.filter(seat => seat?.online && text(seat.machine, 60).toLowerCase() === id.toLowerCase()).length;
137
138
  }
138
139
 
140
+ const AdapterVersionSchema = z.string().regex(/^[a-zA-Z0-9._-]{1,80}$/);
141
+ function reportedAdapters(seats, machine, nowMs, policy) {
142
+ return [...new Set(seats.filter(seat => seat.kind === 'agent' && seat.online === true
143
+ && text(seat.machine, 60).toLowerCase() === machine.toLowerCase()
144
+ && fresh(timestamp(seat.lastSeen), nowMs, policy.machineTtlMs))
145
+ .flatMap(seat => {
146
+ const version = AdapterVersionSchema.safeParse(seat.adapterVersion);
147
+ return version.success ? [version.data] : [];
148
+ }))].sort();
149
+ }
150
+
139
151
  function machineEvidence({ rows, seats, nowMs, policy }) {
140
152
  const evidence = [];
141
153
  const emitted = new Set();
@@ -159,7 +171,7 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
159
171
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
160
172
  record: { id, health: observation({ value: health, observedAtMs, receivedAtMs: nowMs,
161
173
  source: 'machine-beats', status: 'ok', sourceRevision: observedAtMs }),
162
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
174
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
163
175
  }
164
176
  for (const seat of seats) {
165
177
  const id = text(seat?.machine, 60);
@@ -172,7 +184,7 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
172
184
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
173
185
  record: { id, health: observation({ value: null, observedAtMs, receivedAtMs: nowMs,
174
186
  source: 'presence', status: 'unknown', reason: 'no fresh machine health beat', sourceRevision: observedAtMs }),
175
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
187
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
176
188
  }
177
189
  return evidence;
178
190
  }
@@ -189,13 +201,13 @@ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
189
201
  if (row?.kind !== 'agent') continue;
190
202
  const id = text(row?.session, 200);
191
203
  const machine = text(row?.machine, 60);
192
- const harness = text(row?.llm, 200);
204
+ const agent = text(row?.llm, 200);
193
205
  const observedAtMs = timestamp(row?.lastSeen);
194
- if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
206
+ if (!id || !machine || !agent || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
195
207
  const lastTurnMs = timestamp(row?.lastTurn?.ts);
196
208
  const binding = resolveSeatAccount({ identity: row.accountIdentity, accounts });
197
209
  const record = { id, machine, accountId: binding.accountId, accountBindingReason: binding.reason,
198
- harness, model: text(row.model, 512) || null,
210
+ harness: 'crew', agent, model: text(row.model, 512) || null,
199
211
  busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
200
212
  lastBeatMs: observedAtMs, lastTurnMs };
201
213
  if (row.project) record.project = text(row.project, 200);
@@ -242,16 +254,17 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
242
254
  }
243
255
  }
244
256
  for (const seat of Array.isArray(seats) ? seats : []) {
257
+ if (seat?.kind !== 'agent') continue;
245
258
  const model = text(seat?.lastTurn?.model, 512);
246
259
  const seatId = text(seat?.session, 200);
247
- const harness = text(seat?.llm, 200);
260
+ const agent = text(seat?.llm, 200);
248
261
  const observedAtMs = timestamp(seat?.lastTurn?.ts);
249
- if (!model || !seatId || !harness || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
250
- const provider = model.includes('/') ? text(model.split('/')[0], 200) : harness;
262
+ if (!model || !seatId || !agent || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
263
+ const provider = model.includes('/') ? text(model.split('/')[0], 200) : agent;
251
264
  const key = `${provider}\0${model}`;
252
265
  const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
253
266
  expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
254
- envelope.record.invocation = observation({ value: { model, seatId, harness }, observedAtMs,
267
+ envelope.record.invocation = observation({ value: { model, seatId, harness: 'crew' }, observedAtMs,
255
268
  receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
256
269
  envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
257
270
  envelope.expiresAtMs = Math.max(envelope.expiresAtMs, observedAtMs + policy.invocationTtlMs);
@@ -264,11 +277,29 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
264
277
  export function buildEvidence({ balances = [], machines = [], seats = [], discovery = [], orgId, nowMs,
265
278
  policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
266
279
  const presentSeats = presenceMachines({ rows: machines, seats });
280
+ const accounts = balanceEvidence({ snapshots: balances, orgId, nowMs, policy });
281
+ const boundSeats = seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy });
282
+ const defaults = [];
283
+ for (const { record: seat } of boundSeats) {
284
+ const turn = presentSeats.find(row => row.session === seat.id)?.lastTurn;
285
+ const account = accounts.find(row => row.kind === 'account' && row.id === seat.accountId)?.record;
286
+ if (seat.model !== null || !turn?.attemptId || account?.status !== 'verified'
287
+ || !fresh(timestamp(turn.ts), nowMs, policy.invocationTtlMs)) continue;
288
+ const envelope = modelEnvelope({ provider: account.provider, model: null, observedAtMs: turn.ts,
289
+ expiresAtMs: turn.ts + policy.invocationTtlMs, nowMs, catalog });
290
+ envelope.id = `default:${seat.id}`;
291
+ envelope.sourceRef = `presence:${seat.id}:${turn.ts}`;
292
+ envelope.record.accountId = account.id;
293
+ envelope.record.liveUse = { seatId: seat.id, harness: seat.harness, attemptId: turn.attemptId };
294
+ envelope.record.efforts = [!turn.effort || turn.effort === 'unknown' ? 'default' : turn.effort];
295
+ defaults.push(envelope);
296
+ }
267
297
  return [
268
- ...balanceEvidence({ snapshots: balances, orgId, nowMs, policy }),
298
+ ...accounts,
269
299
  ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
270
- ...seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy }),
300
+ ...boundSeats,
271
301
  ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
302
+ ...defaults,
272
303
  ];
273
304
  }
274
305
 
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { projectBoardCards } from './board-bridge.mjs';
3
- import { createRolloutOperations, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
3
+ import { createRolloutOperations, createShadowScheduler, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
4
4
  import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
5
5
  ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
6
6
  import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
@@ -489,6 +489,7 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
489
489
  },
490
490
  };
491
491
  Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
492
+ service.tickShadow = createShadowScheduler({ service, orgId: configuredOrg, clock });
492
493
  service.executor = { ...executor, kill(orgId, input, actor) {
493
494
  const control = KillSchema.parse(input);
494
495
  return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);