trantor 0.18.139 → 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.
@@ -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.139"
9
+ "version": "0.18.140"
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.139",
16
+ "version": "0.18.140",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.140",
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
@@ -214,8 +214,8 @@ function hostPane(ctx, chosen, id) {
214
214
  return pane;
215
215
  }
216
216
 
217
- // #6888: index the project once so its seats' Graft tools (graft_find_code, _trace_calls, …) have a
218
- // graph to serve. Non-blocking — the pane opens now, the ~7s build lands in the background; a no-op
217
+ // #6888: index the project once for the desktop's direct graft CLI reads. Non-blocking — the pane
218
+ // opens now, the ~7s build lands in the background; a no-op
219
219
  // if graft isn't installed or the index already exists (the graph self-refreshes per query after the
220
220
  // first build). Keeps the 20MB index out of the project's git.
221
221
  // Hide graft/ through .git/info/exclude, never the user's tracked .gitignore (#14322). Returns the file written, "" when not a git checkout.
@@ -251,7 +251,7 @@ export function maybeBuildGraft(dir) {
251
251
  const child = spawn("graft", ["build", dir], { cwd: dir, stdio: ["ignore", fd, fd], detached: true });
252
252
  child.on("error", () => {}); // ENOENT/EACCES: the log and the absent index are the evidence
253
253
  child.unref();
254
- console.error(`— indexing this project for the seats' Graft tools in the background (failures land in ${log}) —`);
254
+ console.error(`— indexing this project for the desktop's graft CLI in the background (failures land in ${log}) —`);
255
255
  } catch {}
256
256
  }
257
257
 
@@ -19,16 +19,16 @@ import { shellQuote } from "./crew/core.mjs";
19
19
  // One ownership map. Shared steps must finish before ANY card they cover can close.
20
20
  export const CARD_STEPS = {
21
21
  6799: { steps: ["S0", "S1", "S2", "S3", "S4", "S5"], autoClose: false },
22
- 6533: { steps: ["S6-ask"], autoClose: false, recipe: "covered by in-app Drill Mode: open a live orchestrator mid-ask, answer from Chat, and confirm the terminal advances and the card closes" },
22
+ 6533: { steps: ["S6-ask"], autoClose: false, recipe: "run TRANTOR_ASK_DRILL=trantor on the installed app, answer from Chat, and confirm the terminal advances and the card closes" },
23
23
  6668: { steps: ["S6-handoff"], autoClose: true },
24
- 6317: { steps: ["S6-key-post", "S6-key-throw"], autoClose: false, recipe: "covered by in-app Drill Mode: open a real Workspace with a live terminal pane and exercise key dispatch in the terminal and composer" },
24
+ 6317: { steps: ["S6-key-post", "S6-key-throw"], autoClose: false, recipe: "run TRANTOR_KEY_DRILL=post and TRANTOR_KEY_DRILL=throw on the installed app and verify key dispatch and exception containment" },
25
25
  6667: { steps: ["S4b", "S7"], autoClose: true },
26
26
  // P9 (#6965): the Phase-1 handoff carries a WorkingState and it carries NO credit. Never
27
27
  // auto-closes — with the flag off the step SKIPs, and a skip must not be mistaken for proof.
28
28
  6965: { steps: ["S4c"], autoClose: false, recipe: "set TRANTOR_STATE_HANDOFF=1 on a dogfood card, run `trantor drill`, and read S4c: the carried state must show 0 credited paths" },
29
29
  6587: { steps: ["S8"], autoClose: false, recipe: "needs live duty probe: operator removes the trantor/trantor-duty link, DMs the idle orchestrator, and checks for a socket nudge within 3 minutes" },
30
30
  6481: { steps: ["S9"], autoClose: true },
31
- 6483: { steps: ["S10"], autoClose: false, recipe: "covered by in-app Drill Mode (#6800): operator checks Accounts with the CLI below the app minimum, then restores the CLI" },
31
+ 6483: { steps: ["S10"], autoClose: false, recipe: "operator checks Settings › About with the CLI below the app minimum, then restores the CLI" },
32
32
  };
33
33
 
34
34
  export function findHandoff(dir, project) {
@@ -490,9 +490,9 @@ try {
490
490
  // attended (default) = recap-then-WAIT; unattended = recap-then-RESUME — the handoff's OPEN
491
491
  // THREADS are the work order ("handoffs must never be a break").
492
492
  if (handoff.mode === "unattended") {
493
- additionalContext += `🔄 **You are taking over from a prior session that hit its context limit, in UNATTENDED (long-run) mode.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable; Foundation/Gaia has it ingested) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU BUILD (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — BEFORE you touch code. Reading is not waiting, and it is not optional: three days running, successors recapped from this summary alone and went straight to code, burning a fifth of a context window rediscovering what was already written down. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then RESUME the open threads — they are your work order. Do NOT wait for the user; keep building. Keep replies short: no status tables, no headers, no walls of text.\n\n`;
493
+ additionalContext += `🔄 **You are taking over from a prior session that hit its context limit, in UNATTENDED (long-run) mode.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU BUILD (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — BEFORE you touch code. Reading is not waiting, and it is not optional: three days running, successors recapped from this summary alone and went straight to code, burning a fifth of a context window rediscovering what was already written down. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then RESUME the open threads — they are your work order. Do NOT wait for the user; keep building. Keep replies short: no status tables, no headers, no walls of text.\n\n`;
494
494
  } else {
495
- additionalContext += `🔄 **You are taking over from a prior session that hit its context limit.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable; Foundation/Gaia has it ingested) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU ANSWER (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — before you recap. A 3-sentence recap is producible from this summary alone, which is exactly how three days of takeovers went straight to code without opening anything. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then wait. Keep replies short: no status tables, no headers, no walls of text unless the user explicitly asks for detail.\n\n`;
495
+ additionalContext += `🔄 **You are taking over from a prior session that hit its context limit.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU ANSWER (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — before you recap. A 3-sentence recap is producible from this summary alone, which is exactly how three days of takeovers went straight to code without opening anything. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then wait. Keep replies short: no status tables, no headers, no walls of text unless the user explicitly asks for detail.\n\n`;
496
496
  }
497
497
  // Verification gates FIRST — these are structured "must verify before shipping" claims the prior
498
498
  // session couldn't independently prove. They go above the summary on purpose: a safety-critical
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.140",
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",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.140",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"
@@ -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,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,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
- }