trantor 0.18.133 → 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/cli.mjs +40 -0
- package/bin/crew-runner.mjs +17 -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/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/cli.mjs
CHANGED
|
@@ -140,6 +140,45 @@ switch (cmd) {
|
|
|
140
140
|
case "seats": case "seat": run("bin/seats.mjs"); break;
|
|
141
141
|
case "seat-why": case "why": run("bin/seat-why.mjs"); break;
|
|
142
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
|
+
}
|
|
143
182
|
case "orchestrate": run("bin/orchestrate.mjs"); break;
|
|
144
183
|
case "app": run("bin/app.mjs"); break;
|
|
145
184
|
case "patrol": run("bin/patrol.mjs"); break;
|
|
@@ -285,6 +324,7 @@ switch (cmd) {
|
|
|
285
324
|
trantor state a seat's working memory: show <seat> <card> [--json] · validate · reset --force · gc [--apply]
|
|
286
325
|
trantor seat-why WHY a seat is down (err file, logs, pids): seat-why <agent> [--json] — quota, auth, crash, or just no pane
|
|
287
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
|
|
288
328
|
trantor watch live bus feed in the terminal
|
|
289
329
|
trantor inbox THIS session's unread bus messages, signed (works under enforce) — [--all] [--consume] [--json]
|
|
290
330
|
trantor policy the autonomy ladder: show | set <project> <1-4> | link <a> <b> --reason "<why>"
|
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/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/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
|
+
}
|