trantor 0.18.12 → 0.18.14

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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.12",
3
+ "version": "0.18.14",
4
4
  "description": "Trantor \u2014 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/cli.mjs CHANGED
@@ -73,6 +73,7 @@ switch (cmd) {
73
73
  case "recost": run("bin/recost.mjs"); break;
74
74
  case "handoff": run("bin/baton.mjs"); break;
75
75
  case "adopt": run("bin/adopt.mjs"); break;
76
+ case "takeover": run("bin/takeover.mjs"); break;
76
77
  case "summarize": run("bin/summarize.mjs"); break;
77
78
  case "policy": run("bin/policy.mjs"); break;
78
79
  case "proposals": case "proposal": run("bin/proposals.mjs"); break;
@@ -195,6 +196,7 @@ switch (cmd) {
195
196
  trantor herdr install|remove|status the login agent that keeps panes alive across a reboot
196
197
  trantor autonomy how much Trantor may do unasked: seats, your harness, commit/push/deploy
197
198
  trantor adopt take over a session already running in a Terminal, then open it here
199
+ trantor takeover the whole move in one command: idle-gate the Terminal session, end it gracefully, adopt, open in the pane — [--force] [--session <id>] [--dry-run]
198
200
  trantor integrate collect the crew's work, merge it, verify it, push it (--dry-run to rehearse)
199
201
  trantor down tear the crew down (kills processes, closes windows, no dialogs)
200
202
  trantor prune drop dead crew-window tracking rows (ghost workspaces/panes) without spawning anything
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env node
2
+ // `trantor takeover` — one command from "the conversation lives in a Terminal window" to "it
3
+ // lives in the pane" (#5495, design: docs/DESIGN-takeover-visibility.md).
4
+ //
5
+ // The chain: inventory → idle gate → graceful end → adopt → open. CLI-first on purpose: the
6
+ // app's button shells THIS command (takeover_now), so the terminal user and the button share one
7
+ // tested implementation — the handoff_now pattern.
8
+ //
9
+ // What this must never do, from the design:
10
+ // - never end a session that wrote its transcript seconds ago without --force (in-flight work);
11
+ // - never pick silently between two live candidates (refuse and show both; --session decides);
12
+ // - never leave the operator with nothing: if open fails after the terminal claude exited, print
13
+ // the exact `claude --resume <sid>` that recovers the thread by hand.
14
+ import { readdirSync, statSync, existsSync } from "node:fs";
15
+ import { join, dirname } from "node:path";
16
+ import { homedir } from "node:os";
17
+ import { fileURLToPath } from "node:url";
18
+ import { execFileSync, spawnSync } from "node:child_process";
19
+ import { resolveProject } from "../lib/project.mjs";
20
+
21
+ const HERE = dirname(fileURLToPath(import.meta.url));
22
+ const args = process.argv.slice(2);
23
+ const flag = (n) => args.includes(n);
24
+ const opt = (n) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : null; };
25
+ const JSON_OUT = flag("--json");
26
+ const stages = [];
27
+ const say = (s) => { stages.push(s); if (!JSON_OUT) console.log(s); };
28
+ const out = (ok, extra = {}) => {
29
+ if (JSON_OUT) console.log(JSON.stringify({ ok, stages, ...extra }));
30
+ process.exit(ok ? 0 : 2);
31
+ };
32
+
33
+ const project = args.find(a => !a.startsWith("--") && args[args.indexOf(a) - 1] !== "--session")
34
+ || resolveProject(process.cwd());
35
+ const devRoot = process.env.TRANTOR_DEV_ROOT || join(homedir(), "development");
36
+ const dir = join(devRoot, project);
37
+ if (!existsSync(dir)) { say(`no local checkout for ${project} (looked in ${devRoot})`); out(false, { reason: "no-checkout" }); }
38
+
39
+ // The idle gate: a transcript written this recently means the session is MID-TURN, and ending it
40
+ // would eat in-flight work. Overridable for drills and deliberate --force.
41
+ export const IDLE_GATE_SEC = Number(process.env.TRANTOR_TAKEOVER_IDLE_SEC || 15);
42
+
43
+ /** The decision table, pure so it can be drilled without processes (test-takeover.mjs). */
44
+ export function decide({ terminalPids, candidates, sessionFlag, force, idleGateSec = IDLE_GATE_SEC }) {
45
+ if (!terminalPids.length) return { action: "open", reason: "no terminal session — plain open (start or reopen the pane)" };
46
+ if (terminalPids.length > 1) {
47
+ return { action: "refuse", reason: `${terminalPids.length} claude sessions run in this directory (pids ${terminalPids.join(", ")}) — close the extras first; a takeover must know which conversation it is adopting` };
48
+ }
49
+ if (!candidates.length) return { action: "refuse", reason: "a claude runs here but no transcript has been written in the last hour — nothing safe to adopt" };
50
+ const chosen = sessionFlag ? candidates.find(c => c.id === sessionFlag) : candidates[0];
51
+ if (sessionFlag && !chosen) return { action: "refuse", reason: `${sessionFlag} is not among the recent transcripts here` };
52
+ if (!sessionFlag && candidates.length > 1) {
53
+ const list = candidates.slice(0, 4).map(c => `${c.id} (${c.ageSec}s ago)`).join(" · ");
54
+ return { action: "refuse", reason: `two live conversations here — pick one with --session <id>: ${list}` };
55
+ }
56
+ if (chosen.ageSec < idleGateSec && !force) {
57
+ return { action: "refuse", reason: `looks MID-TURN (transcript written ${chosen.ageSec}s ago, gate ${idleGateSec}s) — wait for the turn to finish, or --force` };
58
+ }
59
+ return { action: "takeover", sid: chosen.id, pid: terminalPids[0] };
60
+ }
61
+
62
+ // ---- inventory (process + filesystem truth only) ----------------------------------------------
63
+ function paneForegroundPgid() {
64
+ try {
65
+ const rows = execFileSync("cat", [join(process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus"), "crew-windows.txt")], { encoding: "utf8" });
66
+ const pane = rows.split("\n").map(l => l.split("\t")).find(f => f[0] === project && f[1] === "orch")?.[3];
67
+ if (!pane) return 0;
68
+ const info = execFileSync("herdr", ["pane", "process-info", "--pane", pane], { encoding: "utf8", timeout: 6000 });
69
+ return Number(JSON.parse(info.slice(info.search(/[[{]/)))?.result?.process_info?.foreground_process_group_id) || 0;
70
+ } catch { return 0; }
71
+ }
72
+
73
+ function terminalClaudePids() {
74
+ let pids = [];
75
+ try { pids = execFileSync("/usr/bin/pgrep", ["-x", "claude"], { encoding: "utf8" }).split("\n").filter(Boolean); } catch { return []; }
76
+ const panePgid = paneForegroundPgid();
77
+ const mine = [];
78
+ for (const pid of pids) {
79
+ if (Number(pid) === panePgid) continue; // the pane's own claude is not a "terminal session"
80
+ try {
81
+ const cwd = execFileSync("/usr/sbin/lsof", ["-a", "-d", "cwd", "-p", pid, "-Fn"], { encoding: "utf8" })
82
+ .split("\n").find(l => l.startsWith("n"))?.slice(1);
83
+ if (cwd === dir) mine.push(Number(pid));
84
+ } catch { /* raced away */ }
85
+ }
86
+ return mine;
87
+ }
88
+
89
+ function recentCandidates() {
90
+ const slug = dir.replace(/[/.]/g, "-");
91
+ const tdir = join(process.env.TRANTOR_CLAUDE_DIR || join(homedir(), ".claude", "projects"), slug);
92
+ if (!existsSync(tdir)) return [];
93
+ const now = Date.now();
94
+ return readdirSync(tdir).filter(f => f.endsWith(".jsonl"))
95
+ .map(f => { const st = statSync(join(tdir, f)); return { id: f.replace(/\.jsonl$/, ""), ageSec: Math.round((now - st.mtimeMs) / 1000) }; })
96
+ .filter(c => c.ageSec < 3600)
97
+ .sort((a, b) => a.ageSec - b.ageSec);
98
+ }
99
+
100
+ // ---- the chain --------------------------------------------------------------------------------
101
+ // Run the chain ONLY when this file is the entrypoint. The first cut used
102
+ // argv[1].endsWith("takeover.mjs"), which is also true for test-takeover.mjs — importing the
103
+ // decision table from the drill file executed a real (luckily idempotent) pane open.
104
+ import { basename as _bn } from "node:path";
105
+ if (process.argv[1] && _bn(process.argv[1]) === "takeover.mjs") {
106
+ const d = decide({ terminalPids: terminalClaudePids(), candidates: recentCandidates(), sessionFlag: opt("--session"), force: flag("--force") });
107
+ if (flag("--dry-run")) { say(`dry-run: ${d.action}${d.reason ? ` — ${d.reason}` : ""}${d.sid ? ` (sid ${d.sid}, pid ${d.pid})` : ""}`); out(true, { decision: d }); }
108
+ if (d.action === "refuse") { say(d.reason); out(false, { reason: d.reason }); }
109
+
110
+ if (d.action === "takeover") {
111
+ say(`ending Terminal session pid ${d.pid} (idle ${IDLE_GATE_SEC}s gate passed)`);
112
+ try { process.kill(d.pid, "SIGTERM"); } catch {}
113
+ const deadline = Date.now() + 8000;
114
+ let alive = true;
115
+ while (alive && Date.now() < deadline) {
116
+ try { process.kill(d.pid, 0); spawnSync("sleep", ["0.3"]); } catch { alive = false; }
117
+ }
118
+ if (alive) { try { process.kill(d.pid, "SIGKILL"); } catch {} say("did not exit in 8s — killed"); }
119
+ else say("session ended cleanly");
120
+
121
+ const adopt = spawnSync(process.execPath, [join(HERE, "adopt.mjs"), project, "--session", d.sid], { encoding: "utf8", timeout: 20000 });
122
+ if (adopt.status !== 0) { say(`adopt failed: ${(adopt.stderr || adopt.stdout || "").trim().slice(0, 200)}`); out(false, { reason: "adopt-failed", sid: d.sid }); }
123
+ say(`adopted ${d.sid} as ${project}'s orchestrator thread`);
124
+ }
125
+
126
+ const open = spawnSync("bash", [join(HERE, "crew.sh"), "open", project], { cwd: dir, encoding: "utf8", timeout: 120000 });
127
+ if (open.status !== 0) {
128
+ say(`open failed: ${(open.stderr || "").trim().slice(0, 200)}`);
129
+ if (d.sid) say(`the conversation is safe on disk — recover by hand: claude --resume ${d.sid}`);
130
+ out(false, { reason: "open-failed", sid: d.sid || null });
131
+ }
132
+ say(`pane hosted: ${(open.stdout || "").trim().split("\n").pop()}`);
133
+ out(true, { sid: d.sid || null });
134
+ }
package/lib/balances.mjs CHANGED
@@ -120,7 +120,22 @@ export async function fetchBalances(env = process.env, opts = {}) {
120
120
  try { return { ...base, ok: true, ...(await a.fetch(env[envKey])) }; }
121
121
  catch (e) { return { ...base, ok: false, error: String(e?.message || e) }; }
122
122
  });
123
- return (await Promise.all(jobs)).filter(Boolean);
123
+ const rows = (await Promise.all(jobs)).filter(Boolean);
124
+ // Codex has no balance API to query — it authenticates by `codex login` and bills a
125
+ // subscription. The fleet list must still show it, honestly, or the header reads as if the
126
+ // seat does not exist. Evidence of configuration is the login artifact, not an env key.
127
+ if (!only || only.has("codex") || only.has("openai")) {
128
+ try {
129
+ const { existsSync } = await import("node:fs");
130
+ const { join } = await import("node:path");
131
+ const { homedir } = await import("node:os");
132
+ if (existsSync(join(homedir(), ".codex", "auth.json"))) {
133
+ rows.push({ provider: "codex", label: "Codex", kind: "subscription", via: "codex login",
134
+ ok: true, plan: "OpenAI subscription", note: "no balance API — flat subscription" });
135
+ }
136
+ } catch { /* no fs access → no row, never an error */ }
137
+ }
138
+ return rows;
124
139
  }
125
140
 
126
141
  // human one-liner for a credit entry (CLI + warning line)
@@ -131,6 +146,7 @@ export function fmtBalance(e) {
131
146
  const reset = e.resetTime ? ` · resets ${fmtReset(e.resetTime)}` : "";
132
147
  return `${e.label}${e.plan ? " (" + e.plan + ")" : ""}: ${e.remainingPct}% left${reset}`;
133
148
  }
149
+ if (e.kind === "subscription") return `${e.label}: ${e.plan || "subscription"} (${e.note || "no balance API"})`;
134
150
  const sym = e.currency === "CNY" ? "¥" : e.currency === "EUR" ? "€" : "$";
135
151
  if (e.unlimited || e.remaining == null) return `${e.label}: ${e.kind === "prepaid" ? "no limit / unknown" : e.kind}`;
136
152
  const amt = e.remaining.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.12",
3
+ "version": "0.18.14",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"