trantor 0.18.130 → 0.18.132
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 +12 -0
- package/bin/cli.mjs +1 -0
- package/bin/crew/herdr.mjs +6 -4
- package/bin/crew/open.mjs +10 -3
- package/bin/crew-runner.mjs +102 -25
- package/bin/hub-timeouts.mjs +51 -0
- package/hooks/lib/api.mjs +19 -1
- package/hub/auth.mjs +5 -3
- package/hub/public.mjs +2 -1
- package/hub/routes/cards.mjs +2 -0
- package/hub/routes/messages.mjs +6 -0
- package/hub/routes/session.mjs +46 -5
- package/hub/store.mjs +7 -3
- package/hub.mjs +10 -3
- package/lib/disk.mjs +74 -8
- package/lib/herdr-integration.mjs +81 -0
- package/lib/hub-diagnostics.mjs +81 -0
- package/lib/machine-health.mjs +27 -0
- package/lib/seat-cache.mjs +16 -0
- package/lib/seat-worktree.mjs +22 -4
- package/lib/turn-policy.mjs +40 -0
- package/mcp.mjs +26 -4
- package/package.json +1 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.132",
|
|
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
|
@@ -391,6 +391,9 @@ project's own checkout wherever it is called from, handoff-beats-resume, and the
|
|
|
391
391
|
prompt so the woken session catches up (handoff, board, memory) and recaps on its own.
|
|
392
392
|
A reboot can leave herdr with a pane in its layout and no terminal behind it; `trantor open`,
|
|
393
393
|
the app's Resume and `trantor prune` all treat such a pane as dead and host a fresh one.
|
|
394
|
+
Trantor does not write herdr's global config. To make restored agents start one at a time, add
|
|
395
|
+
`startup_per_agent_delay_ms = 100` under `[session]` in `~/.config/herdr/config.toml`, then restart
|
|
396
|
+
the herdr server.
|
|
394
397
|
|
|
395
398
|
Why crews never exhaust the orchestrator: bus messages are **by reference** (~70 tokens),
|
|
396
399
|
work products stay in each agent's own context — the orchestrator burns at coordination
|
|
@@ -535,6 +538,15 @@ The default is `max(1, floor(cores / 4))` slots; set `"heavyGateSlots": 4` in
|
|
|
535
538
|
`~/.agent-bus/config.json` to override it. Crew runners wire Cargo and package-runner shims into
|
|
536
539
|
each seat. For a heavy command outside a runner, use `node bin/heavy-gate.mjs -- <command> …`.
|
|
537
540
|
|
|
541
|
+
Seats share one build cache per project under `~/.agent-bus/cache/<project>/`: Cargo builds go to
|
|
542
|
+
`cargo-target` there (an explicit `CARGO_TARGET_DIR` still wins) and the iOS drills put Xcode's
|
|
543
|
+
DerivedData beside it. The disk janitor prunes it under the same thresholds as other build output.
|
|
544
|
+
|
|
545
|
+
A machine that hosts seats can report its load: set `"healthHeartbeat": true` (plus a
|
|
546
|
+
`"machineLabel"`) in its `~/.agent-bus/config.json`, and its crew runners post CPU and memory to
|
|
547
|
+
the hub every 30 seconds. The desktop bottom bar shows each reporting machine, greyed once its last
|
|
548
|
+
report is older than 90 seconds.
|
|
549
|
+
|
|
538
550
|
## License
|
|
539
551
|
|
|
540
552
|
[MIT](./LICENSE) © 2026 Sasha Bogojevic · Built with [Claude Code](https://claude.com/claude-code) ·
|
package/bin/cli.mjs
CHANGED
|
@@ -45,6 +45,7 @@ switch (cmd) {
|
|
|
45
45
|
case "prune": runCrew(); break;
|
|
46
46
|
case "hub": {
|
|
47
47
|
const sub = args[0];
|
|
48
|
+
if (sub === "timeouts") { args.splice(0, 1); run("bin/hub-timeouts.mjs", process.execPath); break; }
|
|
48
49
|
// Per-project hub routing (TDD §12.1): a project lives on exactly ONE hub; codependent
|
|
49
50
|
// projects MUST share one. The mapping lives in ~/.agent-bus/config.json `hubs`.
|
|
50
51
|
if (sub === "list" || sub === "set" || sub === "unset") {
|
package/bin/crew/herdr.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { call, gridColumns, parseJsonOutput, runnerCommand } from "./core.mjs";
|
|
1
|
+
import { call, formatCommand, gridColumns, parseJsonOutput, runnerCommand } from "./core.mjs";
|
|
2
|
+
import { herdrReportArgs } from "../../lib/herdr-integration.mjs";
|
|
2
3
|
import { dropState, readRows, recordState } from "./state.mjs";
|
|
3
4
|
|
|
4
5
|
export function herdrCall(ctx, args) {
|
|
@@ -91,13 +92,14 @@ export function closePane(ctx, id) {
|
|
|
91
92
|
return herdrCall(ctx, ["pane", "close", id]).ok;
|
|
92
93
|
}
|
|
93
94
|
|
|
94
|
-
export function reportAgent(ctx, pane, agent) {
|
|
95
|
+
export function reportAgent(ctx, pane, agent, { sessionId = "", resumeArgv = [] } = {}) {
|
|
95
96
|
if (!pane) return;
|
|
97
|
+
const args = herdrReportArgs({ pane, agent, state: "working", sessionId, resumeArgv });
|
|
96
98
|
if (ctx.dry) {
|
|
97
|
-
console.log(`[dry]
|
|
99
|
+
console.log(`[dry] ${formatCommand("herdr", args)}`);
|
|
98
100
|
return;
|
|
99
101
|
}
|
|
100
|
-
herdrCall(ctx,
|
|
102
|
+
herdrCall(ctx, args);
|
|
101
103
|
}
|
|
102
104
|
|
|
103
105
|
function runSeat(ctx, pane, agent, command) {
|
package/bin/crew/open.mjs
CHANGED
|
@@ -72,7 +72,7 @@ function humanPromptAfter(transcriptPath, afterSecs) {
|
|
|
72
72
|
const at = Date.parse(e.timestamp || "") / 1000;
|
|
73
73
|
if (!(at >= afterSecs)) continue;
|
|
74
74
|
const c = e.message?.content;
|
|
75
|
-
const body =
|
|
75
|
+
const body = Array.isArray(c) ? c.map(x => x?.text || "").join("") : String(c || "");
|
|
76
76
|
if (body.startsWith("You have just taken over via handoff")) continue;
|
|
77
77
|
return at;
|
|
78
78
|
}
|
|
@@ -118,6 +118,13 @@ function orchestratorCommand(ctx, id) {
|
|
|
118
118
|
return `${env} claude${harnessFlag(ctx)} ${action}`;
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
function reportOrchestrator(ctx, pane, id) {
|
|
122
|
+
const resumeArgv = ["env", ...STRIP.flatMap(name => ["-u", name]), `TRANTOR_ORCH=${ctx.project}`, "claude"];
|
|
123
|
+
if (harnessFlag(ctx).trim()) resumeArgv.push("--dangerously-skip-permissions");
|
|
124
|
+
resumeArgv.push("--resume", id);
|
|
125
|
+
reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv });
|
|
126
|
+
}
|
|
127
|
+
|
|
121
128
|
export function paneHasAgent(ctx, pane) {
|
|
122
129
|
const result = herdrCall(ctx, ["pane", "process-info", "--pane", pane]);
|
|
123
130
|
const info = parseJsonOutput(result.stdout)?.result?.process_info;
|
|
@@ -160,7 +167,7 @@ function reattach(ctx, workspace, pane, id) {
|
|
|
160
167
|
if (!paneHasAgent(ctx, pane)) {
|
|
161
168
|
const started = herdrCall(ctx, ["pane", "run", pane, orchestratorCommand(ctx, id)]);
|
|
162
169
|
if (!started.ok) throw new Error(`trantor open: could not start the orchestrator in pane ${pane}`);
|
|
163
|
-
|
|
170
|
+
reportOrchestrator(ctx, pane, id);
|
|
164
171
|
console.error(`— orchestrator pane was empty: resumed session ${id} in herdr:${workspace || "?"}/${pane} —`);
|
|
165
172
|
} else console.error(`— orchestrator already hosted: reattached to herdr:${workspace || "?"}/${pane} —`);
|
|
166
173
|
console.log(`herdr:${workspace || "?"}/${pane}`);
|
|
@@ -200,7 +207,7 @@ function hostPane(ctx, chosen, id) {
|
|
|
200
207
|
if (!pane) throw new Error("trantor open: could not create the orchestrator pane");
|
|
201
208
|
herdrCall(ctx, ["pane", "rename", pane, `orchestrator · ${ctx.project}`]);
|
|
202
209
|
herdrCall(ctx, ["pane", "run", pane, orchestratorCommand(ctx, id)]);
|
|
203
|
-
|
|
210
|
+
reportOrchestrator(ctx, pane, id);
|
|
204
211
|
return pane;
|
|
205
212
|
}
|
|
206
213
|
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -2,12 +2,15 @@
|
|
|
2
2
|
// trantor crew runner — keeps a crew agent alive without burning tokens: it long-polls the bus
|
|
3
3
|
// (zero tokens) and resumes the CLI with each message. Usage: node crew-runner.mjs <agent> [dir]
|
|
4
4
|
import { execSync, spawnSync, spawn } from "node:child_process";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
5
6
|
import { readFileSync, writeFileSync, unlinkSync, existsSync, appendFileSync, mkdirSync, realpathSync, statSync, rmSync } from "node:fs";
|
|
6
7
|
import { join, basename } from "node:path";
|
|
7
8
|
import { homedir } from "node:os";
|
|
8
9
|
import { resolveProject, resolveHub, withEnvFiles, hostId } from "../lib/project.mjs";
|
|
9
10
|
import { machineLabel } from "../lib/machine-label.mjs";
|
|
11
|
+
import { healthPayload, defaultOs, HEALTH_BEAT_MS } from "../lib/machine-health.mjs";
|
|
10
12
|
import { resolveSecrets, shadowEnv, withSecretExports } from "../lib/secrets.mjs";
|
|
13
|
+
import { seatBuildCacheEnv } from "../lib/seat-cache.mjs";
|
|
11
14
|
import { runnerPersona } from "../lib/persona.mjs";
|
|
12
15
|
import { loadOrCreate } from "../lib/identity.mjs";
|
|
13
16
|
import { signedHeaders } from "../lib/signed-fetch.mjs";
|
|
@@ -26,6 +29,8 @@ import { capWake, capBcast, pickLessons, composePrompt, contractBase, baseLine }
|
|
|
26
29
|
import {
|
|
27
30
|
cardRefs, servedContractCard, carriesWork, parseTurnTokens, parseResetAt, reasonWithBalances, quotaResetAt, queuedWording, turnDelivered, budgetPause, PARKING_REASONS,
|
|
28
31
|
senderProjectOf, isLinkedProject, stateSkipReason, isMessageCardTitle, OPEN_CARD_STATUSES,
|
|
32
|
+
ownCardForInstance, contractedCardIds,
|
|
33
|
+
shouldAlignForContract,
|
|
29
34
|
CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
|
|
30
35
|
} from "../lib/turn-policy.mjs";
|
|
31
36
|
import { snapshotBeforeCut } from "./cut-snapshot.mjs";
|
|
@@ -54,6 +59,13 @@ import { resolveStateFlags, stateFeatureOn } from "../lib/state/flags.mjs";
|
|
|
54
59
|
|
|
55
60
|
import { awaitSwapRelease } from "./crew/stage.mjs";
|
|
56
61
|
import { codexRelayFlags } from "./crew/codex-relay.mjs";
|
|
62
|
+
import { codexSessionId, geminiSessionId, herdrReportArgs, runnerResumeArgv } from "../lib/herdr-integration.mjs";
|
|
63
|
+
|
|
64
|
+
const RUNNER_ARGV = process.argv.slice(2);
|
|
65
|
+
const runnerOption = (name, fallback = "") => {
|
|
66
|
+
const at = RUNNER_ARGV.indexOf(`--${name}`);
|
|
67
|
+
return at >= 0 ? (RUNNER_ARGV[at + 1] || fallback) : fallback;
|
|
68
|
+
};
|
|
57
69
|
|
|
58
70
|
const releaseState = process.env.CREW_RELEASE_STATE ? JSON.parse(process.env.CREW_RELEASE_STATE) : null;
|
|
59
71
|
delete process.env.CREW_RELEASE_STATE;
|
|
@@ -84,14 +96,14 @@ function newerVersion(next, previous) {
|
|
|
84
96
|
return false;
|
|
85
97
|
}
|
|
86
98
|
if (!releaseState) await awaitSwapRelease();
|
|
87
|
-
const AGENT = process.env.CREW_SWAP_AGENT || process.env.CREW_AGENT ||
|
|
88
|
-
const PERSONA = runnerPersona(process.env, AGENT);
|
|
89
|
-
const DIR =
|
|
99
|
+
const AGENT = process.env.CREW_SWAP_AGENT || process.env.CREW_AGENT || runnerOption("agent") || RUNNER_ARGV[0];
|
|
100
|
+
const PERSONA = runnerPersona({ ...process.env, CREW_PERSONA: process.env.CREW_PERSONA || runnerOption("persona") }, AGENT);
|
|
101
|
+
const DIR = RUNNER_ARGV[1] || process.cwd();
|
|
90
102
|
// Crew agents MUST share the orchestrator's project key (one repo = one lane).
|
|
91
103
|
// RELAY_PROJECT is inherited from crew.mjs (the host's resolved key); else fall
|
|
92
104
|
// back to the git-repo-root basename — never a loose dir basename that could
|
|
93
105
|
// fork the host's "builtbetter.ai" into a separate "builtbetter" lane.
|
|
94
|
-
const PROJ = process.env.RELAY_PROJECT || resolveProject(DIR);
|
|
106
|
+
const PROJ = process.env.RELAY_PROJECT || runnerOption("project") || resolveProject(DIR);
|
|
95
107
|
let machineConfig = {};
|
|
96
108
|
try { machineConfig = JSON.parse(readFileSync(join(process.env.AGENT_BUS_DIR || process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus"), "config.json"), "utf8")); } catch {}
|
|
97
109
|
const MACHINE_LABEL = machineLabel(machineConfig);
|
|
@@ -157,6 +169,8 @@ if (!AGENT) { console.error("usage: crew-runner.mjs <agent> [project-dir]"); pro
|
|
|
157
169
|
// talked to the remote one — the crew would look alive and record onto a different board entirely.
|
|
158
170
|
function hubUrl() {
|
|
159
171
|
if (process.env.RELAY_URL) return process.env.RELAY_URL;
|
|
172
|
+
const argHub = runnerOption("hub");
|
|
173
|
+
if (argHub) return argHub;
|
|
160
174
|
try { return resolveHub(PROJ); } catch {}
|
|
161
175
|
return "http://127.0.0.1:4477";
|
|
162
176
|
}
|
|
@@ -174,6 +188,11 @@ const log = (s) => console.log(`\x1b[38;5;43m[runner]\x1b[0m ${redactKeys(String
|
|
|
174
188
|
const LOGDIR = join(homedir(), ".agent-bus", "logs");
|
|
175
189
|
try { mkdirSync(LOGDIR, { recursive: true }); } catch {}
|
|
176
190
|
let TURN = releaseState?.turn || 0;
|
|
191
|
+
// #13923: when THIS seat instance started. A seat name is reused across instances and the board's
|
|
192
|
+
// assignee only knows the name, so the my-cards surfaces (relay_board mine, the own-card reroute)
|
|
193
|
+
// fence assignments against this stamp — cards assigned before it are a predecessor's (#12138).
|
|
194
|
+
// Carried across the in-place release restart; a swap or a fresh `trantor up` stamps anew.
|
|
195
|
+
const BOOT_TS = releaseState?.bootTs || Date.now();
|
|
177
196
|
const telemetry = (rec) => { try { appendFileSync(join(LOGDIR, `${PERSONA}-${PROJ}.jsonl`), JSON.stringify(rec) + "\n"); } catch {} };
|
|
178
197
|
// The boot line records the HUB this runner bound to, so a split-brain is diagnosable from disk.
|
|
179
198
|
telemetry({ ts: Date.now(), persona: PERSONA, agent: AGENT, project: PROJ, boot: true, hub: HUB, pid: process.pid, version: bootVersion });
|
|
@@ -241,8 +260,11 @@ function herdrAgent(state) {
|
|
|
241
260
|
.filter(c => c.length >= 4 && c[0] === PROJ && c[1] === "herdr" && c[2] === PERSONA)
|
|
242
261
|
.pop();
|
|
243
262
|
if (!row || !row[3]) return;
|
|
244
|
-
|
|
245
|
-
|
|
263
|
+
const resumeArgv = runnerResumeArgv({ agent: AGENT, driver: cli.pinned ? "opencode" : DRIVER, persona: PERSONA, dir: DIR,
|
|
264
|
+
runnerPath: join(import.meta.dirname, "crew-runner.mjs"), model: MODEL, effort: EFFORT,
|
|
265
|
+
project: PROJ, hub: HUB, sessionId: sid });
|
|
266
|
+
const args = herdrReportArgs({ pane: row[3], agent: AGENT, state, sessionId: sid, resumeArgv });
|
|
267
|
+
spawnSync("herdr", args, { stdio: "ignore", timeout: 1500 });
|
|
246
268
|
} catch { /* no herdr, or no row for this seat: the cmux/tmux paths do not need it */ }
|
|
247
269
|
}
|
|
248
270
|
|
|
@@ -253,7 +275,7 @@ function cmuxLog(message, level = "info") {
|
|
|
253
275
|
|
|
254
276
|
// ---- per-CLI invocation (first turn vs resume turn). {P} = prompt file path ----
|
|
255
277
|
// CREW_MODEL env pins the model: each CLI gets its own flag via {M} (empty when unset).
|
|
256
|
-
let MODEL = process.env.CREW_MODEL || "";
|
|
278
|
+
let MODEL = process.env.CREW_MODEL || runnerOption("model");
|
|
257
279
|
// opencode expects provider/model. A BARE id for the `deepseek` agent qualifies to its
|
|
258
280
|
// own provider; `opencode` ids must already be provider-qualified (e.g.
|
|
259
281
|
// `zai-coding-plan/glm-5.1`) — never assume `deepseek/` for opencode (that mangled
|
|
@@ -261,9 +283,11 @@ let MODEL = process.env.CREW_MODEL || "";
|
|
|
261
283
|
if (MODEL && !MODEL.includes("/") && AGENT === "deepseek") MODEL = `deepseek/${MODEL}`;
|
|
262
284
|
const CLI = {
|
|
263
285
|
codex: { first: `codex exec{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`,
|
|
264
|
-
next: `codex exec resume --last{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`,
|
|
286
|
+
next: `codex exec resume --last{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`,
|
|
287
|
+
nextById: `codex exec resume {SID}{M}{R} --skip-git-repo-check --dangerously-bypass-approvals-and-sandbox "$(cat {P})" < /dev/null`, mflag: " -m " },
|
|
265
288
|
gemini: { first: `gemini --yolo{M} -p "$(cat {P})"`,
|
|
266
|
-
next: `gemini --yolo{M} -r latest -p "$(cat {P})"`,
|
|
289
|
+
next: `gemini --yolo{M} -r latest -p "$(cat {P})"`,
|
|
290
|
+
nextById: `gemini --yolo{M} -r {SID} -p "$(cat {P})"`, mflag: " -m " },
|
|
267
291
|
// kimi-code (successor to kimi-cli) has no --print (-p alone is non-interactive), REJECTS
|
|
268
292
|
// --yolo in prompt mode (prompt mode auto-approves tools), and emits session_-prefixed ids.
|
|
269
293
|
kimi: { first: `kimi{M} -p "$(cat {P})" < /dev/null`,
|
|
@@ -283,7 +307,9 @@ const CLI = {
|
|
|
283
307
|
openrouter: { first: `opencode run --dir {DIR}{M} "$(cat {P})"`,
|
|
284
308
|
next: `opencode run --dir {DIR} -s {SID}{M} "$(cat {P})"`, mflag: " -m ", pinned: true, env: join(homedir(), ".token-scrooge", ".env") },
|
|
285
309
|
claude: { first: `claude{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
|
|
310
|
+
firstById: `claude{M} --session-id {SID} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
|
|
286
311
|
next: `claude -c{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
|
|
312
|
+
nextById: `claude --resume {SID}{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions`,
|
|
287
313
|
// TDD §4.6: a state step is a fresh `claude -p` (no `-c`) carrying the assembled prefix, held
|
|
288
314
|
// to the TurnResult grammar by --json-schema; test/state/test-runner-state.mjs pins the strings.
|
|
289
315
|
stateNext: `claude{M} -p "$(cat {P})" --permission-mode bypassPermissions --dangerously-skip-permissions --output-format json --json-schema "$(cat {S})"`,
|
|
@@ -307,12 +333,12 @@ if (!CLI[AGENT]) log(`'${AGENT}' is not a built-in seat — running it as an ope
|
|
|
307
333
|
// it as CREW_EFFORT (JSON from bin/crew/core.mjs runnerCommand). The runner applies the
|
|
308
334
|
// parameters the CLI can carry (codex -c model_reasoning_effort / claude --effort / opencode
|
|
309
335
|
// --variant) and logs ONE line saying what it set — or that the model is uncatalogued.
|
|
310
|
-
const EFFORT = (() => { try { return JSON.parse(process.env.CREW_EFFORT || "null"); } catch { return null; } })();
|
|
336
|
+
const EFFORT = (() => { try { return JSON.parse(process.env.CREW_EFFORT || runnerOption("effort") || "null"); } catch { return null; } })();
|
|
311
337
|
const EFFORT_FLAG = EFFORT ? cliEffortFlag(DRIVER, EFFORT) : { flag: "", text: "" };
|
|
312
338
|
|
|
313
339
|
// RUNNER_RULES / RUNNER_KICKOFF env overrides: the runner is also the substrate for non-crew
|
|
314
340
|
// always-on seats (the fleet DUTY agent, bin/duty.mjs) whose doctrine is not "work your card".
|
|
315
|
-
const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head
|
|
341
|
+
const RULES = process.env.RUNNER_RULES || `Rules: you are ${SESSION} on the trantor crew. Before starting a card, read YOUR card: relay_board with card:<id> (the card, its deps, its notes, and the last five done cards whose title shares a word); never the whole board. If your wake names no card id (or cites only a message-card), make relay_board with mine:true your FIRST call — it lists the cards assigned to you (doing/testing/todo, newest first, full card shape); work your newest one (#7763). After long read-only recon, commit a WIP note with findings so the turn leaves evidence. Work your assigned file(s), report on the bus (relay_send, <280 chars), move your Kanban card as you go with a NOTE saying what you did (doing -> testing, then STOP: you never close your own card to done — the orchestrator runs the card's drill on the built artifact and closes it, and the hub refuses a move to done on a card with no drill line anyway; in 'testing' run YOUR OWN test file — never the full npm test, suites collide across seats — plus \`node bin/slop-gate.mjs\` when the repo has one: it lints ONLY your changed files against the anti-slop rules, and a card must not reach testing with slop-gate failing; use 'failed' + a report if anything breaks). If your work starts containers or a dev server (\`supabase start\`, \`docker run\`, a watch process), stop them before moving your card to testing and name them in the note — the runner also stops containers it saw your turn create when the card closes, but the first responsibility is yours (#9778). If a contract omits a fact you cannot proceed without, ASK — never invent the value: relay_ask(<card>, <question>) blocks the card with your question, keeps the turn owed (no park, no failure), and resumes you when the assigner's answer lands; an invented value that reads as reasoned is the worst outcome this crew ships (#7756). If you need something from another session, message THAT SESSION (relay_peers to find its id, relay_send to reach it) — never ask the human to pass it along; carrying messages between agents is the job this bus exists to remove. When your work for THIS message is finished, END YOUR TURN — do NOT park, do NOT loop relay_wait; the runner waits for you and will wake you with the next message. Path discipline: build/test from your worktree root ${TURN_DIR} with absolute paths or --manifest-path/--prefix instead of cd-ing into subdirs, and put anything that must land outside the repo under ${TURN_DIR}/.agent-bus-out/ (gitignored) — never ~/.agent-bus. Realigning your seat branch after the orchestrator harvested your commits is \`trantor sync\` run from your worktree: it reads the harvest receipts and refuses when an unharvested commit would be lost, so never reset or rebase onto main by hand. A contract's \`base: <sha>\` line is the integration head, and the runner has already aligned your seat branch to it before your turn starts, saving any unharvested commit to harvest/<card> first (#13961). Work only on \`seat/<persona>\`; never create branches. Never \`git reset\`, \`rebase\` or \`checkout\` your seat branch yourself: a hand reset skips that save and silently drops finished work. If HEAD doesn't contain the base (\`git merge-base --is-ancestor <sha> HEAD\` fails), say \`cannot resolve base <sha>\` on the bus and move the card to blocked instead of working from somewhere else. Every testing/done note names the sha you verified against as \`verified at <sha>\`; a note without it is flagged HOLLOW. Cross-project action is a breach: never \`trantor up\` a crew, register a seat, or send a card/contract into a project other than ${PROJ} unless the operator ran \`trantor policy link ${PROJ} <other> --reason "<why>"\` first — the hub, the CLI and this runner all refuse it mechanically, so ask the operator to link the projects instead of routing around the refusal.`;
|
|
316
342
|
|
|
317
343
|
// ---- the pulse --------------------------------------------------------------
|
|
318
344
|
// RUNNER_PULSE_MS re-runs an orchestrator seat's mission note on a cadence when the bus is silent;
|
|
@@ -858,7 +884,7 @@ const OC_COMPACTION = ocCompactionContent(process.env, OC_COMPACTION_WINDOW);
|
|
|
858
884
|
// #11854: plus every non-relay MCP server of the user's opencode config switched off for the seat.
|
|
859
885
|
const OC_SEAT_CONFIG = seatConfigContent(OC_COMPACTION, seatMcpOverlay(readOpencodeUserConfig()));
|
|
860
886
|
|
|
861
|
-
let sid = releaseState?.sid || "";
|
|
887
|
+
let sid = releaseState?.sid || runnerOption("resume");
|
|
862
888
|
// #6206: the watchdog is DETACHED, so a runner that dies without ending it leaves an orphan
|
|
863
889
|
// sleeping toward a false alarm against whatever runner comes next.
|
|
864
890
|
// Every exit path therefore kills it, and the stamp carries this runner's instance id so any
|
|
@@ -879,7 +905,11 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
879
905
|
// A fresh session must not resume the old one's id: `first` is chosen by isFirst OR a missing
|
|
880
906
|
// sid, so a stale sid would quietly resume the session this turn exists to leave behind.
|
|
881
907
|
// #11855: the min-steps guard counts from the last fresh start; a state step never resets it.
|
|
882
|
-
if (isFirst) {
|
|
908
|
+
if (isFirst) {
|
|
909
|
+
sid = "";
|
|
910
|
+
if (DRIVER === "claude" && !opts.state) sid = randomUUID();
|
|
911
|
+
if (!opts.state) capFreshTurn = TURN;
|
|
912
|
+
}
|
|
883
913
|
// #5965 — TURN START. The hub peer row is where the app reads activity from, and the runner is
|
|
884
914
|
// the only one who knows a turn is starting, so say so before the CLI spawn (awaited: the spawn
|
|
885
915
|
// below blocks the loop, an unawaited fetch would not leave the machine until the turn ended).
|
|
@@ -917,7 +947,9 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
917
947
|
const busSeqBefore = await latestBusEventId();
|
|
918
948
|
// #6154: a pinned seat with no sid yet resumes as FRESH — the guard below fails open, because
|
|
919
949
|
// a resume without an id must fall back to a new session, never to `next`'s bare resume shape.
|
|
920
|
-
let cmd =
|
|
950
|
+
let cmd = isFirst || ((cli.sid || cli.pinned) && !sid)
|
|
951
|
+
? (sid && cli.firstById ? cli.firstById : cli.first)
|
|
952
|
+
: (runnerOption("resume") && sid && cli.nextById ? cli.nextById : cli.next);
|
|
921
953
|
// The flagged row (TDD §4.6). `{S}` exists only in `stateNext`, so the replaceAll below is a
|
|
922
954
|
// no-op on every other path — which is what "flag off = byte-identical" has to mean.
|
|
923
955
|
if (opts.state && cli.stateNext) cmd = cli.stateNext;
|
|
@@ -933,7 +965,10 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
933
965
|
// #6393: the store's keys ride the spawn env under shadow names and the shell re-exports them
|
|
934
966
|
// AFTER the sources ran, so the keychain wins over a stale .env line and no file is ever copied.
|
|
935
967
|
const secrets = resolveSecrets(process.env);
|
|
936
|
-
|
|
968
|
+
// #13923: the instance stamp rides the turn shell so the CLI's own MCP server (relay_board mine)
|
|
969
|
+
// fences inherited assignments with the SAME clock the runner's own-card resolution uses.
|
|
970
|
+
const bootStamp = `export TRANTOR_SEAT_BOOT_TS=${BOOT_TS}\n`;
|
|
971
|
+
cmd = withEnvFiles(withSecretExports(seatSignalPrefix(TURN_DIR) + bootStamp + cmd, Object.keys(secrets)), envs);
|
|
937
972
|
log(`turn starting (${isFirst ? "fresh session" : "resume"})${MODEL ? ` · model=${MODEL}` : ""}`);
|
|
938
973
|
// #7777: the one effort line — which effort parameters were set, or that the model is uncatalogued.
|
|
939
974
|
if (turnEffort.changed) log(`effort: ${turnEffort.effort.difficulty} for #${sessionCard} (launch ${EFFORT?.difficulty || "none"}) — ${turnEffort.text}`);
|
|
@@ -1057,7 +1092,7 @@ exit $turn_exit`;
|
|
|
1057
1092
|
detached: true,
|
|
1058
1093
|
cwd: TURN_DIR, encoding: "utf8", stdio: cli.sid ? ["ignore", "pipe", "inherit"] : ["ignore", "inherit", "inherit"],
|
|
1059
1094
|
};
|
|
1060
|
-
const spawnEnv = { ...process.env, ...shadowEnv(secrets), RELAY_URL: HUB, RELAY_AGENT: AGENT, RELAY_SESSION: SESSION, RELAY_PROJECT: PROJ,
|
|
1095
|
+
const spawnEnv = { ...seatBuildCacheEnv(process.env, PROJ), ...shadowEnv(secrets), RELAY_URL: HUB, RELAY_AGENT: AGENT, RELAY_SESSION: SESSION, RELAY_PROJECT: PROJ,
|
|
1061
1096
|
// #6228: marks this env as belonging to PROJ, unlike a one-off RELAY_PROJECT override; crew.mjs's
|
|
1062
1097
|
// `up` guard refuses to bring up another project's crew from a shell carrying this badge.
|
|
1063
1098
|
TRANTOR_SEAT: PROJ,
|
|
@@ -1139,6 +1174,14 @@ exit $turn_exit`;
|
|
|
1139
1174
|
// keyed by the worktree the session was created in. Fail-open: nothing found leaves sid empty,
|
|
1140
1175
|
// and the next turn starts fresh rather than resuming whatever other project ran last.
|
|
1141
1176
|
if (cli.pinned) { const found = ocSid(TURN_DIR); if (found) sid = found; }
|
|
1177
|
+
if (DRIVER === "codex") {
|
|
1178
|
+
const found = codexSessionId(join(homedir(), ".codex", "sessions"), TURN_DIR, t0);
|
|
1179
|
+
if (found) sid = found;
|
|
1180
|
+
}
|
|
1181
|
+
if (DRIVER === "gemini") {
|
|
1182
|
+
const found = geminiSessionId(join(homedir(), ".gemini"), TURN_DIR, t0);
|
|
1183
|
+
if (found) sid = found;
|
|
1184
|
+
}
|
|
1142
1185
|
const realExit = r.status;
|
|
1143
1186
|
// A zero exit is not proof the turn ran (#5405): an exit-0 auth turn is FAILED when the CLI's own
|
|
1144
1187
|
// output is short enough to be just the error (#5868). Telemetry keeps the real exit.
|
|
@@ -1508,15 +1551,29 @@ function askedExcerpt(message) {
|
|
|
1508
1551
|
// bus message parked on the board is never work, and chasing one (or a phantom id) is how a turn
|
|
1509
1552
|
// burns on bookkeeping. Only a CONFIRMED message-card title reroutes, to the seat's OWN newest
|
|
1510
1553
|
// open card (same statuses/ordering as relay_board's mine view); a phantom binds nothing.
|
|
1511
|
-
|
|
1554
|
+
|
|
1555
|
+
// #13923: the reroute lands only on a card THIS instance may work (newer than its start, or
|
|
1556
|
+
// contracted to it after) — never an assignment the reused name inherited from a predecessor.
|
|
1557
|
+
async function newestOwnCard(session, why, messages = []) {
|
|
1512
1558
|
try {
|
|
1513
1559
|
const { tasks } = await api(`/tasks?project=${encodeURIComponent(PROJ)}`);
|
|
1514
1560
|
const own = (Array.isArray(tasks) ? tasks : [])
|
|
1515
|
-
.filter((t) => t.assignee === session && OPEN_CARD_STATUSES.includes(t.status) && !isMessageCardTitle(t.title))
|
|
1516
|
-
|
|
1517
|
-
if (own.
|
|
1561
|
+
.filter((t) => t.assignee === session && OPEN_CARD_STATUSES.includes(t.status) && !isMessageCardTitle(t.title));
|
|
1562
|
+
let eligible = own;
|
|
1563
|
+
if (own.some((t) => (Number(t.ts) || 0) < BOOT_TS)) {
|
|
1564
|
+
// Contracts in hand (this wake batch) plus everything the hub still shows as delivered to
|
|
1565
|
+
// this session — a contract consumed turns ago still counts, so long as it is post-boot.
|
|
1566
|
+
const contracted = contractedCardIds(messages, { session, bootTs: BOOT_TS });
|
|
1567
|
+
try {
|
|
1568
|
+
const r = await api(`/inbox?session=${encodeURIComponent(session)}&since=0&peek=1`);
|
|
1569
|
+
for (const id of contractedCardIds(r?.messages, { session, bootTs: BOOT_TS })) contracted.add(id);
|
|
1570
|
+
} catch { /* inbox unreadable: the in-hand batch still decides; the fence holds */ }
|
|
1571
|
+
eligible = own.filter((t) => ownCardForInstance(t, { bootTs: BOOT_TS, contractedIds: contracted }));
|
|
1572
|
+
}
|
|
1573
|
+
const list = eligible.sort((a, b) => (b.updated || b.ts || 0) - (a.updated || a.ts || 0));
|
|
1574
|
+
if (list.length) log(`${why} — resolved to the seat's own #${list[0].id} (${list[0].status})`);
|
|
1518
1575
|
else log(`${why} — and the seat has no open card, so this turn carries no card binding`);
|
|
1519
|
-
return
|
|
1576
|
+
return list.length ? list[0].id : 0;
|
|
1520
1577
|
} catch { return 0; } // board unreadable: no binding beats a guessed one
|
|
1521
1578
|
}
|
|
1522
1579
|
async function resolveWakeCard(messages, { session }) {
|
|
@@ -1527,7 +1584,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1527
1584
|
try {
|
|
1528
1585
|
const { task } = await api(`/card?project=${encodeURIComponent(PROJ)}&id=${cited}`);
|
|
1529
1586
|
if (!task) { log(`#${cited}: the wake cites a card this board does not have — no card binding; the mine view is the first call`); return 0; }
|
|
1530
|
-
if (isMessageCardTitle(task.title)) return newestOwnCard(session, `#${cited} is a message-card ("${String(task.title).slice(0, 60)}")
|
|
1587
|
+
if (isMessageCardTitle(task.title)) return newestOwnCard(session, `#${cited} is a message-card ("${String(task.title).slice(0, 60)}")`, messages);
|
|
1531
1588
|
return cited;
|
|
1532
1589
|
} catch { return cited; } // hub unreachable: keep the pre-#7763 reading rather than drop a contract
|
|
1533
1590
|
}
|
|
@@ -1598,7 +1655,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1598
1655
|
// construction and now says so, in the same breath as the line that armed the mode.
|
|
1599
1656
|
if (!releaseState) {
|
|
1600
1657
|
stateSkip("kickoff");
|
|
1601
|
-
const ec0 = await runTurn(composedTurn({ base: KICKOFF, lessons: pickLessons(LESSONS_RAW, "") }),
|
|
1658
|
+
const ec0 = await runTurn(composedTurn({ base: KICKOFF, lessons: pickLessons(LESSONS_RAW, "") }), !runnerOption("resume"), runnerOption("resume") ? "reboot resume" : "kickoff");
|
|
1602
1659
|
if (ec0) await reportFailure(ec0, "kickoff", pendingWake.length); // a failed kickoff = the "fired up, died, nobody knew" case
|
|
1603
1660
|
// #7778: the kickoff is a turn like any other — a message that landed mid-kickoff and was read
|
|
1604
1661
|
// through the session's own inbox is consumed by a successful kickoff, and the first poll must
|
|
@@ -1626,7 +1683,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1626
1683
|
writeFileSync(PENDF, JSON.stringify({ persona: PERSONA, agent: AGENT, project: PROJ, ts: Date.now(),
|
|
1627
1684
|
wake: pendingWake, bcast: pendingBcast, seen: seenLedger, ask: awaitingAsk?.id || 0, askTo: awaitingAsk?.to || "" }));
|
|
1628
1685
|
const state = { cursor, turn: TURN, sid, sessionCard, retryAt, deliveryFails,
|
|
1629
|
-
noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions],
|
|
1686
|
+
noDeliveryRetry, askReleased, lastTurnAt, attempted: [...attemptedVersions], bootTs: BOOT_TS,
|
|
1630
1687
|
cardTokens, cardCommits, cardStartedAt, budgetStop, budgetRetryAt,
|
|
1631
1688
|
capHandoffs, capLogged, capArmed, capFreshTurn };
|
|
1632
1689
|
process.execve(process.execPath, [process.execPath, ...process.execArgv, ...process.argv.slice(1)],
|
|
@@ -1636,6 +1693,22 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1636
1693
|
if (PULSE_MS) log(`pulse armed — mission re-read every ${Math.round(PULSE_MS / 1000)}s (${MISSION_FILE})`);
|
|
1637
1694
|
log(`parked — long-polling the bus as ${SESSION} (free; this poll is also the heartbeat)`);
|
|
1638
1695
|
|
|
1696
|
+
// #13920: machine health heartbeat — opt-in via config.json healthHeartbeat:true (plus a valid
|
|
1697
|
+
// machineLabel, read at boot). One small signed POST every HEALTH_BEAT_MS; failures stay silent
|
|
1698
|
+
// by the monitoring doctrine (state not event — a machine that stops beating reads stale on the
|
|
1699
|
+
// hub, which IS the honest "unreachable" signal, not an error to alert on).
|
|
1700
|
+
if (machineConfig.healthHeartbeat === true && MACHINE_LABEL) {
|
|
1701
|
+
// A throw while building the payload must never reach the process: an unhandled rejection
|
|
1702
|
+
// here took a seat runner down on 0.18.131.
|
|
1703
|
+
const beat = () => {
|
|
1704
|
+
try { return api("/machines/health", { ...healthPayload(defaultOs, MACHINE_LABEL), project: PROJ }).catch(() => {}); }
|
|
1705
|
+
catch { return Promise.resolve(); }
|
|
1706
|
+
};
|
|
1707
|
+
beat();
|
|
1708
|
+
setInterval(beat, HEALTH_BEAT_MS).unref?.();
|
|
1709
|
+
log(`machine health heartbeat armed as ${MACHINE_LABEL} every ${Math.round(HEALTH_BEAT_MS / 1000)}s`);
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1639
1712
|
while (true) {
|
|
1640
1713
|
restartForRelease();
|
|
1641
1714
|
// pulse first: a due mission beat runs even on a silent bus. Measured from the END of the
|
|
@@ -1919,6 +1992,10 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1919
1992
|
const baseCard = card || servedContractCard(wakeForTurn, { session: SESSION });
|
|
1920
1993
|
const statedBase = contractBase(wakeForTurn);
|
|
1921
1994
|
const base = statedBase || originMainHead();
|
|
1995
|
+
const recentCardCommits = card && !statedBase
|
|
1996
|
+
? gitOut(["log", "-5", "--format=%s%n%b"], TURN_DIR)
|
|
1997
|
+
: "";
|
|
1998
|
+
const alignForContract = shouldAlignForContract(card, statedBase, sessionCard, recentCardCommits);
|
|
1922
1999
|
if (base && baseCard && !resolvesHere(base)) {
|
|
1923
2000
|
const text = `cannot resolve base ${base} in ${TURN_DIR} (git cat-file -e failed) — #${baseCard} moved to blocked; push or fetch that sha, or name one this worktree can reach`;
|
|
1924
2001
|
log(text);
|
|
@@ -1930,7 +2007,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1930
2007
|
savePending([], pendingBcast);
|
|
1931
2008
|
return;
|
|
1932
2009
|
}
|
|
1933
|
-
if (base && TURN_DIR !== DIR && card &&
|
|
2010
|
+
if (base && TURN_DIR !== DIR && card && alignForContract) {
|
|
1934
2011
|
const aligned = alignSeatWorktree({ dir: TURN_DIR, project: PROJ, agent: PERSONA, base });
|
|
1935
2012
|
if (!aligned.ok) {
|
|
1936
2013
|
const text = `cannot align seat worktree for #${card}: ${aligned.reason}`;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
const args = process.argv.slice(2);
|
|
8
|
+
let since = "1h";
|
|
9
|
+
for (let i = 0; i < args.length; i++) {
|
|
10
|
+
if (args[i] === "--since" && args[i + 1]) since = args[++i];
|
|
11
|
+
else { console.error("usage: trantor hub timeouts [--since 1h]"); process.exit(2); }
|
|
12
|
+
}
|
|
13
|
+
const match = since.match(/^(\d+)(m|h|d)$/);
|
|
14
|
+
if (!match) { console.error("--since must be a duration such as 30m, 1h, or 2d"); process.exit(2); }
|
|
15
|
+
const amount = Number(match[1]);
|
|
16
|
+
const ageMs = amount * ({ m: 60_000, h: 3_600_000, d: 86_400_000 })[match[2]];
|
|
17
|
+
const cutoff = Date.now() - ageMs;
|
|
18
|
+
const sinceArg = `${amount} ${match[2] === "m" ? "minute" : match[2] === "h" ? "hour" : "day"}${amount === 1 ? "" : "s"} ago`;
|
|
19
|
+
const busDir = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
|
|
20
|
+
const receiptFile = process.env.TRANTOR_HUB_TIMEOUTS_FILE || join(busDir, "hub-timeouts.jsonl");
|
|
21
|
+
let receipts = [];
|
|
22
|
+
if (existsSync(receiptFile)) {
|
|
23
|
+
receipts = readFileSync(receiptFile, "utf8").split("\n").filter(Boolean).flatMap(line => {
|
|
24
|
+
try {
|
|
25
|
+
const row = JSON.parse(line);
|
|
26
|
+
return Date.parse(row.ts) >= cutoff ? [{ time: Date.parse(row.ts), kind: "client timeout", text: `${row.route} op=${row.op} elapsed=${row.elapsedMs}ms hub=${row.hubUrl}` }] : [];
|
|
27
|
+
} catch { return []; }
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
let journal = "";
|
|
32
|
+
const remote = process.env.TRANTOR_HUB_SSH;
|
|
33
|
+
if (process.env.TRANTOR_HUB_JOURNAL_FILE) {
|
|
34
|
+
journal = readFileSync(process.env.TRANTOR_HUB_JOURNAL_FILE, "utf8");
|
|
35
|
+
} else {
|
|
36
|
+
const command = ["journalctl", "-u", "trantor-hub", "--since", sinceArg, "--output=short-iso", "--no-pager"];
|
|
37
|
+
try {
|
|
38
|
+
journal = remote
|
|
39
|
+
? execFileSync("ssh", [remote, "journalctl", "-u", "trantor-hub", "--since", sinceArg, "--output=short-iso", "--no-pager"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
|
|
40
|
+
: execFileSync(command[0], command.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
41
|
+
} catch { journal = ""; }
|
|
42
|
+
}
|
|
43
|
+
const journalRows = journal.split("\n").filter(line => /\[trantor\] (event-loop stall|slow request)/.test(line)).flatMap(line => {
|
|
44
|
+
const iso = line.match(/^(\d{4}-\d\d-\d\d[T ][0-9:.+-]+Z?)/)?.[1];
|
|
45
|
+
const time = Date.parse(iso || "");
|
|
46
|
+
return Number.isFinite(time) && time >= cutoff ? [{ time, kind: "hub", text: line }] : [];
|
|
47
|
+
});
|
|
48
|
+
const rows = [...receipts, ...journalRows].sort((a, b) => a.time - b.time);
|
|
49
|
+
console.log(`Hub diagnostics for the last ${since}${remote ? ` (journal via ssh ${remote})` : " (local journal only; set TRANTOR_HUB_SSH to include the remote hub journal)"}`);
|
|
50
|
+
if (!rows.length) console.log("No matching hub timeouts, event-loop stalls, or slow requests in this window.");
|
|
51
|
+
for (const row of rows) console.log(`${new Date(row.time).toISOString()} [${row.kind}] ${row.text}`);
|
package/hooks/lib/api.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// Wraps lib/signed-fetch.mjs (#3916) with hub URL resolution per project (§12.1), session identity
|
|
3
3
|
// (the same derivation mcp.mjs uses) and the Ed25519 keypair. FAIL-OPEN IS A CONTRACT (acceptance §9
|
|
4
4
|
// #10): getJSON/signedPost never throw; no key means unsigned, and only the hub knows its RELAY_AUTH policy.
|
|
5
|
-
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
5
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { homedir } from "node:os";
|
|
8
8
|
import { resolveProject, hostId, resolveHub } from "../../lib/project.mjs";
|
|
@@ -12,6 +12,22 @@ import { sfetchJson } from "../../lib/signed-fetch.mjs";
|
|
|
12
12
|
export const DEFAULT_TIMEOUT_MS = 1500;
|
|
13
13
|
export const WRITE_TIMEOUT_MS = 8000; // #7755: writes get their own budget above the read default
|
|
14
14
|
|
|
15
|
+
function recordAmbiguousTimeout(pathOrUrl, op, elapsedMs, project) {
|
|
16
|
+
const busDir = process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
|
|
17
|
+
const file = join(busDir, "hub-timeouts.jsonl");
|
|
18
|
+
const row = {
|
|
19
|
+
ts: new Date().toISOString(),
|
|
20
|
+
route: String(pathOrUrl),
|
|
21
|
+
op,
|
|
22
|
+
elapsedMs,
|
|
23
|
+
hubUrl: relayUrl(project),
|
|
24
|
+
};
|
|
25
|
+
try {
|
|
26
|
+
mkdirSync(busDir, { recursive: true });
|
|
27
|
+
appendFileSync(file, `${JSON.stringify(row)}\n`, { mode: 0o600 });
|
|
28
|
+
} catch { /* timeout reporting must never change the fail-open result */ }
|
|
29
|
+
}
|
|
30
|
+
|
|
15
31
|
// Hub URL, PER-PROJECT (TDD §12.1): env RELAY_URL, then config `hubs[project]`, then the legacy global
|
|
16
32
|
// `url`, then the local default. Never throws, keeping hooks fail-open.
|
|
17
33
|
export function relayUrl(project) {
|
|
@@ -180,6 +196,7 @@ export async function signedGet(pathOrUrl, { timeoutMs = DEFAULT_TIMEOUT_MS, ses
|
|
|
180
196
|
// one GET /_op — committed returns the stored body as success, rejected returns the stored refusal,
|
|
181
197
|
// unknown reads "ambiguous: timed out, outcome unknown". Never a bare failure for a write that landed.
|
|
182
198
|
export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT_MS, session, instance, project } = {}) {
|
|
199
|
+
const startedAt = Date.now();
|
|
183
200
|
const proj = projectOf(project, payload, pathOrUrl);
|
|
184
201
|
const sess = session || sessionFor(proj);
|
|
185
202
|
const durable = loadIdentity(sess);
|
|
@@ -193,6 +210,7 @@ export async function signedPost(pathOrUrl, payload, { timeoutMs = WRITE_TIMEOUT
|
|
|
193
210
|
const st = q.ok ? q.json?.status : "unknown";
|
|
194
211
|
if (st === "committed") return { ok: true, status: q.json.code || 200, json: q.json.body, resolved: "committed" };
|
|
195
212
|
if (st === "rejected") return { ok: false, status: q.json.code || 400, json: q.json.body, resolved: "rejected" };
|
|
213
|
+
recordAmbiguousTimeout(pathOrUrl, op, Date.now() - startedAt, proj);
|
|
196
214
|
return { ...f, ambiguous: true, reason: "ambiguous: timed out, outcome unknown" };
|
|
197
215
|
};
|
|
198
216
|
try {
|
package/hub/auth.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { timingSafeEqual, randomBytes } from "node:crypto";
|
|
|
6
6
|
import { publicView } from "../lib/identity.mjs";
|
|
7
7
|
import { IDENTITY_KINDS } from "../lib/store-contract.mjs";
|
|
8
8
|
|
|
9
|
-
export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map() }) {
|
|
9
|
+
export function createAuthRuntime({ state, markDirty, AUTH_MODE, SUPERSEDE_GRACE_MS, LOOPBACK_BIND, ENROLL_MODE, seenNonces = new Map(), diagnostics = null }) {
|
|
10
10
|
const now = () => Date.now();
|
|
11
11
|
// Route measurements and supported envelopes: docs/REQUEST-BODY-LIMITS.md.
|
|
12
12
|
const BODY_CAP_DEFAULT = 4 * 1024 * 1024;
|
|
@@ -61,7 +61,9 @@ async function body(req, maxBytes = BODY_CAP_DEFAULT) {
|
|
|
61
61
|
function json(res, code, obj) {
|
|
62
62
|
if (res.headersSent || res.writableEnded || res.destroyed) return false;
|
|
63
63
|
res.writeHead(code, { "content-type": "application/json", "access-control-allow-origin": "*" });
|
|
64
|
-
|
|
64
|
+
const payload = JSON.stringify(obj);
|
|
65
|
+
diagnostics?.recordStep("response.serialize", Buffer.byteLength(payload));
|
|
66
|
+
res.end(payload);
|
|
65
67
|
return true;
|
|
66
68
|
}
|
|
67
69
|
// Canonical project name: follow the alias chain so historically-divergent keys
|
|
@@ -96,7 +98,7 @@ const AUTH_HEADERS = ["x-trantor-pubkey", "x-trantor-sig", "x-trantor-ts", "x-tr
|
|
|
96
98
|
const PUBLIC_ENDPOINTS = new Set(["/", "/ui", "/health", "/enroll"]);
|
|
97
99
|
const OWNER_ENDPOINTS = new Set(["/project/delete", "/sweep", "/reconcile", "/invite", "/import", "/policy", "/session/prompts", "/session/prompt/claim", "/session/prompt/ack", "/session/attachment"]);
|
|
98
100
|
const DEVICE_ENDPOINTS = new Set(["/device/register", "/device/unregister", "/devices"]);
|
|
99
|
-
const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster"]);
|
|
101
|
+
const READ_ENDPOINTS = new Set(["/peers", "/tasks", "/events", "/inbox", "/peer", "/card", "/stream", "/history", "/projects", "/catchup", "/phases", "/recent", "/handoffs", "/verify-gates", "/claims", "/proposals", "/grants", "/overseer/context", "/overseer/status", "/session/chat", "/session/prompt", "/crew/roster", "/machines/health"]);
|
|
100
102
|
const roleRank = { read: 1, write: 2, approver: 3, owner: 4 };
|
|
101
103
|
const hasAuthHeaders = (req) => AUTH_HEADERS.some(h => !!req.headers[h]);
|
|
102
104
|
const authPath = (u) => `${u.pathname}${u.search || ""}`;
|
package/hub/public.mjs
CHANGED
|
@@ -4,7 +4,8 @@ import { HDR } from "../lib/identity.mjs";
|
|
|
4
4
|
const ALLOWED = new Set([
|
|
5
5
|
...["/health", "/projects", "/catchup", "/tasks", "/card", "/events", "/stream",
|
|
6
6
|
"/inbox", "/poll", "/recent", "/peers", "/holds", "/verify-gates", "/proposals",
|
|
7
|
-
"/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster",
|
|
7
|
+
"/balances", "/economics", "/session/chat", "/session/prompt", "/crew/roster",
|
|
8
|
+
"/machines/health", "/_op"]
|
|
8
9
|
.map(path => `GET ${path}`),
|
|
9
10
|
...["/enroll", "/task/update", "/task/checklist-toggle", "/send", "/delivered",
|
|
10
11
|
"/verify-gate", "/hold/decide", "/proposal/decide", "/session/prompt", "/session/answer",
|
package/hub/routes/cards.mjs
CHANGED
|
@@ -28,6 +28,8 @@ function slimCard(t) {
|
|
|
28
28
|
for (const k of Object.keys(t)) if (!SLIM_DROP.has(k)) out[k] = t[k];
|
|
29
29
|
// Keep the ·N the board renders, so slimming costs a reader nothing visible.
|
|
30
30
|
out.logCount = Array.isArray(t.log) ? t.log.length : 0;
|
|
31
|
+
out.checklistCount = Array.isArray(t.checklist) ? t.checklist.length : 0;
|
|
32
|
+
out.checklistDone = Array.isArray(t.checklist) ? t.checklist.filter(item => item.done).length : 0;
|
|
31
33
|
return out;
|
|
32
34
|
}
|
|
33
35
|
|
package/hub/routes/messages.mjs
CHANGED
|
@@ -34,6 +34,12 @@ export async function routeMessages({ req, res, q, P, auth, ctx }) {
|
|
|
34
34
|
// it (#6134). Stored only when false — absent means wake, so every older client is unchanged.
|
|
35
35
|
const wake = b.wake === false ? { wake: false } : {};
|
|
36
36
|
const msg = { id: ++state.seq, ts: now(), from: b.from || "anon", to: b.to || "all", text, project: String(b.project || fromProj || "").slice(0, 80), ...(re ? { re } : {}), ...(kind ? { kind } : {}), ...wake };
|
|
37
|
+
const peer = state.peers[msg.from];
|
|
38
|
+
if (msg.to === "all" && msg.kind === "status" && peer?.status === "crew member booting" && /^[A-Za-z0-9_.-]+ reporting — ready for a contract\b/.test(msg.text.trim())) {
|
|
39
|
+
peer.status = "idle";
|
|
40
|
+
peer.phase = "idle";
|
|
41
|
+
peer.phaseSince = msg.ts;
|
|
42
|
+
}
|
|
37
43
|
state.messages.push(msg); if (state.messages.length > 5000) state.messages.splice(0, 1000);
|
|
38
44
|
markDirty(); pushToStreams(msg); // <-- instant push to live watchers
|
|
39
45
|
// Mirror onto the unified log. `refs` = the card ids this message cites (#3701), which is what
|