trantor 0.18.138 → 0.18.140

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,205 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
- import { join } from "node:path";
5
- import { createServer, createConnection } from "node:net";
6
- import { createServer as createHttpServer } from "node:http";
7
- import { DrillReport } from "./drill-report.mjs";
8
- import { CARD_STEPS, findHandoff } from "./drill-surface.mjs";
9
- import { appVerdict, startDrillHub, stopChild, checkSocketHome } from "./drill-seams.mjs";
10
- import { signedGet, signedPost } from "../hooks/lib/api.mjs";
11
-
12
- test("S4 waits for the hook ledger when relay_handoff arrives first", () => {
13
- const world = mkdtempSync(join(import.meta.dirname, "..", ".agent-bus-out", "ledger-"));
14
- try {
15
- assert.equal(findHandoff(join(world, "missing"), "trantor"), null);
16
- writeFileSync(join(world, "trantor-100.json"), JSON.stringify({ summary: "tool handoff" }));
17
- writeFileSync(join(world, "trantor-101.json"), "{");
18
- writeFileSync(join(world, "trantor-102.json"), JSON.stringify({ states: [] }));
19
- writeFileSync(join(world, "other-100.json"), JSON.stringify({ states: [{ state: "written" }] }));
20
- assert.equal(findHandoff(world, "trantor"), null);
21
- const ledger = join(world, "trantor-103.json");
22
- writeFileSync(ledger, JSON.stringify({ states: [{ state: "written" }] }));
23
- assert.equal(findHandoff(world, "trantor"), ledger);
24
- writeFileSync(ledger, JSON.stringify({ states: [{ state: "written" }, { state: "claimed" }, { state: "recapped" }] }));
25
- assert.equal(findHandoff(world, "trantor"), ledger);
26
- } finally { rmSync(world, { recursive: true, force: true }); }
27
- });
28
-
29
- test("signed closer on an enforce hub: complete evidence closes, partial/failure/skip never does", async () => {
30
- const out = join(import.meta.dirname, "..", ".agent-bus-out");
31
- mkdirSync(out, { recursive: true });
32
- const world = mkdtempSync(join(out, "closer-test-"));
33
- const bus = join(world, "bus");
34
- const hub = await startDrillHub(world, bus);
35
- const saved = { ...process.env };
36
- Object.assign(process.env, { RELAY_URL: hub.url, AGENT_BUS_DIR: bus, RELAY_SESSION: "drill:trantor", RELAY_PROJECT: "trantor" });
37
- const project = "trantor", session = "drill:trantor";
38
- const path = join(world, "drill-result.json");
39
- try {
40
- const create = await signedPost("/task", { project, by: session, title: "closer test", status: "testing" });
41
- assert.equal(create.ok, true, JSON.stringify(create));
42
- const id = create.json.task.id;
43
- const report = new DrillReport({ [id]: { steps: ["one", "two"], autoClose: true } }, path, { project, session });
44
- report.record("one", "pass", "first assertion", "real evidence A");
45
- await report.closePassed();
46
- assert.equal(report.results()[id].status, "fail");
47
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks[0].status, "testing");
48
- report.complete("one");
49
- report.record("two", "pass", "second assertion", "real evidence B");
50
- report.complete("two");
51
- assert.equal(await report.closePassed(), true);
52
- const card = (await signedGet("/tasks?project=trantor")).json.tasks[0];
53
- assert.equal(card.status, "done");
54
- assert.equal(card.workedBy, session);
55
- assert.match(card.log.at(-1).text, /^Drill: trantor drill PASS/); // #6452: the closer's note IS the drill line the hub gate requires
56
- assert.match(card.log.at(-1).text, /real evidence A/);
57
- assert.match(card.log.at(-1).text, /real evidence B/);
58
- assert.equal(JSON.parse(readFileSync(path, "utf8"))[id].closure, "done");
59
- const notes = card.log.length;
60
- await report.closePassed();
61
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks[0].log.length, notes);
62
- const unsigned = await fetch(`${hub.url}/task/update`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, status: "testing", by: session }) });
63
- assert.equal(unsigned.status, 401);
64
-
65
- for (const status of ["fail", "skip"]) {
66
- const created = await signedPost("/task", { project, by: session, title: status, status: "testing" });
67
- const blockedId = created.json.task.id;
68
- const blocked = new DrillReport({ [blockedId]: { steps: ["step"], autoClose: true } }, path, { project, session });
69
- blocked.record("step", "pass", "partial success");
70
- blocked.record("step", status, "missing proof");
71
- blocked.complete("step");
72
- await blocked.closePassed();
73
- assert.equal(blocked.results()[blockedId].status, status);
74
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks.find(row => row.id === blockedId).status, "testing");
75
- }
76
- // #11498: a green seam mapped to a card the board no longer has (the fleet cap deletes old
77
- // cards, #11142) — the hub's 404 "no such task" is a stale map, recorded as gone, never red.
78
- const missing = new DrillReport({ 999999: { steps: ["step"], autoClose: true } }, path, { project, session });
79
- missing.record("step", "pass", "proof");
80
- missing.complete("step");
81
- assert.equal(await missing.closePassed(), true);
82
- assert.equal(missing.results()[999999].closure, "gone: card no longer on the board");
83
- assert.equal(missing.exitCode(), 0);
84
- const fresh = new DrillReport({ [id]: { steps: ["one"], autoClose: true } }, path, { project, session });
85
- assert.equal(fresh.results()[id].status, "fail", "a rerun cannot inherit old PASS evidence");
86
- } finally {
87
- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
88
- Object.assign(process.env, saved);
89
- await stopChild(hub.child);
90
- rmSync(world, { recursive: true, force: true });
91
- }
92
- });
93
-
94
- test("gone vs refused (#11498): a 404 no-such-task close is green, any other refusal stays red", async () => {
95
- const out = join(import.meta.dirname, "..", ".agent-bus-out");
96
- mkdirSync(out, { recursive: true });
97
- const world = mkdtempSync(join(out, "refusal-test-"));
98
- const bus = join(world, "bus");
99
- mkdirSync(bus, { recursive: true });
100
- // A stub hub that refuses per card id: 777 is gone (404 no-such-task, the fleet cap's answer,
101
- // #11142), 4242 is a cross-project refusal, 5150 a server error — the closes a drill must keep red.
102
- const answers = { 777: [404, "no such task"], 4242: [403, "cross-project writes are refused"], 5150: [500, "hub exploded"] };
103
- const stub = createHttpServer((req, res) => {
104
- let body = "";
105
- req.on("data", d => { body += d; });
106
- req.on("end", () => {
107
- let id = null; try { id = JSON.parse(body).id; } catch {}
108
- const [code, error] = answers[id] || [404, "no such task"];
109
- res.writeHead(code, { "content-type": "application/json" });
110
- res.end(JSON.stringify({ error }));
111
- });
112
- });
113
- await new Promise(resolve => stub.listen(0, "127.0.0.1", resolve));
114
- const saved = { ...process.env };
115
- Object.assign(process.env, { RELAY_URL: `http://127.0.0.1:${stub.address().port}`, AGENT_BUS_DIR: bus, RELAY_SESSION: "drill:trantor", RELAY_PROJECT: "trantor" });
116
- const ctx = { project: "trantor", session: "drill:trantor" };
117
- try {
118
- const report = (id) => {
119
- const r = new DrillReport({ [id]: { steps: ["step"], autoClose: true } }, join(world, `result-${id}.json`), ctx);
120
- r.record("step", "pass", "proof", "real evidence");
121
- r.complete("step");
122
- return r;
123
- };
124
- const gone = report(777);
125
- assert.equal(await gone.closePassed(), true, "404 no-such-task is a stale map, not a failed seam");
126
- assert.equal(gone.results()[777].closure, "gone: card no longer on the board");
127
- assert.equal(gone.exitCode(), 0);
128
-
129
- // gone + refused together: one real hub refusal among gones still reds the drill
130
- const mixed = new DrillReport({ 777: { steps: ["step"], autoClose: true }, 4242: { steps: ["step"], autoClose: true } }, join(world, "result-mixed.json"), ctx);
131
- for (const id of [777, 4242]) { mixed.record("step", "pass", "proof", "real evidence"); mixed.complete("step"); }
132
- assert.equal(await mixed.closePassed(), false);
133
- assert.equal(mixed.results()[777].closure, "gone: card no longer on the board");
134
- assert.match(mixed.results()[4242].closure, /^failed: hub 403/);
135
- assert.equal(mixed.exitCode(), 1);
136
-
137
- const dead = report(5150);
138
- assert.equal(await dead.closePassed(), false, "a server error is a real refusal");
139
- assert.match(dead.results()[5150].closure, /^failed: hub 500/);
140
- assert.equal(dead.exitCode(), 1);
141
- } finally {
142
- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
143
- Object.assign(process.env, saved);
144
- stub.close();
145
- rmSync(world, { recursive: true, force: true });
146
- }
147
- });
148
-
149
- test("app proof requires every leg and rejects skipped key targets", () => {
150
- assert.deepEqual(CARD_STEPS[6317].steps, ["S6-key-post", "S6-key-throw"]);
151
- assert.equal(appVerdict("ask", "ask-drill PASS:"), false);
152
- assert.equal(appVerdict("ask", "ask-drill open PASS\nask-drill cold PASS\nask-drill PASS:"), true);
153
- const key = [1, 2, 3].map(pass => `key-drill pass=${pass} posted keyDown+keyUp`).join("\n") + "\nkey-drill verdict exit=0";
154
- assert.equal(appVerdict("key-post", key), true);
155
- assert.equal(appVerdict("key-post", key + "\npass=2 skipped"), false);
156
- assert.equal(appVerdict("key-throw", key), false);
157
- assert.equal(appVerdict("key-throw", key, "TaoObjcExceptionDrill"), true);
158
- assert.equal(appVerdict("handoff", "handoff-drill PASS:\nhandoff-drill verdict exit=3"), false);
159
- });
160
-
161
- test("manual probes remain SKIP even when the runner stops before reaching them", () => {
162
- const world = mkdtempSync(join(import.meta.dirname, "..", ".agent-bus-out", "skip-"));
163
- try {
164
- const report = new DrillReport(CARD_STEPS, join(world, "result.json"), { project: "trantor", session: "drill:trantor" });
165
- assert.deepEqual(Object.keys(CARD_STEPS).filter(id => CARD_STEPS[id].autoClose), ["6481", "6667", "6668"]);
166
- for (const id of [6317, 6533, 6587, 6483]) {
167
- assert.equal(report.results()[id].status, "skip");
168
- assert.equal(report.results()[id].closure, "not attempted");
169
- assert.match(report.results()[id].evidence.join(" "), id === 6587 ? /live duty probe/ : /covered by in-app Drill Mode/);
170
- }
171
- assert.equal(report.exitCode(), 1, "unrun seams still fail");
172
- for (const { steps, recipe } of Object.values(CARD_STEPS)) {
173
- if (recipe) continue;
174
- for (const step of steps) {
175
- report.record(step, step === "S5" ? "skip" : "pass", step === "S5" ? "interactive Terminal takeover probe" : "seam proof");
176
- report.complete(step);
177
- }
178
- }
179
- assert.equal(report.exitCode(), 0, "passing seams plus manual SKIPs exit zero");
180
- report.record("S4", "fail", "ledger missing");
181
- assert.equal(report.exitCode(), 1, "a real seam failure remains fatal");
182
- } finally { rmSync(world, { recursive: true, force: true }); }
183
- });
184
-
185
- test("short drill HOME connects through the native socket symlink; old staging is rejected", async () => {
186
- const world = mkdtempSync(`${join(import.meta.dirname, "..", ".agent-bus-out")}/`);
187
- const server = createServer(socket => socket.end("connected"));
188
- try {
189
- const path = checkSocketHome(world);
190
- assert.throws(() => checkSocketHome(join(world, "x".repeat(108))), /too long/);
191
- mkdirSync(join(world, ".config", "herdr"), { recursive: true });
192
- const target = join(world, "s");
193
- await new Promise((resolve, reject) => { server.once("error", reject); server.listen(target, resolve); });
194
- symlinkSync(target, path);
195
- const proof = await new Promise((resolve, reject) => {
196
- const socket = createConnection(path);
197
- socket.once("error", reject);
198
- socket.once("data", data => resolve(data.toString()));
199
- });
200
- assert.equal(proof, "connected");
201
- } finally {
202
- await new Promise(resolve => server.close(resolve));
203
- rmSync(world, { recursive: true, force: true });
204
- }
205
- });
@@ -1,52 +0,0 @@
1
- #!/usr/bin/env node
2
- // relay-watch streams the bus and lists live peer status.
3
- // Run `node bin/relay-watch.mjs [session]`; the default watches every session.
4
- import { resolveProject, hostId, resolveHub } from "../lib/project.mjs";
5
- import { loadOrCreate } from "../lib/identity.mjs";
6
- import { sfetch, sfetchJson } from "../lib/signed-fetch.mjs";
7
-
8
- const PROJECT = resolveProject(process.cwd());
9
- const ME = process.env.RELAY_SESSION
10
- || (process.env.RELAY_AGENT ? `${process.env.RELAY_AGENT}:${PROJECT}` : `${hostId()}:${PROJECT}`);
11
- const identity = loadOrCreate(ME, "agent");
12
- const URL_BASE = resolveHub(PROJECT);
13
- const SESSION = process.argv[2] || "all";
14
- const t = () => new Date().toLocaleTimeString();
15
-
16
- async function showPeers() {
17
- try {
18
- const { peers } = await (await sfetchJson(`${URL_BASE}/peers`, { method: "GET", identity })).json();
19
- const live = peers.filter(p => p.online);
20
- console.log(`\n live sessions (${live.length}):`);
21
- for (const p of live) console.log(` 🟢 ${p.session}${p.machine ? ` [${p.machine}]` : ""}${p.status ? ` — ${p.status}` : ""}`);
22
- console.log("");
23
- } catch {}
24
- }
25
-
26
- async function watch() {
27
- console.log(`relay-watch → ${URL_BASE} (watching "${SESSION}") — Ctrl-C to stop`);
28
- await showPeers();
29
- for (;;) {
30
- try {
31
- const r = await sfetch(`${URL_BASE}/stream?session=${encodeURIComponent(SESSION)}`, { headers: { accept: "text/event-stream" } }, identity);
32
- if (!r.ok || !r.body) throw new Error(`stream ${r.status}`);
33
- let buf = "";
34
- const dec = new TextDecoder();
35
- for await (const chunk of r.body) {
36
- buf += dec.decode(chunk, { stream: true });
37
- let i;
38
- while ((i = buf.indexOf("\n\n")) >= 0) {
39
- const frame = buf.slice(0, i); buf = buf.slice(i + 2);
40
- for (const line of frame.split("\n")) {
41
- if (!line.startsWith("data:")) continue;
42
- try { const m = JSON.parse(line.slice(5).trim()); console.log(` [${t()}] ${m.from} → ${m.to}: ${m.text}`); } catch {}
43
- }
44
- }
45
- }
46
- } catch (e) {
47
- console.error(` (stream dropped: ${e?.message || e} — reconnecting in 2s)`);
48
- await new Promise(r => setTimeout(r, 2000));
49
- }
50
- }
51
- }
52
- watch();
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env node
2
- // trantor seat-tokens (#11559) — per-provider token totals for the seat fleet from opencode's
3
- // session store, the 30-day shape compared week over week: sessions, assistant steps, tokens,
4
- // the single biggest step, and cost. Read-only; a missing or locked DB prints "no data".
5
- // node bin/seat-tokens.mjs [--days 30] [--db <path>] [--json]
6
- import { homedir } from "node:os";
7
- import { join } from "node:path";
8
- import { seatTokensReport } from "../lib/seat-tokens.mjs";
9
-
10
- const argv = process.argv.slice(2);
11
- const val = (k, d) => { const i = argv.indexOf(k); return i >= 0 && argv[i + 1] ? argv[i + 1] : d; };
12
- const DAYS = Math.max(1, Number(val("--days", 30)) || 30);
13
- const DB = val("--db", join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "opencode", "opencode.db"));
14
- const since = Date.now() - DAYS * 24 * 60 * 60 * 1000;
15
- const rows = seatTokensReport({ dbPath: DB, sinceMs: since });
16
- const fmt = (n) => Number(n).toLocaleString("en-US");
17
-
18
- if (val("--json", "")) { console.log(JSON.stringify({ db: DB, days: DAYS, providers: rows }, null, 1)); process.exit(0); }
19
- if (!rows.length) { console.log(`no session data in ${DB} for the last ${DAYS} day(s)`); process.exit(0); }
20
- console.log(`opencode seat usage, last ${DAYS} day(s) — ${DB}\n`);
21
- console.log("provider sessions steps input output cache-read cache-write peak-step cost");
22
- for (const r of rows) {
23
- console.log(
24
- String(r.provider).padEnd(18),
25
- String(r.sessions).padStart(8),
26
- String(r.steps).padStart(8),
27
- fmt(r.input).padStart(12),
28
- fmt(r.output).padStart(10),
29
- fmt(r.cacheRead).padStart(14),
30
- fmt(r.cacheWrite).padStart(14),
31
- fmt(r.peakInput).padStart(12),
32
- fmt(Math.round(r.cost)).padStart(6),
33
- );
34
- }
@@ -1,6 +0,0 @@
1
- # agent-bus for Codex CLI — add to ~/.codex/config.toml
2
- # Loading this MCP auto-registers the Codex session on the bus + gives the relay_* tools.
3
- [mcp_servers.relay]
4
- command = "node"
5
- args = ["REPLACE/WITH/ABSOLUTE/PATH/agent-bus/mcp.mjs"]
6
- env = { RELAY_URL = "http://127.0.0.1:4477", RELAY_SESSION = "codex:myproject" }
@@ -1,10 +0,0 @@
1
- {
2
- "//": "trantor for Gemini CLI — merge into ~/.gemini/settings.json (or a project .gemini/settings.json).",
3
- "mcpServers": {
4
- "relay": {
5
- "command": "node",
6
- "args": ["REPLACE/WITH/ABSOLUTE/PATH/trantor/mcp.mjs"],
7
- "env": { "RELAY_URL": "http://127.0.0.1:4477", "RELAY_SESSION": "gemini:myproject" }
8
- }
9
- }
10
- }
@@ -1,72 +0,0 @@
1
- // #11559: the seat fleet's token burn was invisible — mined by hand from opencode's DB. This
2
- // reader makes it a command: per-provider 30-day session/step/token totals, read-only, so a
3
- // week-over-week comparison is one line. No DB at all is "no data", never zero. Read path
4
- // mirrors lib/turn-usage.mjs (sqlite3 CLI, -readonly, fail-open).
5
- import { spawnSync } from "node:child_process";
6
-
7
- const num = (v) => { const n = Number(v); return Number.isInteger(n) && n >= 0 ? n : 0; };
8
-
9
- /// "provider/model" → "provider"; a bare model reads "?" so the row still groups. The 1.16.x DB
10
- /// also stores whole JSON blobs ({"id":…,"providerID":…,"variant":…}) in session.model — the
11
- /// provider then lives at $.providerID. The SQL mirrors this in CASE/WHEN form.
12
- export function providerOf(model) {
13
- const s = String(model || "").trim();
14
- if (s.startsWith("{")) {
15
- try { return String(JSON.parse(s).providerID || "?"); } catch { return "?"; }
16
- }
17
- const at = s.indexOf("/");
18
- return at > 0 ? s.slice(0, at) : "?";
19
- }
20
-
21
- const PROVIDER_SQL = (col) => `CASE WHEN substr(${col},1,1)='{' THEN COALESCE(json_extract(${col},'$.providerID'),'?')`
22
- + ` WHEN instr(${col},'/')>1 THEN substr(${col},1,instr(${col},'/')-1) ELSE '?' END`;
23
-
24
- export const SESSIONS_SQL = (sinceMs) => `SELECT ${SESSION_COLS} FROM session`
25
- + ` WHERE time_updated>=${Math.floor(sinceMs)} GROUP BY p ORDER BY total DESC;`;
26
- const SESSION_COLS = `${PROVIDER_SQL("model")} AS p, COUNT(*) AS sessions,`
27
- + ` COALESCE(SUM(tokens_input),0), COALESCE(SUM(tokens_output),0), COALESCE(SUM(tokens_cache_read),0),`
28
- + ` COALESCE(SUM(tokens_cache_write),0), COALESCE(SUM(cost),0), COALESCE(MIN(time_created),0),`
29
- + ` COALESCE(MAX(time_updated),0), COALESCE(SUM(tokens_input+tokens_output+tokens_cache_read+tokens_cache_write),0) AS total`;
30
-
31
- export const STEPS_SQL = (sinceMs) => `SELECT ${PROVIDER_SQL("s.model")} AS p,`
32
- + ` COUNT(m.id), COALESCE(MAX(json_extract(m.data,'$.tokens.input')),0)`
33
- + ` FROM message m JOIN session s ON s.id=m.session_id`
34
- + ` WHERE json_extract(m.data,'$.role')='assistant' AND m.time_created>=${Math.floor(sinceMs)} GROUP BY p;`;
35
-
36
- const pipeRows = (text, cols) => String(text || "").split("\n").filter((l) => l.trim() !== "")
37
- .map((line) => {
38
- const parts = line.split("|");
39
- return parts.length === cols ? parts : null;
40
- })
41
- .filter(Boolean);
42
-
43
- /// { provider, sessions, input, output, cacheRead, cacheWrite, cost, firstAt, lastAt, tokens,
44
- /// steps, peakInput } per provider, tokens descending. [] when both queries return nothing —
45
- /// an empty fleet and an unreadable DB print the same "no data" line, never zeros that lie.
46
- export function seatTokensReport({ dbPath, sinceMs, run = spawnSync } = {}) {
47
- if (!dbPath || !Number.isFinite(sinceMs)) return [];
48
- const q = (sql) => {
49
- let r;
50
- try { r = run("sqlite3", ["-readonly", dbPath, sql], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15000 }); }
51
- catch { return null; }
52
- return !r || r.error || r.status !== 0 ? null : r.stdout;
53
- };
54
- const sessions = pipeRows(q(SESSIONS_SQL(sinceMs)), 10);
55
- const steps = pipeRows(q(STEPS_SQL(sinceMs)), 3);
56
- const byProvider = new Map(sessions.map((c) => [c[0], {
57
- provider: c[0],
58
- sessions: num(c[1]),
59
- input: num(c[2]), output: num(c[3]), cacheRead: num(c[4]), cacheWrite: num(c[5]),
60
- cost: Number(c[6]) || 0,
61
- firstAt: num(c[7]), lastAt: num(c[8]),
62
- tokens: num(c[9]),
63
- steps: 0, peakInput: 0,
64
- }]));
65
- for (const [p, count, peak] of steps) {
66
- const row = byProvider.get(p);
67
- if (!row) continue;
68
- row.steps = num(count);
69
- row.peakInput = num(peak);
70
- }
71
- return [...byProvider.values()].sort((a, b) => b.tokens - a.tokens);
72
- }
@@ -1,5 +0,0 @@
1
- {
2
- "name": "trantor-band",
3
- "version": "0.1.0",
4
- "description": "Pilot: a line above the Claude Code prompt with live context fill and the project's handoff state, read from Trantor's files. Off unless TRANTOR_MOD=1."
5
- }
@@ -1,72 +0,0 @@
1
- // Pure helpers for the trantor-band pilot mod (#12091). No I/O and no Node imports on purpose:
2
- // the mod runs in Claude Code's sandboxed module environment, and the tests import this file directly.
3
-
4
- // The session id comes from Claude Code, but it names a file, so keep it to a safe alphabet.
5
- export function safeId(id) {
6
- return String(id ?? "").replace(/[^A-Za-z0-9_.-]/g, "_").slice(0, 120);
7
- }
8
-
9
- // Context fill as a fraction, from $.session.usage().context. Null until the first API response.
10
- export function contextFraction(context) {
11
- const tokens = Number(context?.tokens);
12
- const window = Number(context?.window);
13
- if (context?.tokens == null || !Number.isFinite(tokens) || !Number.isFinite(window) || window <= 0 || tokens < 0) return null;
14
- return Math.min(1, tokens / window);
15
- }
16
-
17
- export function contextPercent(context) {
18
- const frac = contextFraction(context);
19
- return frac === null ? null : Math.round(frac * 100);
20
- }
21
-
22
- // The file the pilot leaves for Trantor's own code to read later.
23
- export function contextRecord(context, ts) {
24
- const frac = contextFraction(context);
25
- if (frac === null) return null;
26
- return { ts, tokens: Number(context.tokens), window: Number(context.window), frac: Math.round(frac * 10000) / 10000 };
27
- }
28
-
29
- // The project id a checkout records in .trantor/project.json, mirroring lib/project.mjs readProjectId.
30
- export function projectFromMarker(text) {
31
- try {
32
- const id = JSON.parse(text)?.id;
33
- return /^[A-Za-z0-9][A-Za-z0-9_.-]{0,79}$/.test(String(id ?? "")) && !String(id).includes("..") ? String(id) : "";
34
- } catch { return ""; }
35
- }
36
-
37
- export function basename(path) {
38
- return String(path ?? "").replace(/\/+$/, "").split("/").pop() || "";
39
- }
40
-
41
- // The newest <project>-<unix seconds>.json among a directory listing, or "" (the name handoff.mjs writes).
42
- export function newestHandoffName(names, project) {
43
- if (!project) return "";
44
- const prefix = `${project}-`;
45
- let best = "";
46
- let bestTs = -1;
47
- for (const name of names || []) {
48
- if (!name.startsWith(prefix)) continue;
49
- const rest = name.slice(prefix.length);
50
- if (!/^\d+\.json$/.test(rest)) continue;
51
- const ts = Number(rest.slice(0, -5));
52
- if (ts > bestTs) { bestTs = ts; best = name; }
53
- }
54
- return best;
55
- }
56
-
57
- // "pending" (written, nobody has it), "claimed" (a fresh session holds an unexpired claim), or ""
58
- // when it is consumed or unreadable. Mirrors hooks/lib/handoff-claims.mjs: consumed, claim.expiresAt.
59
- export function handoffState(text, nowSeconds) {
60
- let record;
61
- try { record = JSON.parse(text); } catch { return ""; }
62
- if (!record || record.consumed) return "";
63
- return Number(record.claim?.expiresAt) > nowSeconds ? "claimed" : "pending";
64
- }
65
-
66
- // The band's one line. Parts that are unknown are left out; an empty result means draw nothing.
67
- export function bandText({ percent, handoff }) {
68
- const parts = [];
69
- if (Number.isFinite(percent)) parts.push(`ctx ${percent}%`);
70
- if (handoff) parts.push(`handoff ${handoff}`);
71
- return parts.join(" · ");
72
- }
@@ -1,5 +0,0 @@
1
- {
2
- "modules": [
3
- "./trantor-band.tsx"
4
- ]
5
- }
@@ -1,83 +0,0 @@
1
- // Read-only pilot band (#12091): "ctx 34% · handoff pending" above the prompt, OFF unless TRANTOR_MOD=1.
2
- // It never calls the hub (no auth surface) and any error draws nothing.
3
- // The one write is ~/.agent-bus/mod-context/<session>.json.
4
- import type { EngineInterface, Register } from 'claude-code'
5
-
6
- import {
7
- bandText, basename, contextPercent, contextRecord, handoffState, newestHandoffName, projectFromMarker, safeId,
8
- } from './band-lib.mjs'
9
-
10
- type Snapshot = { percent: number | null; handoff: string; at: number }
11
-
12
- const REFRESH_MS = 15_000
13
-
14
- // A reload starts these over; they are only a cache of what the files and the engine can say again.
15
- let snap: Snapshot = { percent: null, handoff: '', at: 0 }
16
-
17
- // AGENT_BUS_DIR mirrors hooks/lib/handoff.mjs; HOME is the fallback.
18
- async function busDir($: EngineInterface): Promise<string> {
19
- const override = await $.env.get('AGENT_BUS_DIR')
20
- if (override) return override
21
- const home = await $.env.get('HOME')
22
- return home ? `${home}/.agent-bus` : ''
23
- }
24
-
25
- async function readHandoff($: EngineInterface, bus: string): Promise<string> {
26
- const root = await $.session.root()
27
- let project = ''
28
- try { project = projectFromMarker(await $.fs.read(`${root}/.trantor/project.json`)) } catch {}
29
- if (!project) project = basename(root)
30
- const dir = `${bus}/handoffs`
31
- const entries = await $.fs.list(dir)
32
- const name = newestHandoffName(entries.map(entry => entry.name), project)
33
- if (!name) return ''
34
- return handoffState(await $.fs.read(`${dir}/${name}`), Math.floor((await $.clock.now()) / 1000))
35
- }
36
-
37
- // One refresh: the live context from the native API, the handoff file, and the context JSON.
38
- async function refresh($: EngineInterface, writeContext: boolean): Promise<void> {
39
- try {
40
- if ((await $.env.get('TRANTOR_MOD')) !== '1') return
41
- const bus = await busDir($)
42
- const usage = await $.session.usage()
43
- const now = await $.clock.now()
44
- let handoff = ''
45
- try { if (bus) handoff = await readHandoff($, bus) } catch {}
46
- snap = { percent: contextPercent(usage.context), handoff, at: now }
47
- if (writeContext && bus) {
48
- const record = contextRecord(usage.context, now)
49
- const id = safeId(await $.session.id())
50
- if (record && id) await $.fs.write(`${bus}/mod-context/${id}.json`, JSON.stringify(record))
51
- }
52
- } catch {}
53
- }
54
-
55
- export const register: Register = on => {
56
- on('session.start', async ($, e, next) => {
57
- await refresh($, false)
58
- return next(e)
59
- })
60
-
61
- on('turn.complete', async ($, e, next) => {
62
- await refresh($, true)
63
- try { $.ui.invalidate('ui.render') } catch {}
64
- return next(e)
65
- })
66
-
67
- on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
68
- try {
69
- if ((await $.env.get('TRANTOR_MOD')) !== '1' || e.props.hasSurvey) return next(e)
70
- if ((await $.clock.now()) - snap.at > REFRESH_MS) await refresh($, false)
71
- const text = bandText(snap)
72
- if (!text) return next(e)
73
- const { Box, Text } = $.ui.resolve(e)
74
- return (
75
- <Box>
76
- <Text dimColor>{text}</Text>
77
- </Box>
78
- )
79
- } catch {
80
- return next(e)
81
- }
82
- })
83
- }
@@ -1,70 +0,0 @@
1
- // The engine's own headless harness for mods: `claude plugin test mods/trantor-band`.
2
- import { expect, mock, test } from 'claude-code/testing'
3
-
4
- // The stand-ins below only need the fields the mod reads; the full engine types are not the point.
5
- const PROPS: any = {
6
- hasSurvey: false,
7
- isWorking: false,
8
- maxRows: 10,
9
- bodyColumns: 80,
10
- scroll: { offset: 0, bodyRows: 10 },
11
- view: {},
12
- }
13
-
14
- const USAGE: any = {
15
- startedAt: 0,
16
- context: { tokens: 34_000, window: 100_000, percent: 34 },
17
- rateLimits: [],
18
- }
19
-
20
- const FILES: any = [
21
- { name: 'demo-100.json', kind: 'file', size: 1, mtimeMs: 0, isLink: false },
22
- { name: 'demo-200.json', kind: 'file', size: 1, mtimeMs: 0, isLink: false },
23
- ]
24
-
25
- // What the engine would draw there when the mod passes: a plain Text.
26
- const engineBand = ($: any, e: any): any => {
27
- const { Text } = $.ui.resolve(e)
28
- return h(Text, null, 'engine band')
29
- }
30
-
31
- const mountBand = ($: any): Promise<any> =>
32
- $.ui.mount({ plugin: 'trantor', surface: 'terminal', component: 'AbovePrompt', props: PROPS })
33
-
34
- test('the band passes through to the engine band while TRANTOR_MOD is unset', async ($, on) => {
35
- mock.env(on, {})
36
- on('session.usage', () => ({ value: USAGE }))
37
- on('ui.render', engineBand)
38
- const ui = await mountBand($)
39
- expect((await ui.find({ type: 'Text' }))?.text).toBe('engine band')
40
- await ui.unmount()
41
- })
42
-
43
- test('the band shows the live context fill when TRANTOR_MOD=1', async ($, on) => {
44
- mock.env(on, { TRANTOR_MOD: '1', HOME: '/h' })
45
- mock.clock(on, { now: 1_000_000 })
46
- on('session.usage', () => ({ value: USAGE }))
47
- on('session.root', () => ({ value: '/work/demo' }))
48
- on('fs.read', () => ({ deny: 'ENOENT' }))
49
- on('fs.list', () => ({ deny: 'ENOENT' }))
50
- on('ui.render', engineBand)
51
- const ui = await mountBand($)
52
- expect((await ui.find({ type: 'Text', text: /ctx 34%/ }))?.text).toContain('ctx 34%')
53
- await ui.unmount()
54
- })
55
-
56
- test('the band names the newest unconsumed handoff of the project', async ($, on) => {
57
- mock.env(on, { TRANTOR_MOD: '1', HOME: '/h' })
58
- mock.clock(on, { now: 1_000_000 })
59
- on('session.usage', () => ({ value: USAGE }))
60
- on('session.root', () => ({ value: '/work/demo' }))
61
- on('fs.list', () => ({ value: FILES }))
62
- on('fs.read', (_$: any, e: any) => {
63
- if (e.path.endsWith('project.json')) return { deny: 'ENOENT' }
64
- return { value: e.path.endsWith('demo-200.json') ? '{"consumed":false}' : '{"consumed":true}' }
65
- })
66
- on('ui.render', engineBand)
67
- const ui = await mountBand($)
68
- expect((await ui.find({ type: 'Text', text: /handoff/ }))?.text).toContain('ctx 34% · handoff pending')
69
- await ui.unmount()
70
- })