trantor 0.18.155 → 0.18.159

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.155"
9
+ "version": "0.18.159"
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.155",
16
+ "version": "0.18.159",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.155",
3
+ "version": "0.18.159",
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) {
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 });
@@ -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.mjs CHANGED
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { assertNoSecrets } from "./lib/scrub.mjs";
8
+ import { createDispatcherTick } from "./lib/dispatcher/store.mjs";
8
9
  import { DEFAULT_ORG } from "./lib/store-contract.mjs";
9
10
  import { createStoreRuntime } from "./hub/store.mjs";
10
11
  import { createAuthRuntime } from "./hub/auth.mjs";
@@ -141,16 +142,8 @@ const context = {
141
142
  REAP_GRACE_MS, CONTRACT_WINDOW_MS, PUBLIC_URL,
142
143
  };
143
144
  if (store.dispatcher && AUTH_MODE !== 'off') {
144
- let ticking = false;
145
- setInterval(async () => {
146
- if (ticking) return;
147
- ticking = true;
148
- try { await store.dispatcher.tick(); }
149
- catch (error) {
150
- store.dispatcher.store.closeAdmission();
151
- console.error(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
152
- } finally { ticking = false; }
153
- }, 1000).unref();
145
+ setInterval(createDispatcherTick({ dispatcher: store.dispatcher }), 1000).unref();
146
+ setInterval(() => store.dispatcher.tickShadow(), 1000).unref();
154
147
  }
155
148
  const sessionChat = createSessionRuntime({
156
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.155",
3
+ "version": "0.18.159",
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",
@@ -10,6 +10,8 @@ import { homedir } from 'node:os';
10
10
 
11
11
  // Stable IDs and internal key fingerprints become subjects; credentials never leave the reader.
12
12
  // no zod here: lib/balances.mjs pulls this into the hook snapshot, which ships no node_modules (#14754)
13
+ // SAFETY: loginId comes from credential JSON or public caller input; reject non-strings before hashing.
14
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof
13
15
  const isLoginId = value => typeof value === 'string' && value.length >= 1 && value.length <= 512
14
16
  && value === value.trim() && !value.includes('@');
15
17
  export function providerSubject({ provider, loginId }) {
@@ -28,12 +30,16 @@ function oneLoginId(values) {
28
30
  }
29
31
 
30
32
  function tokenIdentity(token) {
33
+ // SAFETY: access_token is untrusted credential JSON; only strings can be JWT-decoded.
34
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof
31
35
  if (typeof token !== 'string') return null;
32
36
  try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); }
33
37
  catch { return null; }
34
38
  }
35
39
 
36
40
  function credentialLogin(key) {
41
+ // SAFETY: key can come from untrusted credential JSON; never coerce non-strings into a login.
42
+ // oxlint-disable-next-line anti-slop/no-runtime-typeof
37
43
  return typeof key === 'string' && key.length > 0 ? `key:${createHash('sha256').update(key).digest('hex')}` : null;
38
44
  }
39
45
 
@@ -43,7 +49,17 @@ export function readProviderIdentity({ provider, home = homedir(), env = process
43
49
  deepseek: ['DEEPSEEK_API_KEY'], openrouter: ['OPENROUTER_API_KEY'],
44
50
  moonshot: ['MOONSHOT_API_KEY'], qwen: ['QWEN_API_KEY'] };
45
51
  const key = (keyNames[provider] || []).map(name => env[name]).find(Boolean);
46
- if (key) {
52
+ if (provider === 'kimi') {
53
+ const auth = ['.kimi-code', '.kimi'].map(directory => loginFile(join(home, directory, 'credentials', 'kimi-code.json')))
54
+ .find(value => value?.access_token);
55
+ if (auth) {
56
+ const token = tokenIdentity(auth.access_token);
57
+ const ids = [auth.user_id, auth.userId, auth.user?.id, token?.user_id].filter(value => value != null && value !== '');
58
+ loginId = ids.length ? oneLoginId(ids) : token?.sub;
59
+ } else if (key) {
60
+ loginId = credentialLogin(key);
61
+ }
62
+ } else if (key) {
47
63
  loginId = credentialLogin(key);
48
64
  } else if (provider === 'codex') {
49
65
  const auth = loginFile(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json'));
@@ -56,14 +72,6 @@ export function readProviderIdentity({ provider, home = homedir(), env = process
56
72
  const config = loginFile(env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'));
57
73
  loginId = oneLoginId([auth?.claudeAiOauth?.accountUuid, config?.oauthAccount?.accountUuid]);
58
74
  }
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
75
  } else {
68
76
  const auth = loginFile(join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode', 'auth.json'));
69
77
  const names = provider === 'zai' ? ['zai', 'zai-coding-plan'] : [provider];
@@ -186,15 +186,16 @@ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
186
186
  const { accounts } = bindAccounts({ org: orgId, bindings });
187
187
  const evidence = [];
188
188
  for (const row of Array.isArray(rows) ? rows : []) {
189
+ if (row?.kind !== 'agent') continue;
189
190
  const id = text(row?.session, 200);
190
191
  const machine = text(row?.machine, 60);
191
- const harness = text(row?.llm, 200);
192
+ const agent = text(row?.llm, 200);
192
193
  const observedAtMs = timestamp(row?.lastSeen);
193
- if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
194
+ if (!id || !machine || !agent || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
194
195
  const lastTurnMs = timestamp(row?.lastTurn?.ts);
195
196
  const binding = resolveSeatAccount({ identity: row.accountIdentity, accounts });
196
197
  const record = { id, machine, accountId: binding.accountId, accountBindingReason: binding.reason,
197
- harness, model: text(row.model, 512) || null,
198
+ harness: 'crew', agent, model: text(row.model, 512) || null,
198
199
  busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
199
200
  lastBeatMs: observedAtMs, lastTurnMs };
200
201
  if (row.project) record.project = text(row.project, 200);
@@ -241,16 +242,17 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
241
242
  }
242
243
  }
243
244
  for (const seat of Array.isArray(seats) ? seats : []) {
245
+ if (seat?.kind !== 'agent') continue;
244
246
  const model = text(seat?.lastTurn?.model, 512);
245
247
  const seatId = text(seat?.session, 200);
246
- const harness = text(seat?.llm, 200);
248
+ const agent = text(seat?.llm, 200);
247
249
  const observedAtMs = timestamp(seat?.lastTurn?.ts);
248
- if (!model || !seatId || !harness || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
249
- const provider = model.includes('/') ? text(model.split('/')[0], 200) : harness;
250
+ if (!model || !seatId || !agent || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
251
+ const provider = model.includes('/') ? text(model.split('/')[0], 200) : agent;
250
252
  const key = `${provider}\0${model}`;
251
253
  const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
252
254
  expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
253
- envelope.record.invocation = observation({ value: { model, seatId, harness }, observedAtMs,
255
+ envelope.record.invocation = observation({ value: { model, seatId, harness: 'crew' }, observedAtMs,
254
256
  receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
255
257
  envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
256
258
  envelope.expiresAtMs = Math.max(envelope.expiresAtMs, observedAtMs + policy.invocationTtlMs);
@@ -308,7 +310,7 @@ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
308
310
  const keys = new Set(pending.map(envelope => JSON.stringify([envelope.kind, envelope.id])));
309
311
  for (const key of state.accepted.keys()) if (!keys.has(key)) state.accepted.delete(key);
310
312
  for (const key of state.failures) if (!keys.has(key)) state.failures.delete(key);
311
- for (const envelope of pending) {
313
+ const entries = pending.map(envelope => {
312
314
  const key = JSON.stringify([envelope.kind, envelope.id]);
313
315
  const sourceTime = envelope.observedAtMs;
314
316
  const hash = contentHash(envelope);
@@ -316,21 +318,19 @@ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
316
318
  if (previous && sourceTime >= previous.sourceTime && sourceTime <= previous.observedAtMs) {
317
319
  envelope.observedAtMs = hash === previous.hash ? previous.observedAtMs : nowMs;
318
320
  }
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
- }
321
+ return { envelope, key, sourceTime, hash,
322
+ retryObservedAtMs: !previous && envelope.observedAtMs < nowMs ? nowMs : undefined };
323
+ });
324
+ const outcomes = await service.registerEvidenceBatch(orgId, entries, { grant: grantId });
325
+ for (const [index, entry] of entries.entries()) {
326
+ const { envelope, key, sourceTime, hash } = entry;
327
+ const { result, error, observedAtMs } = outcomes[index];
328
+ if (!error) {
329
+ envelope.observedAtMs = observedAtMs;
330
330
  state.accepted.set(key, { sourceTime, hash, observedAtMs: envelope.observedAtMs });
331
331
  state.failures.delete(key);
332
332
  if (!result.replayed) written++;
333
- } catch (error) {
333
+ } else {
334
334
  rejected++;
335
335
  if (!state.failures.has(key)) {
336
336
  state.failures.add(key);