trantor 0.18.132 → 0.18.134
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.
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -0
- package/bin/baton-pane.mjs +22 -4
- package/bin/cli.mjs +42 -0
- package/bin/crew/herdr.mjs +27 -12
- package/bin/crew/open.mjs +4 -1
- package/bin/crew/restore.mjs +88 -0
- package/bin/crew-runner.mjs +17 -3
- package/bin/crew.mjs +7 -3
- package/bin/doctor.mjs +11 -0
- package/bin/herdr-agent.mjs +67 -13
- package/hub/routes/insights.mjs +51 -2
- package/hub/routes/messages.mjs +2 -1
- package/hub/routes/session.mjs +9 -2
- package/hub/store.mjs +133 -2
- package/lib/balances.mjs +6 -1
- package/lib/seat-compaction.mjs +26 -4
- package/lib/store-pg.mjs +64 -0
- package/lib/telemetry-ship.mjs +193 -0
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.134",
|
|
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/README.md
CHANGED
|
@@ -470,6 +470,11 @@ trantor setup | doctor | connect | profile | provider | models
|
|
|
470
470
|
then logs, tracked panes, live pids): `live`, `dead-quota`, `dead-auth`, `dead-crash`,
|
|
471
471
|
`no-runner`, or `no-pane`, each with the advice that actually fits. A quota-dead seat is
|
|
472
472
|
indistinguishable from a broken bus until you read the err file — this reads it for you.
|
|
473
|
+
- **`trantor telemetry ship [--all]`** sends turn history to the hub: this seat's log, or every
|
|
474
|
+
log in `~/.agent-bus/logs` with `--all`. Runners report each turn on their own after it ends;
|
|
475
|
+
this command is for history written before a hub could receive it, and for a hub that was
|
|
476
|
+
unreachable for a while. Safe to run twice: the hub ignores rows it already has. See
|
|
477
|
+
`docs/CONTRACT-turn-telemetry.md`.
|
|
473
478
|
- **`trantor down`** kills crew processes via their ttys and closes windows without macOS
|
|
474
479
|
"Terminate?" dialogs.
|
|
475
480
|
|
package/bin/baton-pane.mjs
CHANGED
|
@@ -112,6 +112,20 @@ function summary(value, limit = 240) {
|
|
|
112
112
|
return oneLine.length > limit ? `${oneLine.slice(0, limit - 1)}…` : oneLine;
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
+
/** #13913: herdr's own answer is the delivery receipt — text plus Enter are sent before herdr
|
|
116
|
+
* reports anything, so this only names what became of the kickoff. `timeout` is the busy
|
|
117
|
+
* successor (words are in, not picked up yet), never a failure to resend. */
|
|
118
|
+
export function kickoffVerdict(raw) {
|
|
119
|
+
let response;
|
|
120
|
+
try { response = JSON.parse(String(raw)); } catch { return "unreadable_response"; }
|
|
121
|
+
if (response?.result?.type === "agent_prompted") return "agent_prompted";
|
|
122
|
+
if (response?.error) {
|
|
123
|
+
const code = String(response.error.code || "herdr error");
|
|
124
|
+
return code === "timeout" ? "sent, not yet picked up" : `${code} (${summary(response.error.message)})`;
|
|
125
|
+
}
|
|
126
|
+
return "unexpected_response";
|
|
127
|
+
}
|
|
128
|
+
|
|
115
129
|
async function main() {
|
|
116
130
|
if (!handoffFile || !existsSync(handoffFile)) { log(`no handoff file (${handoffFile}) — abort`); process.exit(1); }
|
|
117
131
|
const pane = arg("--pane") || orchPane((() => { try { return readFileSync(join(busDir, "crew-windows.txt"), "utf8"); } catch { return ""; } })(), projectName);
|
|
@@ -168,10 +182,14 @@ async function main() {
|
|
|
168
182
|
await sleep(3000);
|
|
169
183
|
}
|
|
170
184
|
try {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
185
|
+
// #13913: the same bounded pickup wait the app uses — herdr sends the text and Enter, then
|
|
186
|
+
// holds the answer until the successor shows working/blocked activity (10s budget, well
|
|
187
|
+
// inside this socket's own 30s read timeout).
|
|
188
|
+
const raw = await socketRequest({
|
|
189
|
+
id: "trantor:agent.prompt", method: "agent.prompt",
|
|
190
|
+
params: { target: pane, text: KICKOFF_PROMPT, wait: { until: ["working", "blocked"], timeout_ms: 10_000 } },
|
|
191
|
+
});
|
|
192
|
+
log(`kickoff result: ${kickoffVerdict(raw)}`);
|
|
175
193
|
} catch (e) {
|
|
176
194
|
log(`kickoff FAILED (${String(e?.message).slice(0, 120)}) — successor may sit idle until spoken to`);
|
|
177
195
|
}
|
package/bin/cli.mjs
CHANGED
|
@@ -43,6 +43,7 @@ switch (cmd) {
|
|
|
43
43
|
case "down": runCrew(); break;
|
|
44
44
|
case "swap": runCrew(); break;
|
|
45
45
|
case "prune": runCrew(); break;
|
|
46
|
+
case "restore": runCrew(); break;
|
|
46
47
|
case "hub": {
|
|
47
48
|
const sub = args[0];
|
|
48
49
|
if (sub === "timeouts") { args.splice(0, 1); run("bin/hub-timeouts.mjs", process.execPath); break; }
|
|
@@ -139,6 +140,45 @@ switch (cmd) {
|
|
|
139
140
|
case "seats": case "seat": run("bin/seats.mjs"); break;
|
|
140
141
|
case "seat-why": case "why": run("bin/seat-why.mjs"); break;
|
|
141
142
|
case "seat-record": run("bin/seat-record.mjs"); break;
|
|
143
|
+
case "telemetry": {
|
|
144
|
+
// #14067: `trantor telemetry ship` is how existing history reaches the hub — this seat's log,
|
|
145
|
+
// or every *.jsonl in the logs folder with --all. Always from the start of the file: a re-run
|
|
146
|
+
// must come back as duplicates, not as silence.
|
|
147
|
+
if (args[0] !== "ship") { console.error("usage: trantor telemetry ship [--all]"); process.exit(1); }
|
|
148
|
+
const { shipTurnRows, seatForTelemetryFile, telemetryDir, telemetryFiles, telemetryFileFor } = await import(join(ROOT, "lib/telemetry-ship.mjs"));
|
|
149
|
+
const { sessionContext } = await import(join(ROOT, "hooks/lib/api.mjs"));
|
|
150
|
+
// History rows carry no machine: stamp this machine's label, as the runner does for new rows.
|
|
151
|
+
const { machineLabel } = await import(join(ROOT, "lib/machine-label.mjs"));
|
|
152
|
+
const { homedir } = await import("node:os");
|
|
153
|
+
let machineConfig = {};
|
|
154
|
+
try { machineConfig = JSON.parse(readFileSync(join(process.env.AGENT_BUS_DIR || process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus"), "config.json"), "utf8")); } catch {}
|
|
155
|
+
const machine = machineLabel(machineConfig);
|
|
156
|
+
const report = (label, r) => {
|
|
157
|
+
if (r.ok) console.log(`${label}: stored ${r.stored} · duplicates ${r.duplicates} · dropped ${r.dropped}`);
|
|
158
|
+
else console.error(`${label}: FAILED — ${r.error}`);
|
|
159
|
+
return r.ok ? 0 : 1;
|
|
160
|
+
};
|
|
161
|
+
if (args.includes("--all")) {
|
|
162
|
+
const dir = telemetryDir();
|
|
163
|
+
const files = telemetryFiles();
|
|
164
|
+
if (!files.length) { console.log(`no telemetry logs in ${dir}`); break; }
|
|
165
|
+
let failed = 0;
|
|
166
|
+
for (const name of files) {
|
|
167
|
+
const seat = seatForTelemetryFile(join(dir, name));
|
|
168
|
+
if (!seat) { console.log(`${name}: no seat rows — skipped`); continue; }
|
|
169
|
+
failed += report(`${seat.persona}-${seat.project}`, await shipTurnRows({ ...seat, fromStart: true, machine }));
|
|
170
|
+
}
|
|
171
|
+
process.exitCode = failed ? 1 : 0;
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
const { session, project } = sessionContext();
|
|
175
|
+
const persona = (session.split(":")[0] || session);
|
|
176
|
+
const file = telemetryFileFor(persona, project);
|
|
177
|
+
if (!existsSync(file)) { console.error(`no telemetry log for ${persona}-${project} at ${file}`); process.exit(1); }
|
|
178
|
+
const seat = seatForTelemetryFile(file) || { persona, project };
|
|
179
|
+
process.exitCode = report(`${seat.persona}-${seat.project}`, await shipTurnRows({ ...seat, fromStart: true, machine }));
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
142
182
|
case "orchestrate": run("bin/orchestrate.mjs"); break;
|
|
143
183
|
case "app": run("bin/app.mjs"); break;
|
|
144
184
|
case "patrol": run("bin/patrol.mjs"); break;
|
|
@@ -259,6 +299,7 @@ switch (cmd) {
|
|
|
259
299
|
trantor sync realign a seat branch with main from the receipts: sync [<seat>] [--dry-run] — refuses and names unharvested commits
|
|
260
300
|
trantor down tear the crew down (kills processes, closes windows, no dialogs)
|
|
261
301
|
trantor prune drop dead crew-window tracking rows (ghost workspaces/panes) without spawning anything
|
|
302
|
+
trantor restore after a reboot, reopen only the orchestrators you opted in: restore [--dry-run] · restore enable|disable <project>
|
|
262
303
|
trantor ui open the live dashboard (board + flow views)
|
|
263
304
|
trantor pair pair a phone: mint a trantor://enroll link for the companion app — [--role owner] [--sim] [--json]
|
|
264
305
|
trantor app the DESKTOP app: status | install | update — pulls the latest DMG from GitHub Releases
|
|
@@ -283,6 +324,7 @@ switch (cmd) {
|
|
|
283
324
|
trantor state a seat's working memory: show <seat> <card> [--json] · validate · reset --force · gc [--apply]
|
|
284
325
|
trantor seat-why WHY a seat is down (err file, logs, pids): seat-why <agent> [--json] — quota, auth, crash, or just no pane
|
|
285
326
|
trantor seat-record the per-project seat record the advisor benches from (✓/∅/↩ per difficulty) — [--project p] [--reset <seat>] [--json]
|
|
327
|
+
trantor telemetry ship send turn history to the hub — this seat's log, or every log with --all; prints stored/duplicates/dropped per file
|
|
286
328
|
trantor watch live bus feed in the terminal
|
|
287
329
|
trantor inbox THIS session's unread bus messages, signed (works under enforce) — [--all] [--consume] [--json]
|
|
288
330
|
trantor policy the autonomy ladder: show | set <project> <1-4> | link <a> <b> --reason "<why>"
|
package/bin/crew/herdr.mjs
CHANGED
|
@@ -6,6 +6,15 @@ export function herdrCall(ctx, args) {
|
|
|
6
6
|
return call("herdr", args, { env: ctx.env });
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
function requireHerdr(ctx, args, execute = herdrCall) {
|
|
10
|
+
const result = execute(ctx, args);
|
|
11
|
+
if (result.ok === false) {
|
|
12
|
+
const detail = result.stderr || result.stdout || "no error output";
|
|
13
|
+
throw new Error(`${formatCommand("herdr", args)} exited ${result.status}: ${detail}`);
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
|
|
9
18
|
export function workspaceList(ctx) {
|
|
10
19
|
if (!ctx.have.herdr) return { proven: false, ids: new Set(), names: new Set(), items: [] };
|
|
11
20
|
const result = herdrCall(ctx, ["workspace", "list"]);
|
|
@@ -21,12 +30,12 @@ export function workspaceList(ctx) {
|
|
|
21
30
|
}
|
|
22
31
|
|
|
23
32
|
export function createWorkspace(ctx, cwd, label) {
|
|
24
|
-
const parsed = parseJsonOutput(
|
|
33
|
+
const parsed = parseJsonOutput(requireHerdr(ctx, ["workspace", "create", "--cwd", cwd, "--label", label, "--no-focus"]).stdout);
|
|
25
34
|
const result = parsed?.result || {};
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
};
|
|
35
|
+
const workspace = result.workspace?.workspace_id || "";
|
|
36
|
+
const pane = result.root_pane?.pane_id || "";
|
|
37
|
+
if (!workspace || !pane) throw new Error("herdr workspace create returned no usable workspace and root pane");
|
|
38
|
+
return { workspace, pane };
|
|
30
39
|
}
|
|
31
40
|
|
|
32
41
|
export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
|
|
@@ -34,7 +43,7 @@ export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
|
|
|
34
43
|
if (pane) args.push(pane);
|
|
35
44
|
args.push("--direction", direction, "--no-focus");
|
|
36
45
|
if (cwd) args.push("--cwd", cwd);
|
|
37
|
-
const parsed = parseJsonOutput(
|
|
46
|
+
const parsed = parseJsonOutput(requireHerdr(ctx, args, execute).stdout);
|
|
38
47
|
return parsed?.result?.pane?.pane_id || "";
|
|
39
48
|
}
|
|
40
49
|
|
|
@@ -43,9 +52,14 @@ export function splitPane(ctx, pane, direction, cwd = "", execute = herdrCall) {
|
|
|
43
52
|
// is a layout question; process-info is the terminal question, and only a terminal hosts a session.
|
|
44
53
|
export function paneAlive(ctx, pane) {
|
|
45
54
|
if (!pane) return false;
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
55
|
+
return paneReadAlive(ctx, pane);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Herdr can retain a layout row after its terminal has vanished. A readable pane is the
|
|
59
|
+
// authoritative liveness signal shared by CLI callers; process-info can report stale metadata.
|
|
60
|
+
export function paneReadAlive(ctx, pane) {
|
|
61
|
+
if (!pane) return false;
|
|
62
|
+
return herdrCall(ctx, ["pane", "read", pane, "--source", "recent-unwrapped"]).ok;
|
|
49
63
|
}
|
|
50
64
|
|
|
51
65
|
export function workspacePane(ctx, workspace, preferredCwd) {
|
|
@@ -103,9 +117,10 @@ export function reportAgent(ctx, pane, agent, { sessionId = "", resumeArgv = []
|
|
|
103
117
|
}
|
|
104
118
|
|
|
105
119
|
function runSeat(ctx, pane, agent, command) {
|
|
106
|
-
if (
|
|
107
|
-
|
|
108
|
-
|
|
120
|
+
if (ctx.dry) return;
|
|
121
|
+
if (!pane) throw new Error(`herdr created no pane for ${agent}; the seat runner was not started`);
|
|
122
|
+
requireHerdr(ctx, ["pane", "rename", pane, `${agent} · ${ctx.project}`]);
|
|
123
|
+
requireHerdr(ctx, ["pane", "run", pane, command]);
|
|
109
124
|
}
|
|
110
125
|
|
|
111
126
|
function trackedWorkspace(ctx) {
|
package/bin/crew/open.mjs
CHANGED
|
@@ -169,7 +169,10 @@ function reattach(ctx, workspace, pane, id) {
|
|
|
169
169
|
if (!started.ok) throw new Error(`trantor open: could not start the orchestrator in pane ${pane}`);
|
|
170
170
|
reportOrchestrator(ctx, pane, id);
|
|
171
171
|
console.error(`— orchestrator pane was empty: resumed session ${id} in herdr:${workspace || "?"}/${pane} —`);
|
|
172
|
-
} else
|
|
172
|
+
} else {
|
|
173
|
+
reportOrchestrator(ctx, pane, id);
|
|
174
|
+
console.error(`— orchestrator already hosted: reattached to herdr:${workspace || "?"}/${pane} —`);
|
|
175
|
+
}
|
|
173
176
|
console.log(`herdr:${workspace || "?"}/${pane}`);
|
|
174
177
|
return true;
|
|
175
178
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readFileSync, existsSync, writeFileSync, renameSync, mkdirSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { call, parseJsonOutput } from "./core.mjs";
|
|
4
|
+
import { paneAlive, paneHasAgent, herdrCall } from "./herdr.mjs";
|
|
5
|
+
import { readRows } from "./state.mjs";
|
|
6
|
+
|
|
7
|
+
function config(ctx) {
|
|
8
|
+
try { return JSON.parse(readFileSync(join(ctx.home, ".agent-bus", "config.json"), "utf8")); }
|
|
9
|
+
catch { return {}; }
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function sessionIds(ctx, rows, agents) {
|
|
13
|
+
const result = new Map();
|
|
14
|
+
const file = join(ctx.home, ".agent-bus", "orch-sessions.txt");
|
|
15
|
+
if (!existsSync(file)) return result;
|
|
16
|
+
for (const line of readFileSync(file, "utf8").split("\n")) {
|
|
17
|
+
const [project, id] = line.split("\t");
|
|
18
|
+
if (project && id) result.set(project, id);
|
|
19
|
+
}
|
|
20
|
+
const paneProject = new Map(rows.filter(row => row.kind === "orch").map(row => [row.handle, row.project]));
|
|
21
|
+
for (const agent of agents) {
|
|
22
|
+
const project = paneProject.get(agent.pane_id);
|
|
23
|
+
const nativeId = agent.agent_session?.value;
|
|
24
|
+
if (project && nativeId) result.set(project, nativeId);
|
|
25
|
+
}
|
|
26
|
+
return result;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function restoreCandidates({ rows, configured, frozen = [], dismissed = [], sessions = new Map(), live = new Set() }) {
|
|
30
|
+
const projects = [...new Set(rows.filter(row => row.kind === "orch").map(row => row.project))];
|
|
31
|
+
return projects.filter(project => configured.includes(project)
|
|
32
|
+
&& !frozen.includes(project)
|
|
33
|
+
&& !live.has(project)
|
|
34
|
+
&& !dismissed.some(item => item.project === project && item.sessionId === sessions.get(project)));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function dismissedSessions(ctx) {
|
|
38
|
+
try {
|
|
39
|
+
const value = JSON.parse(readFileSync(join(ctx.home, ".agent-bus", "config.json"), "utf8"));
|
|
40
|
+
return Array.isArray(value.dismissedSessions) ? value.dismissedSessions : [];
|
|
41
|
+
} catch { return []; }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function restoreOrchestrators(ctx, args = []) {
|
|
45
|
+
if (args[0] === "enable" || args[0] === "disable") {
|
|
46
|
+
const [action, project, extra] = args;
|
|
47
|
+
if (!project || extra) throw new Error("usage: trantor restore enable|disable <project>");
|
|
48
|
+
const cfg = config(ctx);
|
|
49
|
+
const set = new Set(Array.isArray(cfg.resumeOnRestore) ? cfg.resumeOnRestore : []);
|
|
50
|
+
if (action === "enable") set.add(project); else set.delete(project);
|
|
51
|
+
cfg.resumeOnRestore = [...set].sort();
|
|
52
|
+
const file = join(ctx.home, ".agent-bus", "config.json");
|
|
53
|
+
mkdirSync(join(ctx.home, ".agent-bus"), { recursive: true });
|
|
54
|
+
const tmp = `${file}.tmp`;
|
|
55
|
+
writeFileSync(tmp, `${JSON.stringify(cfg, null, 2)}\n`);
|
|
56
|
+
renameSync(tmp, file);
|
|
57
|
+
console.log(`${project} ${action}d for Trantor restore`);
|
|
58
|
+
return 0;
|
|
59
|
+
}
|
|
60
|
+
const unknown = args.filter(arg => arg !== "--dry-run");
|
|
61
|
+
if (unknown.length) throw new Error("usage: trantor restore [--dry-run]");
|
|
62
|
+
if (args.includes("--dry-run")) ctx.dry = true;
|
|
63
|
+
if (!ctx.have.herdr) throw new Error("trantor restore needs herdr");
|
|
64
|
+
const cfg = config(ctx);
|
|
65
|
+
const configured = Array.isArray(cfg.resumeOnRestore) ? cfg.resumeOnRestore : [];
|
|
66
|
+
const frozen = Array.isArray(cfg.frozenProjects) ? cfg.frozenProjects : [];
|
|
67
|
+
const rows = readRows(ctx);
|
|
68
|
+
const parsed = parseJsonOutput(herdrCall(ctx, ["agent", "list"]).stdout);
|
|
69
|
+
const agents = parsed?.result?.agents || parsed?.agents || [];
|
|
70
|
+
const sessions = sessionIds(ctx, rows, agents);
|
|
71
|
+
const livePanes = new Set(agents.map(agent => agent.pane_id).filter(Boolean));
|
|
72
|
+
const live = new Set(rows.filter(row => row.kind === "orch" && livePanes.has(row.handle) && paneAlive(ctx, row.handle) && paneHasAgent(ctx, row.handle)).map(row => row.project));
|
|
73
|
+
const selected = restoreCandidates({ rows, configured, frozen, dismissed: dismissedSessions(ctx), sessions, live });
|
|
74
|
+
if (!selected.length) {
|
|
75
|
+
console.log("no configured interrupted orchestrators to restore (use trantor restore enable <project>)");
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
for (const project of selected) {
|
|
79
|
+
if (ctx.dry) console.log(`would restore ${project}`);
|
|
80
|
+
else {
|
|
81
|
+
const result = call(process.execPath, [join(ctx.root, "bin/crew.mjs"), "open", project], { env: ctx.env });
|
|
82
|
+
if (!result.ok) throw new Error(`trantor restore: ${project} failed: ${result.stderr || result.stdout}`);
|
|
83
|
+
console.log(`restored ${project}`);
|
|
84
|
+
}
|
|
85
|
+
if (!ctx.dry) await new Promise(resolve => setTimeout(resolve, 1000));
|
|
86
|
+
}
|
|
87
|
+
return 0;
|
|
88
|
+
}
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -17,6 +17,7 @@ import { signedHeaders } from "../lib/signed-fetch.mjs";
|
|
|
17
17
|
import { ensureEnrolled } from "../lib/enroll.mjs";
|
|
18
18
|
import { redactKeys } from "../lib/redact.mjs";
|
|
19
19
|
import { writeTurnState } from "../lib/turnstate.mjs";
|
|
20
|
+
import { completeTurnRow, isTurnRow, shipTurnRows } from "../lib/telemetry-ship.mjs";
|
|
20
21
|
import { alignSeatWorktree, applyWorktreeDeclaration, ensureSeatWorktree, provisioningLines, readWorktreeDeclaration } from "../lib/seat-worktree.mjs";
|
|
21
22
|
import {
|
|
22
23
|
AUTH_MARKER_RE, classifyFailure, looksLikeAuthDeath,
|
|
@@ -36,7 +37,7 @@ import {
|
|
|
36
37
|
import { snapshotBeforeCut } from "./cut-snapshot.mjs";
|
|
37
38
|
import { ocTurnUsage, dshTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput } from "../lib/turn-usage.mjs";
|
|
38
39
|
import { capConfig, capDecision, capHandoffPrompt, capPointerLine, capExhaustedNote } from "../lib/context-cap.mjs";
|
|
39
|
-
import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
|
|
40
|
+
import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatPermissionOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
|
|
40
41
|
import { seatSignalPrefix } from "../lib/seat-signal-guard.mjs";
|
|
41
42
|
import { providerMismatch } from "../lib/seat-provider.mjs";
|
|
42
43
|
import { burnCeiling, afterTurn, burnVerdict } from "../lib/burn-guard.mjs";
|
|
@@ -193,9 +194,18 @@ let TURN = releaseState?.turn || 0;
|
|
|
193
194
|
// fence assignments against this stamp — cards assigned before it are a predecessor's (#12138).
|
|
194
195
|
// Carried across the in-place release restart; a swap or a fresh `trantor up` stamps anew.
|
|
195
196
|
const BOOT_TS = releaseState?.bootTs || Date.now();
|
|
196
|
-
|
|
197
|
+
// #14067: the jsonl stays the write-ahead log; a TURN row is completed (id, v, machine, verdict
|
|
198
|
+
// cut) before it lands on disk, and every turn row drains to the hub right after it is written —
|
|
199
|
+
// never awaited, never able to fail the turn. Boot and text rows are recorded and never shipped.
|
|
200
|
+
const telemetry = (rec) => {
|
|
201
|
+
const row = isTurnRow(rec) ? completeTurnRow(rec, MACHINE_LABEL) : rec;
|
|
202
|
+
try { appendFileSync(join(LOGDIR, `${PERSONA}-${PROJ}.jsonl`), JSON.stringify(row) + "\n"); } catch {}
|
|
203
|
+
if (isTurnRow(rec)) void shipTurnRows({ persona: PERSONA, project: PROJ, hub: HUB, log, machine: MACHINE_LABEL });
|
|
204
|
+
};
|
|
197
205
|
// The boot line records the HUB this runner bound to, so a split-brain is diagnosable from disk.
|
|
198
206
|
telemetry({ ts: Date.now(), persona: PERSONA, agent: AGENT, project: PROJ, boot: true, hub: HUB, pid: process.pid, version: bootVersion });
|
|
207
|
+
// #14067: ship at boot too, so rows written while the hub was down go out without waiting for a turn.
|
|
208
|
+
void shipTurnRows({ persona: PERSONA, project: PROJ, hub: HUB, log, machine: MACHINE_LABEL });
|
|
199
209
|
// A seat can open a terminal window on a machine whose owner never asked for one and does not know
|
|
200
210
|
// what they are looking at. "◤ CLAUDE ◢ trantor crew · fleet" tells that person nothing: not what
|
|
201
211
|
// started, not what it will do, not how to stop it. RUNNER_TITLE names it in full and RUNNER_ABOUT
|
|
@@ -882,7 +892,10 @@ function capStepProcessed(sinceMs) {
|
|
|
882
892
|
const OC_COMPACTION_WINDOW = contextWindow(MODEL);
|
|
883
893
|
const OC_COMPACTION = ocCompactionContent(process.env, OC_COMPACTION_WINDOW);
|
|
884
894
|
// #11854: plus every non-relay MCP server of the user's opencode config switched off for the seat.
|
|
885
|
-
|
|
895
|
+
// #14048: and the heavy-gate shim folder, which this runner puts on the seat's PATH, made readable.
|
|
896
|
+
const OC_USER_CONFIG = readOpencodeUserConfig();
|
|
897
|
+
const HEAVY_SHIM_DIR = join(import.meta.dirname, "heavy-gate-shim");
|
|
898
|
+
const OC_SEAT_CONFIG = seatConfigContent(OC_COMPACTION, seatMcpOverlay(OC_USER_CONFIG), seatPermissionOverlay(HEAVY_SHIM_DIR, OC_USER_CONFIG));
|
|
886
899
|
|
|
887
900
|
let sid = releaseState?.sid || runnerOption("resume");
|
|
888
901
|
// #6206: the watchdog is DETACHED, so a runner that dies without ending it leaves an orphan
|
|
@@ -1100,6 +1113,7 @@ exit $turn_exit`;
|
|
|
1100
1113
|
// so a handoff spawn would only leak an unmanaged interactive window.
|
|
1101
1114
|
TRANTOR_NO_HANDOFF_SPAWN: "1", TRANTOR_NO_BATON_SPAWN: "1",
|
|
1102
1115
|
TRANTOR_HEAVY_GATE_WAIT_DIR: HEAVY_WAIT_DIR,
|
|
1116
|
+
// Spelled out here, not HEAVY_SHIM_DIR: the turn drills run this function alone, without the module's constants (#14048).
|
|
1103
1117
|
PATH: `${join(import.meta.dirname, "heavy-gate-shim")}:${process.env.PATH || ""}`,
|
|
1104
1118
|
// #6206: the seat's transcript dir — a real CLI ignores it, a drill's fake CLI writes
|
|
1105
1119
|
// its transcript lines there so the watchdog sees the liveness a real claude shows.
|
package/bin/crew.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { createCmuxAdapter, spawnCmux } from "./crew/cmux.mjs";
|
|
|
7
7
|
import { createHerdrAdapter, spawnHerdr } from "./crew/herdr.mjs";
|
|
8
8
|
import { resolveSpec, reportSkipped } from "./crew/models.mjs";
|
|
9
9
|
import { openOrchestrator } from "./crew/open.mjs";
|
|
10
|
+
import { restoreOrchestrators } from "./crew/restore.mjs";
|
|
10
11
|
import { performSwap, swapOptions, swapRuntime } from "./crew/swap.mjs";
|
|
11
12
|
import { redactKeys } from "../lib/redact.mjs";
|
|
12
13
|
import { reapSeat, down, prune, readRows } from "./crew/state.mjs";
|
|
@@ -39,7 +40,7 @@ const adapters = {
|
|
|
39
40
|
};
|
|
40
41
|
|
|
41
42
|
function usage() {
|
|
42
|
-
console.log("usage: crew.mjs up <agent...> | crew.mjs open [<project>] | crew.mjs swap <old> <new[:provider[/model]]> | crew.mjs down [<agent>...] [--all --yes] | crew.mjs prune");
|
|
43
|
+
console.log("usage: crew.mjs up <agent...> | crew.mjs open [<project>] | crew.mjs restore [--dry-run] | crew.mjs swap <old> <new[:provider[/model]]> | crew.mjs down [<agent>...] [--all --yes] | crew.mjs prune");
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
function parseUpArgs(args) {
|
|
@@ -150,6 +151,7 @@ try {
|
|
|
150
151
|
if (command === "down") code = await down(ctx, rawArgs, adapters);
|
|
151
152
|
else if (command === "prune") { prune(ctx, adapters); console.log(`— pruned dead crew rows (${ctx.statePath}) —`); }
|
|
152
153
|
else if (command === "open") code = openOrchestrator(ctx, rawArgs);
|
|
154
|
+
else if (command === "restore") code = await restoreOrchestrators(ctx, rawArgs);
|
|
153
155
|
else if (command === "swap") { result = await swap(rawArgs); code = result.ok ? 0 : 1; }
|
|
154
156
|
else if (command === "up") code = guardCrossProjectUp(ctx) ? await runUp(rawArgs) : 1;
|
|
155
157
|
else { usage(); code = 1; }
|
|
@@ -160,7 +162,9 @@ try {
|
|
|
160
162
|
if (!result) result = jsonResult(code);
|
|
161
163
|
if (!result.ok && !result.reason) result.reason = diagnostics.at(-1) || `${command} failed; see stderr`;
|
|
162
164
|
if (result.reason) result.reason = redactKeys(result.reason);
|
|
163
|
-
if (jsonMode)
|
|
164
|
-
|
|
165
|
+
if (jsonMode) {
|
|
166
|
+
if (!result.ok && result.reason) console.error(result.reason);
|
|
167
|
+
output(JSON.stringify(result));
|
|
168
|
+
} else if (result.reason) console.error(result.reason);
|
|
165
169
|
else if (command === "swap") console.log(`— swapped ${result.seat} → ${result.to}; moved contracts: ${result.moved.join(", ") || "none"} —`);
|
|
166
170
|
process.exit(code);
|
package/bin/doctor.mjs
CHANGED
|
@@ -178,6 +178,17 @@ section("duty seat (the fleet watcher)");
|
|
|
178
178
|
section("claude (the orchestrator)");
|
|
179
179
|
if (!has("claude")) warn("claude CLI not found", "install Claude Code: https://claude.com/claude-code");
|
|
180
180
|
else {
|
|
181
|
+
// Claude Code's version against Trantor's compatibility states (#14030), mirroring the
|
|
182
|
+
// Rust-owned table in desktop/src-tauri/src/agent_cli.rs — keep the two in step.
|
|
183
|
+
const raw = (() => { try { return execSync("claude --version", { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { return ""; } })();
|
|
184
|
+
const parts = (raw.split(/\s+/)[0] || "").replace(/^v/, "").split(".").map(Number);
|
|
185
|
+
const cmp = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
|
|
186
|
+
if (parts.length === 3 && parts.every(Number.isFinite)) {
|
|
187
|
+
const MIN = [2, 1, 215], VERIFIED = [2, 1, 326];
|
|
188
|
+
if (cmp(parts, MIN) < 0) warn(`claude ${raw} is older than Trantor has audited (${MIN.join(".")}); the Mode menu needs ${VERIFIED.join(".")}`, "claude update (Claude Code's own updater)");
|
|
189
|
+
else if (cmp(parts, VERIFIED) > 0) note(`claude ${raw} is newer than the releases Trantor has verified (up to ${VERIFIED.join(".")})`);
|
|
190
|
+
else ok(`claude ${raw} within the verified range (${MIN.join(".")}–${VERIFIED.join(".")})`);
|
|
191
|
+
} else if (raw) note(`claude version unreadable: ${raw}`);
|
|
181
192
|
const st = read(join(H, ".claude", "settings.json")) || {};
|
|
182
193
|
Object.keys(st.enabledPlugins || {}).some(k => k.startsWith("agent-bus@") || k.startsWith("trantor@"))
|
|
183
194
|
? ok("plugin installed")
|
package/bin/herdr-agent.mjs
CHANGED
|
@@ -1,23 +1,22 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Keep herdr
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
// window never costs you a session. A REBOOT does: the server dies with everything else, and
|
|
6
|
-
// nothing brings it back, so the next `trantor open` finds no workspace and starts over. That was
|
|
7
|
-
// the missing half of "it survives restarts" (card #5401).
|
|
8
|
-
//
|
|
9
|
-
// This is only the SERVER's lifetime. The conversation inside a pane is a separate problem, solved
|
|
10
|
-
// in crew.mjs: the project keeps one claude session id and `open` resumes it.
|
|
11
|
-
import { existsSync, writeFileSync, unlinkSync, mkdirSync } from "node:fs";
|
|
2
|
+
// Keep herdr alive across reboot; Trantor restores opted-in orchestrators after its server returns.
|
|
3
|
+
// Server lifetime and conversation restore are separate: `trantor open` resumes the project session.
|
|
4
|
+
import { existsSync, writeFileSync, unlinkSync, mkdirSync, chmodSync, readFileSync } from "node:fs";
|
|
12
5
|
import { execFileSync } from "node:child_process";
|
|
13
6
|
import { homedir } from "node:os";
|
|
14
7
|
import { join, dirname } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
15
9
|
|
|
16
10
|
const LABEL = "com.trantor.herdr";
|
|
17
11
|
const PLIST = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
18
12
|
const LOG = "/tmp/trantor-herdr-server.log";
|
|
13
|
+
const RESTORE_LOG = "/tmp/trantor-herdr-restore.log";
|
|
14
|
+
const RESTORE_SCRIPT = join(homedir(), "Library", "LaunchAgents", "trantor-herdr-restore.sh");
|
|
19
15
|
const D = "\x1b[2m", R = "\x1b[0m";
|
|
20
16
|
|
|
17
|
+
const shellQuote = value => `'${String(value).replaceAll("'", `'\\''`)}'`;
|
|
18
|
+
const xmlEscape = value => String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
19
|
+
|
|
21
20
|
function herdrBin() {
|
|
22
21
|
// launchd runs with a minimal PATH, so the absolute path has to be baked in at install time.
|
|
23
22
|
for (const p of [join(homedir(), ".local/bin/herdr"), "/opt/homebrew/bin/herdr", "/usr/local/bin/herdr"]) {
|
|
@@ -30,7 +29,46 @@ function herdrBin() {
|
|
|
30
29
|
return "";
|
|
31
30
|
}
|
|
32
31
|
|
|
33
|
-
|
|
32
|
+
export function restoreScriptBody({ herdr = "herdr", node = process.execPath, cli = join(dirname(fileURLToPath(import.meta.url)), "cli.mjs"), log = RESTORE_LOG } = {}) {
|
|
33
|
+
return `#!/bin/bash
|
|
34
|
+
HERDR_BIN=\${TRANTOR_HERDR_BIN:-${shellQuote(herdr)}}
|
|
35
|
+
NODE_BIN=\${TRANTOR_NODE_BIN:-${shellQuote(node)}}
|
|
36
|
+
TRANTOR_CLI=\${TRANTOR_CLI_PATH:-${shellQuote(cli)}}
|
|
37
|
+
RESTORE_LOG=\${TRANTOR_RESTORE_LOG:-${shellQuote(log)}}
|
|
38
|
+
MARKER_DIR=\${TRANTOR_RESTORE_MARKER_DIR:-/tmp}
|
|
39
|
+
BOOT_KEY=\${TRANTOR_RESTORE_BOOT_KEY:-$(/usr/sbin/sysctl -n kern.boottime 2>/dev/null | sed -E 's/.*sec = ([0-9]+).*/\\1/')}
|
|
40
|
+
WAIT_SECONDS=\${TRANTOR_RESTORE_WAIT_SECONDS:-60}
|
|
41
|
+
SLEEP_SECONDS=\${TRANTOR_RESTORE_SLEEP_SECONDS:-1}
|
|
42
|
+
|
|
43
|
+
if [[ ! "$BOOT_KEY" =~ ^[0-9]+$ ]]; then
|
|
44
|
+
echo "$(date -u '+%FT%TZ') herdr restore skipped: could not determine boot time" >> "$RESTORE_LOG"
|
|
45
|
+
exit 0
|
|
46
|
+
fi
|
|
47
|
+
MARKER="$MARKER_DIR/trantor-herdr-restore-$BOOT_KEY.done"
|
|
48
|
+
if [ -d "$MARKER" ]; then exit 0; fi
|
|
49
|
+
|
|
50
|
+
elapsed=0
|
|
51
|
+
while [ "$elapsed" -lt "$WAIT_SECONDS" ]; do
|
|
52
|
+
if "$HERDR_BIN" status 2>/dev/null | grep -q 'status: running'; then
|
|
53
|
+
if mkdir "$MARKER" 2>/dev/null; then
|
|
54
|
+
echo "$(date -u '+%FT%TZ') herdr is running; restoring opted-in Trantor orchestrators" >> "$RESTORE_LOG"
|
|
55
|
+
"$NODE_BIN" "$TRANTOR_CLI" restore >> "$RESTORE_LOG" 2>&1
|
|
56
|
+
result=$?
|
|
57
|
+
echo "$(date -u '+%FT%TZ') trantor restore exited $result" >> "$RESTORE_LOG"
|
|
58
|
+
fi
|
|
59
|
+
exit 0
|
|
60
|
+
fi
|
|
61
|
+
sleep "$SLEEP_SECONDS"
|
|
62
|
+
elapsed=$((elapsed + 1))
|
|
63
|
+
done
|
|
64
|
+
echo "$(date -u '+%FT%TZ') herdr did not answer status within $WAIT_SECONDS seconds; restore skipped" >> "$RESTORE_LOG"
|
|
65
|
+
exit 0
|
|
66
|
+
`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function plistBody(bin, restoreScript = RESTORE_SCRIPT) {
|
|
70
|
+
const launch = xmlEscape(`/bin/bash ${shellQuote(restoreScript)} >/dev/null 2>&1 & ${shellQuote(bin)} status 2>/dev/null | grep -q 'status: running' && exit 0; exec ${shellQuote(bin)} server`);
|
|
71
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
34
72
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
35
73
|
<plist version="1.0">
|
|
36
74
|
<dict>
|
|
@@ -42,7 +80,7 @@ const plistBody = (bin) => `<?xml version="1.0" encoding="UTF-8"?>
|
|
|
42
80
|
<!-- Idempotent on purpose. A second herdr server against a live one prints "already running"
|
|
43
81
|
and exits 1, so a plain KeepAlive would respawn it every 10s forever. Bail out cleanly
|
|
44
82
|
instead, and only exec when nothing is holding the socket. -->
|
|
45
|
-
<string>${
|
|
83
|
+
<string>${launch}</string>
|
|
46
84
|
</array>
|
|
47
85
|
<key>RunAtLoad</key><true/>
|
|
48
86
|
<!-- Restart a server that DIED, never one that stopped cleanly (herdr server stop) or one that
|
|
@@ -53,7 +91,15 @@ const plistBody = (bin) => `<?xml version="1.0" encoding="UTF-8"?>
|
|
|
53
91
|
</dict>
|
|
54
92
|
</plist>
|
|
55
93
|
`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function restoreWired(plist, script) {
|
|
97
|
+
return String(plist || "").includes("trantor-herdr-restore.sh")
|
|
98
|
+
&& String(script || "").includes("restore >> \"$RESTORE_LOG\"")
|
|
99
|
+
&& String(script || "").includes("trantor-herdr-restore-$BOOT_KEY.done");
|
|
100
|
+
}
|
|
56
101
|
|
|
102
|
+
function main() {
|
|
57
103
|
const cmd = process.argv[2] || "status";
|
|
58
104
|
const uid = process.getuid();
|
|
59
105
|
|
|
@@ -64,6 +110,8 @@ if (cmd === "install") {
|
|
|
64
110
|
process.exit(1);
|
|
65
111
|
}
|
|
66
112
|
mkdirSync(dirname(PLIST), { recursive: true });
|
|
113
|
+
writeFileSync(RESTORE_SCRIPT, restoreScriptBody({ herdr: bin }));
|
|
114
|
+
chmodSync(RESTORE_SCRIPT, 0o755);
|
|
67
115
|
writeFileSync(PLIST, plistBody(bin));
|
|
68
116
|
// bootout first so a re-install replaces rather than stacks
|
|
69
117
|
try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
|
|
@@ -74,7 +122,7 @@ if (cmd === "install") {
|
|
|
74
122
|
process.exit(1);
|
|
75
123
|
}
|
|
76
124
|
console.log(`herdr's server now starts at login (${bin} server)`);
|
|
77
|
-
console.log(`${D}plist: ${PLIST} log: ${LOG}${R}`);
|
|
125
|
+
console.log(`${D}plist: ${PLIST} log: ${LOG} restore log: ${RESTORE_LOG}${R}`);
|
|
78
126
|
} else if (cmd === "remove") {
|
|
79
127
|
try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
|
|
80
128
|
if (existsSync(PLIST)) { unlinkSync(PLIST); console.log("removed the herdr login agent"); }
|
|
@@ -87,10 +135,16 @@ if (cmd === "install") {
|
|
|
87
135
|
} catch { /* launchctl unavailable */ }
|
|
88
136
|
let running = false;
|
|
89
137
|
try { running = /status:\s*running/.test(execFileSync(herdrBin() || "herdr", ["status"], { encoding: "utf8" })); } catch { /* server down */ }
|
|
138
|
+
let wired = false;
|
|
139
|
+
try { wired = restoreWired(readFileSync(PLIST, "utf8"), readFileSync(RESTORE_SCRIPT, "utf8")); } catch { /* missing helper */ }
|
|
90
140
|
console.log(`login agent: ${installed ? "installed" : "not installed"}${installed ? ` (${loaded ? "loaded" : "NOT loaded"})` : ""}`);
|
|
91
141
|
console.log(`herdr server: ${running ? "running" : "not running"}`);
|
|
142
|
+
console.log(`Trantor restore: ${wired ? "wired after herdr starts" : "not wired"}`);
|
|
92
143
|
if (!installed) console.log(`${D}install it so panes survive a reboot: trantor herdr install${R}`);
|
|
93
144
|
} else {
|
|
94
145
|
console.log("usage: trantor herdr install | remove | status");
|
|
95
146
|
process.exit(1);
|
|
96
147
|
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) main();
|
package/hub/routes/insights.mjs
CHANGED
|
@@ -6,6 +6,32 @@ import { join } from "node:path";
|
|
|
6
6
|
let ledgerCache = { mtimeMs: -1, rows: [] };
|
|
7
7
|
let telemetryCache = { maxMtimeMs: -1, turns: [] };
|
|
8
8
|
const LOGDIR = join(homedir(), ".agent-bus", "logs");
|
|
9
|
+
const TURN_OUTCOMES = new Set(["completed", "asked", "blocked", "no-delivery", "empty", "stalled", "cut", "rejected", "api-error"]);
|
|
10
|
+
const stringWithin = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
11
|
+
const safeInteger = (value, min = 0) => Number.isSafeInteger(value) && value >= min;
|
|
12
|
+
const optionalBoolean = (row, key) => row[key] === undefined || typeof row[key] === "boolean";
|
|
13
|
+
|
|
14
|
+
function validTurnRow(row, nowMs) {
|
|
15
|
+
if (!row || typeof row !== "object" || Array.isArray(row)) return null;
|
|
16
|
+
if ("prompt" in row || "output" in row || "text" in row) return null;
|
|
17
|
+
if (typeof row.id !== "string" || !/^[0-9a-f]{32}$/i.test(row.id) || row.v !== 1) return null;
|
|
18
|
+
if (!safeInteger(row.ts, 1) || row.ts > nowMs + 60000 || !safeInteger(row.turn, 1)) return null;
|
|
19
|
+
if (!stringWithin(row.persona, 120) || !stringWithin(row.agent, 80) || !stringWithin(row.project, 80)) return null;
|
|
20
|
+
// A machine with no label configured reports "" (lib/machine-label.mjs): that is a valid row, not a dropped one.
|
|
21
|
+
if (typeof row.machine !== "string" || row.machine.length > 120) return null;
|
|
22
|
+
if (!stringWithin(row.trigger, 120) || !stringWithin(row.model, 200)) return null;
|
|
23
|
+
if (!safeInteger(row.card) || !safeInteger(row.duration_ms)) return null;
|
|
24
|
+
if (!(row.tokens === null || safeInteger(row.tokens))) return null;
|
|
25
|
+
if (!(row.exit === null || Number.isInteger(row.exit)) || !(row.effExit === null || Number.isInteger(row.effExit))) return null;
|
|
26
|
+
if (!TURN_OUTCOMES.has(row.outcome) || typeof row.verdict !== "string") return null;
|
|
27
|
+
if (row.usage !== undefined && (!row.usage || typeof row.usage !== "object" || Array.isArray(row.usage))) return null;
|
|
28
|
+
if (row.containers !== undefined && (!Array.isArray(row.containers) || row.containers.length > 100 || row.containers.some(name => !stringWithin(name, 200)))) return null;
|
|
29
|
+
if (!["cut", "stalled", "authFailed", "emptyOutput", "emptyTurn"].every(key => optionalBoolean(row, key))) return null;
|
|
30
|
+
if (row.cutSignal !== undefined && (typeof row.cutSignal !== "string" || row.cutSignal.length > 80)) return null;
|
|
31
|
+
if (row.extensions !== undefined && !safeInteger(row.extensions)) return null;
|
|
32
|
+
if (row.boxMs !== undefined && !safeInteger(row.boxMs)) return null;
|
|
33
|
+
return { ...row, id: row.id.toLowerCase(), verdict: row.verdict.slice(0, 600) };
|
|
34
|
+
}
|
|
9
35
|
|
|
10
36
|
function scanTelemetry() {
|
|
11
37
|
let files = [];
|
|
@@ -25,8 +51,31 @@ function scanTelemetry() {
|
|
|
25
51
|
return turns;
|
|
26
52
|
}
|
|
27
53
|
|
|
28
|
-
export async function routeInsights({ res, q, P, req, ctx }) {
|
|
29
|
-
const { state, json, canon, now } = ctx;
|
|
54
|
+
export async function routeInsights({ res, q, P, req, auth, ctx }) {
|
|
55
|
+
const { state, json, canon, now, body, scopeAllows, turnTelemetry, AUTH_MODE } = ctx;
|
|
56
|
+
if (req.method === "POST" && P === "/telemetry/turns") {
|
|
57
|
+
const b = await body(req);
|
|
58
|
+
if (!Array.isArray(b?.rows)) return json(res, 400, { error: "rows array required" });
|
|
59
|
+
if (b.rows.length > 100) return json(res, 400, { error: "at most 100 rows per request" });
|
|
60
|
+
const rows = [];
|
|
61
|
+
let dropped = 0;
|
|
62
|
+
for (const candidate of b.rows) {
|
|
63
|
+
const row = validTurnRow(candidate, now());
|
|
64
|
+
if (row) rows.push(row); else dropped++;
|
|
65
|
+
}
|
|
66
|
+
const owner = scopeAllows(auth?.identity, "", "owner");
|
|
67
|
+
if (AUTH_MODE !== "off" && !owner && rows.some(row => auth?.identity?.name !== `${row.persona}:${row.project}`)) {
|
|
68
|
+
return json(res, 403, { error: "turn rows must name the signing seat" });
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const result = await turnTelemetry.append(rows);
|
|
72
|
+
return json(res, 200, { ok: true, stored: result.stored, duplicates: result.duplicates, dropped });
|
|
73
|
+
} catch (error) {
|
|
74
|
+
const reason = String(error?.message || error);
|
|
75
|
+
process.stderr.write(`[trantor] turn telemetry store failed: ${reason}\n`);
|
|
76
|
+
return json(res, 500, { error: `turn telemetry store failed: ${reason}` });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
30
79
|
if (req.method === "GET" && P === "/economics") { // the brain's books, surfaced: scrooge ledger + quota profile
|
|
31
80
|
const out = { scrooge: null, lifetime: null, profile: null };
|
|
32
81
|
try { out.profile = JSON.parse(readFileSync(join(homedir(), ".agent-bus", "profile.json"), "utf8")).providers || {}; } catch {}
|
package/hub/routes/messages.mjs
CHANGED
|
@@ -9,7 +9,7 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
|
|
|
9
9
|
appendEvent, appendCardEvent, appendTaskLog, markDelivered, contractsFor, canUseInboxSession, inboxWindow,
|
|
10
10
|
deliverable, inboxReadable, inboxResponse, filterReadable, canRead, streams, UI,
|
|
11
11
|
AUTH_MODE, persistHealth, duty, now, markDirty, assertNoSecrets, PEER_TTL_MS,
|
|
12
|
-
CONTRACT_WINDOW_MS, PUBLIC_URL,
|
|
12
|
+
CONTRACT_WINDOW_MS, PUBLIC_URL, turnTelemetry,
|
|
13
13
|
} = ctx;
|
|
14
14
|
if (req.method === "POST" && P === "/send") {
|
|
15
15
|
const b = await body(req);
|
|
@@ -175,6 +175,7 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
|
|
|
175
175
|
// #8723: the count is a listing in aggregate — memory rows (past PEER_TTL_MS) never count.
|
|
176
176
|
if (P === "/health") return json(res, 200, { ok: true, authMode: AUTH_MODE, peers: Object.values(state.peers).filter(v => (v.lastSeen || 0) >= now() - PEER_TTL_MS).length, messages: state.messages.length, streams: streams.length,
|
|
177
177
|
persist: persistHealth.view(),
|
|
178
|
+
telemetry: turnTelemetry.health(),
|
|
178
179
|
// v1.4: the public front door, empty when RELAY_PUBLIC_URL is unset — pairing hands it out.
|
|
179
180
|
publicUrl: PUBLIC_URL,
|
|
180
181
|
// #5686: duty liveness rides /health so the app's Home strip and doctor read one truth.
|
package/hub/routes/session.mjs
CHANGED
|
@@ -17,7 +17,7 @@ const CLAIM_TTL_MS = 300000;
|
|
|
17
17
|
const PROMPT_SWEEP_MS = Number(process.env.RELAY_PROMPT_SWEEP_MS || 30000);
|
|
18
18
|
const EXPIRED_REASON = "No Mac is relaying this project. Is the Trantor app open?";
|
|
19
19
|
const CLAIMED_EXPIRED_REASON = "The Mac claimed this prompt but never delivered it. Try sending it again.";
|
|
20
|
-
const ACK_OUTCOMES = new Set(["delivered", "blocked", "not_ready", "stalled", "no_agent", "stale"]);
|
|
20
|
+
const ACK_OUTCOMES = new Set(["delivered", "sent", "blocked", "not_ready", "stalled", "no_agent", "stale"]);
|
|
21
21
|
const ANSWER_PICKS_MAX = 10;
|
|
22
22
|
const ANSWER_OTHER_MAX = 2000;
|
|
23
23
|
const ANSWER_ENTRIES_MAX = 4; // CC's question limit per ask (#12912)
|
|
@@ -524,8 +524,15 @@ function pruneMachinesHealth() {
|
|
|
524
524
|
if (p.kind === "crew") {
|
|
525
525
|
p.output = stripAnsi(String(b.output || "")).slice(-CREW_OUTPUT_MAX);
|
|
526
526
|
p.status = outcome; // "done" or "failed"
|
|
527
|
+
} else if (outcome === "delivered") {
|
|
528
|
+
p.status = "delivered";
|
|
529
|
+
} else if (outcome === "sent") {
|
|
530
|
+
// #13913: herdr typed the text and Enter but the session has not picked it up. Terminal
|
|
531
|
+
// for claiming (never re-claimed, never re-typed); phones keep it queued until the
|
|
532
|
+
// transcript itself shows the turn.
|
|
533
|
+
p.status = "sent";
|
|
527
534
|
} else {
|
|
528
|
-
p.status =
|
|
535
|
+
p.status = "failed";
|
|
529
536
|
}
|
|
530
537
|
// A terminal row will never be claimed or downloaded again: its bytes go now.
|
|
531
538
|
unlinkAttachments(p);
|
package/hub/store.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: State normalization is the persisted-data boundary; these checks preserve the legacy decoder byte-for-byte during a structural-only split. */
|
|
2
|
-
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
4
5
|
import { createPersistHealth } from "../lib/persist-health.mjs";
|
|
5
6
|
import { DEFAULT_ORG } from "../lib/store-contract.mjs";
|
|
6
7
|
|
|
@@ -177,6 +178,136 @@ if (STORE_KIND === "pg" || STORE_KIND === "postgres") {
|
|
|
177
178
|
if (existsSync(DATA)) state = normalizeState(JSON.parse(readFileSync(DATA, "utf8")));
|
|
178
179
|
} catch {}
|
|
179
180
|
}
|
|
181
|
+
|
|
182
|
+
const TURNS_FILE = join(dirname(DATA), "turns.jsonl");
|
|
183
|
+
const TURN_RETENTION_MS = 180 * 86400000;
|
|
184
|
+
const turnRows = new Map();
|
|
185
|
+
const dailyTurns = new Map();
|
|
186
|
+
let recentTurnTs = [];
|
|
187
|
+
let lastTurnTs = null;
|
|
188
|
+
const successfulOutcomes = new Set(["completed", "asked", "blocked"]);
|
|
189
|
+
const turnDay = ts => new Date(ts).toISOString().slice(0, 10);
|
|
190
|
+
function addTurnToTotals(row) {
|
|
191
|
+
const day = turnDay(row.ts);
|
|
192
|
+
const projects = dailyTurns.get(day) || new Map();
|
|
193
|
+
const agents = projects.get(row.project) || new Map();
|
|
194
|
+
const total = agents.get(row.agent) || { day, project: row.project, agent: row.agent, turns: 0, failed: 0, outcomes: {}, models: new Set(), lastFailure: null };
|
|
195
|
+
total.turns++;
|
|
196
|
+
total.outcomes[row.outcome] = (total.outcomes[row.outcome] || 0) + 1;
|
|
197
|
+
if (row.model) total.models.add(row.model);
|
|
198
|
+
if (!successfulOutcomes.has(row.outcome)) {
|
|
199
|
+
total.failed++;
|
|
200
|
+
if (!total.lastFailure || row.ts > total.lastFailure.ts) {
|
|
201
|
+
total.lastFailure = { ts: row.ts, outcome: row.outcome, model: row.model, exit: row.exit, card: row.card };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
agents.set(row.agent, total);
|
|
205
|
+
projects.set(row.project, agents);
|
|
206
|
+
dailyTurns.set(day, projects);
|
|
207
|
+
}
|
|
208
|
+
function rebuildTurnTotals() {
|
|
209
|
+
dailyTurns.clear();
|
|
210
|
+
recentTurnTs = [...turnRows.values()].map(row => row.ts).sort((a, b) => a - b);
|
|
211
|
+
lastTurnTs = recentTurnTs.at(-1) ?? null;
|
|
212
|
+
for (const row of turnRows.values()) addTurnToTotals(row);
|
|
213
|
+
}
|
|
214
|
+
function compactTurnFile(rows) {
|
|
215
|
+
const tmp = `${TURNS_FILE}.${process.pid}.tmp`;
|
|
216
|
+
writeFileSync(tmp, rows.map(row => JSON.stringify(row)).join("\n") + (rows.length ? "\n" : ""));
|
|
217
|
+
renameSync(tmp, TURNS_FILE);
|
|
218
|
+
}
|
|
219
|
+
const bootTurnCutoff = Date.now() - TURN_RETENTION_MS;
|
|
220
|
+
if (durableStore) {
|
|
221
|
+
await durableStore.pruneTurns(ORG_ID, bootTurnCutoff);
|
|
222
|
+
for (const row of await durableStore.loadTurns(ORG_ID, bootTurnCutoff)) turnRows.set(row.id, row);
|
|
223
|
+
} else if (existsSync(TURNS_FILE)) {
|
|
224
|
+
let source = null;
|
|
225
|
+
try { source = readFileSync(TURNS_FILE, "utf8"); } catch {}
|
|
226
|
+
if (source !== null) {
|
|
227
|
+
for (const line of source.split("\n")) {
|
|
228
|
+
if (!line) continue;
|
|
229
|
+
try {
|
|
230
|
+
const row = JSON.parse(line);
|
|
231
|
+
if (row && typeof row.id === "string" && Number.isFinite(row.ts) && row.ts >= bootTurnCutoff) turnRows.set(row.id, row);
|
|
232
|
+
} catch {}
|
|
233
|
+
}
|
|
234
|
+
compactTurnFile([...turnRows.values()]);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
rebuildTurnTotals();
|
|
238
|
+
function trackTurn(row) {
|
|
239
|
+
turnRows.set(row.id, row);
|
|
240
|
+
addTurnToTotals(row);
|
|
241
|
+
let lo = 0, hi = recentTurnTs.length;
|
|
242
|
+
while (lo < hi) {
|
|
243
|
+
const mid = (lo + hi) >> 1;
|
|
244
|
+
if (recentTurnTs[mid] <= row.ts) lo = mid + 1; else hi = mid;
|
|
245
|
+
}
|
|
246
|
+
recentTurnTs.splice(lo, 0, row.ts);
|
|
247
|
+
lastTurnTs = Math.max(lastTurnTs ?? 0, row.ts);
|
|
248
|
+
}
|
|
249
|
+
async function appendTurns(rows) {
|
|
250
|
+
let storedRows, duplicates;
|
|
251
|
+
if (durableStore) {
|
|
252
|
+
({ storedRows, duplicates } = await durableStore.appendTurns(ORG_ID, rows));
|
|
253
|
+
} else {
|
|
254
|
+
storedRows = rows.filter(row => !turnRows.has(row.id));
|
|
255
|
+
duplicates = rows.length - storedRows.length;
|
|
256
|
+
const unique = [];
|
|
257
|
+
const seen = new Set();
|
|
258
|
+
for (const row of storedRows) {
|
|
259
|
+
if (seen.has(row.id)) continue;
|
|
260
|
+
seen.add(row.id);
|
|
261
|
+
unique.push(row);
|
|
262
|
+
}
|
|
263
|
+
duplicates += storedRows.length - unique.length;
|
|
264
|
+
storedRows = unique;
|
|
265
|
+
if (storedRows.length) appendFileSync(TURNS_FILE, storedRows.map(row => JSON.stringify(row)).join("\n") + "\n");
|
|
266
|
+
}
|
|
267
|
+
for (const row of storedRows) trackTurn(row);
|
|
268
|
+
return { stored: storedRows.length, duplicates };
|
|
269
|
+
}
|
|
270
|
+
async function pruneTurns(olderThanMs = Date.now() - TURN_RETENTION_MS) {
|
|
271
|
+
const cutoff = Number(olderThanMs);
|
|
272
|
+
if (durableStore) await durableStore.pruneTurns(ORG_ID, cutoff);
|
|
273
|
+
for (const [id, row] of turnRows) if (row.ts < cutoff) turnRows.delete(id);
|
|
274
|
+
if (!durableStore) compactTurnFile([...turnRows.values()]);
|
|
275
|
+
rebuildTurnTotals();
|
|
276
|
+
}
|
|
277
|
+
const readTurnTotals = () => [...dailyTurns.values()].flatMap(projects =>
|
|
278
|
+
[...projects.values()].flatMap(agents => [...agents.values()].map(total => ({
|
|
279
|
+
day: total.day,
|
|
280
|
+
project: total.project,
|
|
281
|
+
agent: total.agent,
|
|
282
|
+
turns: total.turns,
|
|
283
|
+
failed: total.failed,
|
|
284
|
+
outcomes: { ...total.outcomes },
|
|
285
|
+
models: [...total.models].sort(),
|
|
286
|
+
lastFailure: total.lastFailure ? { ...total.lastFailure } : null,
|
|
287
|
+
}))));
|
|
288
|
+
function turnHealth() {
|
|
289
|
+
const cutoff = Date.now() - 86400000;
|
|
290
|
+
let lo = 0, hi = recentTurnTs.length;
|
|
291
|
+
while (lo < hi) {
|
|
292
|
+
const mid = (lo + hi) >> 1;
|
|
293
|
+
if (recentTurnTs[mid] < cutoff) lo = mid + 1; else hi = mid;
|
|
294
|
+
}
|
|
295
|
+
return { lastRowTs: lastTurnTs, rows24h: recentTurnTs.length - lo };
|
|
296
|
+
}
|
|
297
|
+
let retentionError = "";
|
|
298
|
+
const retentionTimer = setInterval(async () => {
|
|
299
|
+
try {
|
|
300
|
+
await pruneTurns();
|
|
301
|
+
retentionError = "";
|
|
302
|
+
} catch (error) {
|
|
303
|
+
const message = String(error?.message || error);
|
|
304
|
+
if (message !== retentionError) process.stderr.write(`[trantor] turn retention failed: ${message}\n`);
|
|
305
|
+
retentionError = message;
|
|
306
|
+
}
|
|
307
|
+
}, 86400000);
|
|
308
|
+
retentionTimer.unref?.();
|
|
309
|
+
const turnTelemetry = { append: appendTurns, prune: pruneTurns, readTotals: readTurnTotals, health: turnHealth };
|
|
310
|
+
|
|
180
311
|
let dirty = false;
|
|
181
312
|
// Persist the unified log under `events`, AND mirror the card-only subset under the legacy
|
|
182
313
|
// `cardEvents` key — so downgrading to a pre-0.17.54 hub still boots with its full TIMELINE
|
|
@@ -296,6 +427,6 @@ setInterval(persist, persistTickMs).unref?.();
|
|
|
296
427
|
|
|
297
428
|
return {
|
|
298
429
|
state, durableStore, persist, persistHealth, markDirty, copyTask, copyMessage, reload, startChangeSubscription,
|
|
299
|
-
HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
|
|
430
|
+
turnTelemetry, HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
|
|
300
431
|
};
|
|
301
432
|
}
|
package/lib/balances.mjs
CHANGED
|
@@ -144,7 +144,12 @@ export const ADAPTERS = [
|
|
|
144
144
|
const left = num(w?.detail?.remaining), limit = num(w?.detail?.limit);
|
|
145
145
|
const remainingPct = limit > 0 && left != null ? Math.round(left / limit * 100) : null;
|
|
146
146
|
const hours = windowMinutes(w) / 60;
|
|
147
|
-
|
|
147
|
+
// #14055 — a null remainingPct still names WHY: the app chip's "usage unread" tooltip and
|
|
148
|
+
// the CLI line (fmtBalance) carry this detail instead of a bare unread with no reason.
|
|
149
|
+
const unreadWhy = !w ? "no usage window in the limits answer"
|
|
150
|
+
: left == null ? "no remaining figure in the usage window"
|
|
151
|
+
: "no usable limit figure in the usage window";
|
|
152
|
+
const detail = remainingPct == null ? `usage unread: ${unreadWhy}` : `${remainingPct}% left in ${Math.round(hours)}h window`;
|
|
148
153
|
const plan = (j.user?.membership?.level || "").replace("LEVEL_", "").toLowerCase() || "coding";
|
|
149
154
|
return { remainingPct, plan, resetTime: w?.detail?.resetTime || j.usage?.resetTime || null, detail };
|
|
150
155
|
},
|
package/lib/seat-compaction.mjs
CHANGED
|
@@ -80,12 +80,34 @@ export function seatMcpOverlay(userConfig, env = process.env) {
|
|
|
80
80
|
return off.length ? { mcp: Object.fromEntries(off.map((n) => [n, { enabled: false }])) } : null;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
//
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
// #14048: the runner puts its heavy-gate shim folder first on a seat's PATH, outside the worktree.
|
|
84
|
+
// opencode auto-rejects any read outside the worktree in a non-interactive run and the turn ends
|
|
85
|
+
// there, so a seat that looked at what `npx` is lost its whole turn. Allow that one folder.
|
|
86
|
+
// Carries the user's own permission block so nothing of theirs is dropped by the injected config.
|
|
87
|
+
export function seatPermissionOverlay(shimDir, userConfig = null) {
|
|
88
|
+
if (!shimDir) return null;
|
|
89
|
+
const mine = userConfig?.permission;
|
|
90
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
91
|
+
const permission = mine && typeof mine === "object" && !Array.isArray(mine) ? { ...mine } : {};
|
|
92
|
+
const theirs = permission.external_directory;
|
|
93
|
+
if (theirs === "allow") return null; // already open everywhere: nothing to add
|
|
94
|
+
// A string rule becomes the broad rule; opencode takes the LAST match, so ours goes after it.
|
|
95
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
96
|
+
const rules = theirs && typeof theirs === "object" && !Array.isArray(theirs) ? { ...theirs }
|
|
97
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
98
|
+
: typeof theirs === "string" ? { "*": theirs } : {};
|
|
99
|
+
delete rules[`${shimDir}/**`];
|
|
100
|
+
rules[`${shimDir}/**`] = "allow";
|
|
101
|
+
return { permission: { ...permission, external_directory: rules } };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// The OPENCODE_CONFIG_CONTENT for an opencode seat: compaction JSON plus the MCP and permission
|
|
105
|
+
// overlays, "" if none.
|
|
106
|
+
export function seatConfigContent(compactionJson, mcpOverlay, permissionOverlay = null) {
|
|
107
|
+
if (!mcpOverlay && !permissionOverlay) return compactionJson;
|
|
86
108
|
let base = {};
|
|
87
109
|
try { base = compactionJson ? JSON.parse(compactionJson) : {}; } catch {}
|
|
88
|
-
return JSON.stringify({ ...base, ...mcpOverlay });
|
|
110
|
+
return JSON.stringify({ ...base, ...(mcpOverlay || {}), ...(permissionOverlay || {}) });
|
|
89
111
|
}
|
|
90
112
|
|
|
91
113
|
// The one per-turn runner line: what the injected block will actually do for this seat.
|
package/lib/store-pg.mjs
CHANGED
|
@@ -3,6 +3,27 @@
|
|
|
3
3
|
/* oxlint-disable anti-slop/no-runtime-typeof */
|
|
4
4
|
import { SCHEMA_SQL, SCHEMA_VERSION, KV_KEYS, DEFAULT_ORG, CHANGE_CHANNEL } from "./store-contract.mjs";
|
|
5
5
|
|
|
6
|
+
const TURNS_SCHEMA_SQL = `
|
|
7
|
+
CREATE TABLE IF NOT EXISTS turns (
|
|
8
|
+
org_id TEXT NOT NULL,
|
|
9
|
+
id TEXT NOT NULL,
|
|
10
|
+
ts BIGINT NOT NULL,
|
|
11
|
+
project TEXT NOT NULL,
|
|
12
|
+
agent TEXT NOT NULL,
|
|
13
|
+
persona TEXT NOT NULL,
|
|
14
|
+
machine TEXT NOT NULL,
|
|
15
|
+
outcome TEXT NOT NULL,
|
|
16
|
+
model TEXT NOT NULL,
|
|
17
|
+
duration_ms BIGINT,
|
|
18
|
+
tokens BIGINT,
|
|
19
|
+
card BIGINT,
|
|
20
|
+
row JSONB NOT NULL,
|
|
21
|
+
PRIMARY KEY (org_id, id)
|
|
22
|
+
);
|
|
23
|
+
CREATE INDEX IF NOT EXISTS turns_org_ts ON turns (org_id, ts DESC);
|
|
24
|
+
CREATE INDEX IF NOT EXISTS turns_org_project_agent ON turns (org_id, project, agent, ts DESC);
|
|
25
|
+
`;
|
|
26
|
+
|
|
6
27
|
const asJson = (v, fallback) => (v === undefined ? fallback : v);
|
|
7
28
|
const ms = (v, fallback = Date.now()) => {
|
|
8
29
|
const n = Number(v);
|
|
@@ -240,6 +261,7 @@ export class PgStore {
|
|
|
240
261
|
this.pool = new Pool({ connectionString: this.url });
|
|
241
262
|
}
|
|
242
263
|
await this.pool.query(SCHEMA_SQL);
|
|
264
|
+
await this.pool.query(TURNS_SCHEMA_SQL);
|
|
243
265
|
await this.pool.query(
|
|
244
266
|
"INSERT INTO schema_meta(version, applied_at) VALUES($1,$2) ON CONFLICT(version) DO NOTHING",
|
|
245
267
|
[SCHEMA_VERSION, Date.now()],
|
|
@@ -306,6 +328,48 @@ export class PgStore {
|
|
|
306
328
|
return r.rowCount || 0;
|
|
307
329
|
}
|
|
308
330
|
|
|
331
|
+
async appendTurns(orgId, rows) {
|
|
332
|
+
const unique = [];
|
|
333
|
+
const seen = new Set();
|
|
334
|
+
for (const row of rows) {
|
|
335
|
+
if (seen.has(row.id)) continue;
|
|
336
|
+
seen.add(row.id);
|
|
337
|
+
unique.push(row);
|
|
338
|
+
}
|
|
339
|
+
if (!unique.length) return { storedRows: [], duplicates: rows.length };
|
|
340
|
+
const values = [];
|
|
341
|
+
const tuples = unique.map(row => {
|
|
342
|
+
const base = values.length;
|
|
343
|
+
values.push(
|
|
344
|
+
orgId, row.id, row.ts, row.project, row.agent, row.persona, row.machine,
|
|
345
|
+
row.outcome, row.model, row.duration_ms, row.tokens, row.card,
|
|
346
|
+
JSON.stringify(stripNulDeep(row)),
|
|
347
|
+
);
|
|
348
|
+
return `(${Array.from({ length: 13 }, (_, i) => `$${base + i + 1}`).join(",")})`;
|
|
349
|
+
});
|
|
350
|
+
const result = await this.pool.query(
|
|
351
|
+
`INSERT INTO turns(org_id, id, ts, project, agent, persona, machine, outcome, model, duration_ms, tokens, card, row)
|
|
352
|
+
VALUES ${tuples.join(",")} ON CONFLICT(org_id, id) DO NOTHING RETURNING id`,
|
|
353
|
+
values,
|
|
354
|
+
);
|
|
355
|
+
const inserted = new Set(result.rows.map(row => String(row.id)));
|
|
356
|
+
const storedRows = unique.filter(row => inserted.has(row.id));
|
|
357
|
+
return { storedRows, duplicates: rows.length - storedRows.length };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async loadTurns(orgId, sinceMs = 0) {
|
|
361
|
+
const result = await this.pool.query(
|
|
362
|
+
"SELECT row FROM turns WHERE org_id=$1 AND ts>=$2 ORDER BY ts ASC, id ASC",
|
|
363
|
+
[orgId, Number(sinceMs)],
|
|
364
|
+
);
|
|
365
|
+
return result.rows.map(({ row }) => typeof row === "string" ? JSON.parse(row) : row);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
async pruneTurns(orgId, olderThanMs) {
|
|
369
|
+
const result = await this.pool.query("DELETE FROM turns WHERE org_id=$1 AND ts<$2", [orgId, Number(olderThanMs)]);
|
|
370
|
+
return result.rowCount || 0;
|
|
371
|
+
}
|
|
372
|
+
|
|
309
373
|
async upsertTask(orgId, task) {
|
|
310
374
|
await this.pool.query(
|
|
311
375
|
`INSERT INTO tasks(id, org_id, project, title, status, assignee, source, difficulty, model, phase, cost_usd, deps, history, created, updated, extra)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// trantor — the turn-row shipper (#14067, docs/CONTRACT-turn-telemetry.md): the local jsonl stays the
|
|
2
|
+
// write-ahead log; this lib drains it to the hub over the signed bus, oldest first, behind a
|
|
3
|
+
// byte-offset cursor. At-least-once: the cursor only moves after a 200, so an unreachable hub queues
|
|
4
|
+
// rows on disk instead of losing them, and a retry re-posts rows the hub dedupes by id.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { signedPost } from "../hooks/lib/api.mjs";
|
|
10
|
+
import { asString } from "./decode.mjs";
|
|
11
|
+
|
|
12
|
+
const logsDir = () => join(process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus"), "logs");
|
|
13
|
+
const BATCH = 100;
|
|
14
|
+
export const VERDICT_MAX = 600;
|
|
15
|
+
|
|
16
|
+
/** The duplicate key: first 32 hex of sha256 over persona, project, ts, turn. */
|
|
17
|
+
export function turnRowId(persona, project, ts, turn) {
|
|
18
|
+
return createHash("sha256").update(`${persona}\n${project}\n${Number(ts)}\n${Number(turn)}`).digest("hex").slice(0, 32);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Only a row with a positive integer `turn` is a turn. Boot rows and text notes are never turns. */
|
|
22
|
+
export function isTurnRow(rec) {
|
|
23
|
+
return !!rec && Number.isInteger(rec.turn) && rec.turn > 0;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The three fields every written turn row gains (#14067): the dedupe id, the schema version, the
|
|
28
|
+
* machine label — with the verdict cut to the contract's 600 characters. Non-turn rows pass through.
|
|
29
|
+
*/
|
|
30
|
+
export function completeTurnRow(rec, machine = "") {
|
|
31
|
+
if (!isTurnRow(rec)) return rec;
|
|
32
|
+
// machine is always present, "" when this machine has no label: the hub takes a string, not a missing key.
|
|
33
|
+
const row = { ...rec, id: turnRowId(rec.persona, rec.project, rec.ts, rec.turn), v: 1, machine: String(machine || "") };
|
|
34
|
+
if (row.verdict !== undefined) row.verdict = String(row.verdict).slice(0, VERDICT_MAX);
|
|
35
|
+
return row;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const fileFor = (persona, project) => join(logsDir(), `${persona}-${project}.jsonl`);
|
|
39
|
+
export const telemetryDir = logsDir;
|
|
40
|
+
export const telemetryFileFor = fileFor;
|
|
41
|
+
const cursorFor = (persona, project) => join(logsDir(), `.shipped-${persona}-${project}`);
|
|
42
|
+
// The episode marker outlives the process: a boot that finally ships after the previous runner's
|
|
43
|
+
// failures is a recovery too, and the drill expects its one log line.
|
|
44
|
+
const downFor = (persona, project) => join(logsDir(), `.shipped-${persona}-${project}.down`);
|
|
45
|
+
|
|
46
|
+
const episodes = new Set();
|
|
47
|
+
const tails = new Map();
|
|
48
|
+
|
|
49
|
+
function episodeStart(persona, project, reason, log) {
|
|
50
|
+
const key = `${persona}:${project}`;
|
|
51
|
+
if (episodes.has(key)) return;
|
|
52
|
+
episodes.add(key);
|
|
53
|
+
try { writeFileSync(downFor(persona, project), String(Date.now())); } catch {}
|
|
54
|
+
log(`could not report turns to the hub (${reason}) — rows stay queued and retry at the next turn or boot`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function episodeEnd(persona, project, log) {
|
|
58
|
+
const key = `${persona}:${project}`;
|
|
59
|
+
let marked = false;
|
|
60
|
+
try { marked = existsSync(downFor(persona, project)); } catch {}
|
|
61
|
+
if (!episodes.has(key) && !marked) return;
|
|
62
|
+
episodes.delete(key);
|
|
63
|
+
try { unlinkSync(downFor(persona, project)); } catch {}
|
|
64
|
+
log("turn reporting recovered — queued rows shipped");
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Serialised per seat: a boot ship and a turn ship never race one cursor. At-least-once would
|
|
68
|
+
// forgive the overlap; the queue makes it rare instead of routine. Never rejects.
|
|
69
|
+
export function shipTurnRows({ persona, project, hub = "", log = () => {}, timeoutMs = 2000, fromStart = false, machine = "" }) {
|
|
70
|
+
const key = `${persona}:${project}`;
|
|
71
|
+
const drainOne = () => drain({ persona, project, hub, log, timeoutMs, fromStart, machine });
|
|
72
|
+
const run = (tails.get(key) || Promise.resolve()).then(drainOne, drainOne);
|
|
73
|
+
tails.set(key, run);
|
|
74
|
+
run.then(() => { if (tails.get(key) === run) tails.delete(key); });
|
|
75
|
+
return run;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function writeCursor(persona, project, offset) {
|
|
79
|
+
// A torn write can only leave a smaller number (re-ship, deduped) — never a skipped row.
|
|
80
|
+
try { writeFileSync(cursorFor(persona, project), `${offset}\n`); } catch {}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function reasonOf(r) {
|
|
84
|
+
if (r?.status) return `hub answered ${r.status}`;
|
|
85
|
+
return r?.reason || "hub unreachable";
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// The unshipped tail of one seat's jsonl: complete lines only. A partial last line (the writer
|
|
89
|
+
// crashed mid-append) is neither shipped nor consumed — the cursor stops before it.
|
|
90
|
+
function readTail(file, start) {
|
|
91
|
+
const fd = openSync(file, "r");
|
|
92
|
+
try {
|
|
93
|
+
const size = fstatSync(fd).size;
|
|
94
|
+
// A cursor past EOF means the file was rotated or recreated: ship from the beginning rather
|
|
95
|
+
// than sit above the new content forever.
|
|
96
|
+
const from = start > size ? 0 : start;
|
|
97
|
+
const buf = Buffer.alloc(size - from);
|
|
98
|
+
let got = 0;
|
|
99
|
+
while (got < buf.length) {
|
|
100
|
+
const n = readSync(fd, buf, got, buf.length - got, from + got);
|
|
101
|
+
if (n <= 0) break;
|
|
102
|
+
got += n;
|
|
103
|
+
}
|
|
104
|
+
const lines = [];
|
|
105
|
+
let at = 0;
|
|
106
|
+
while (at < got) {
|
|
107
|
+
const nl = buf.indexOf(10, at);
|
|
108
|
+
if (nl < 0) break;
|
|
109
|
+
lines.push({ text: buf.toString("utf8", at, nl).replace(/\r$/, ""), end: from + nl + 1 });
|
|
110
|
+
at = nl + 1;
|
|
111
|
+
}
|
|
112
|
+
return { lines, endOfComplete: lines.length ? lines.at(-1).end : from };
|
|
113
|
+
} finally { closeSync(fd); }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function drain({ persona, project, hub, log, timeoutMs, fromStart, machine }) {
|
|
117
|
+
const totals = { ok: true, stored: 0, duplicates: 0, dropped: 0, shipped: 0, requests: 0, error: "" };
|
|
118
|
+
const file = fileFor(persona, project);
|
|
119
|
+
try {
|
|
120
|
+
if (!existsSync(file)) return totals;
|
|
121
|
+
let start = 0;
|
|
122
|
+
if (!fromStart) {
|
|
123
|
+
try { start = Number(readFileSync(cursorFor(persona, project), "utf8")); } catch {}
|
|
124
|
+
if (!Number.isInteger(start) || start < 0) start = 0;
|
|
125
|
+
}
|
|
126
|
+
const { lines, endOfComplete } = readTail(file, start);
|
|
127
|
+
const entries = [];
|
|
128
|
+
for (const line of lines) {
|
|
129
|
+
let rec = null;
|
|
130
|
+
try { rec = JSON.parse(line.text); } catch { continue; } // a corrupt line has no contract; it is consumed, never shipped
|
|
131
|
+
if (!isTurnRow(rec)) continue; // boot rows and text notes are never turns
|
|
132
|
+
if (!rec.id) rec.id = turnRowId(rec.persona, rec.project, rec.ts, rec.turn); // history rows pre-date the id
|
|
133
|
+
// History rows also pre-date v and machine, and the hub accepts only v 1 with a string machine.
|
|
134
|
+
if (rec.v !== 1) rec.v = 1;
|
|
135
|
+
rec.machine = asString(rec.machine) || String(machine || "");
|
|
136
|
+
if (rec.verdict !== undefined && String(rec.verdict).length > VERDICT_MAX) rec.verdict = String(rec.verdict).slice(0, VERDICT_MAX);
|
|
137
|
+
entries.push({ row: rec, end: line.end });
|
|
138
|
+
}
|
|
139
|
+
const path = hub ? `${hub.replace(/\/+$/, "")}/telemetry/turns` : "/telemetry/turns";
|
|
140
|
+
for (let i = 0; i < entries.length; i += BATCH) {
|
|
141
|
+
const batch = entries.slice(i, i + BATCH);
|
|
142
|
+
const r = await signedPost(path, { rows: batch.map(e => e.row) },
|
|
143
|
+
{ timeoutMs, session: `${persona}:${project}`, project });
|
|
144
|
+
if (!r.ok) {
|
|
145
|
+
totals.ok = false;
|
|
146
|
+
totals.error = reasonOf(r);
|
|
147
|
+
episodeStart(persona, project, totals.error, log);
|
|
148
|
+
return totals;
|
|
149
|
+
}
|
|
150
|
+
const reply = r.json || {};
|
|
151
|
+
totals.stored += Number(reply.stored) || 0;
|
|
152
|
+
totals.duplicates += Number(reply.duplicates) || 0;
|
|
153
|
+
totals.dropped += Number(reply.dropped) || 0;
|
|
154
|
+
totals.shipped += batch.length;
|
|
155
|
+
totals.requests += 1;
|
|
156
|
+
writeCursor(persona, project, batch.at(-1).end);
|
|
157
|
+
episodeEnd(persona, project, log);
|
|
158
|
+
}
|
|
159
|
+
// Consumed-but-unshipped lines (boot rows, text notes, a re-read gap) advance the cursor too —
|
|
160
|
+
// they are never shippable, so holding them only re-reads them every turn.
|
|
161
|
+
writeCursor(persona, project, endOfComplete);
|
|
162
|
+
return totals;
|
|
163
|
+
} catch (e) {
|
|
164
|
+
if (e?.code === "ENOENT") return totals; // the log was rotated away between the check and the read
|
|
165
|
+
totals.ok = false;
|
|
166
|
+
totals.error = String(e?.message || e);
|
|
167
|
+
episodeStart(persona, project, totals.error, log);
|
|
168
|
+
return totals;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* The seat a telemetry file belongs to, read from its rows (a persona or project may contain a
|
|
174
|
+
* hyphen, so the filename alone cannot split). null when no row names a seat.
|
|
175
|
+
*/
|
|
176
|
+
export function seatForTelemetryFile(file) {
|
|
177
|
+
let source = "";
|
|
178
|
+
try { source = readFileSync(file, "utf8"); } catch { return null; }
|
|
179
|
+
for (const line of source.split("\n")) {
|
|
180
|
+
if (!line) continue;
|
|
181
|
+
try {
|
|
182
|
+
const rec = JSON.parse(line);
|
|
183
|
+
const persona = asString(rec?.persona), project = asString(rec?.project);
|
|
184
|
+
if (persona && project) return { persona, project };
|
|
185
|
+
} catch {}
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Every telemetry file in the logs folder, oldest-name first — what `--all` ships. */
|
|
191
|
+
export function telemetryFiles() {
|
|
192
|
+
try { return readdirSync(logsDir()).filter(f => f.endsWith(".jsonl")).sort(); } catch { return []; }
|
|
193
|
+
}
|