trantor 0.18.134 → 0.18.135
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/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +5 -3
- package/bin/adopt.mjs +2 -2
- package/bin/cli.mjs +2 -0
- package/bin/connect.mjs +14 -1
- package/bin/crew/models.mjs +4 -1
- package/bin/crew/open.mjs +18 -8
- package/bin/crew/worktrees.mjs +3 -3
- package/bin/crew-runner.mjs +5 -4
- package/bin/crew.mjs +7 -2
- package/bin/doctor.mjs +3 -3
- package/bin/helper.mjs +119 -0
- package/bin/new.mjs +2 -2
- package/bin/seats.mjs +3 -2
- package/bin/slop-gate.mjs +1 -1
- package/bin/takeover.mjs +2 -2
- package/bin/turn-watchdog.mjs +2 -1
- package/deploy/node-path.sh +18 -0
- package/deploy/setup.sh +11 -3
- package/engine/bin/scrooge +9 -0
- package/hooks/lib/handoff.mjs +10 -3
- package/hooks/lib/start-gates.mjs +18 -0
- package/hooks/precompact.mjs +6 -2
- package/hooks/sessionstart.mjs +11 -6
- package/hub/routes/insights.mjs +29 -31
- package/hub/store.mjs +8 -1
- package/kimi/bin/baton-close.mjs +108 -0
- package/kimi/bin/lib/handoff.mjs +119 -0
- package/kimi/bin/write-handoff.mjs +31 -0
- package/kimi/bridge.mjs +219 -0
- package/kimi/skills/crew/SKILL.md +119 -0
- package/kimi/skills/handoff/SKILL.md +44 -0
- package/kimi/skills/research/SKILL.md +49 -0
- package/kimi.plugin.json +66 -0
- package/lib/agent-preferences.mjs +15 -0
- package/lib/enroll.mjs +20 -2
- package/lib/jsonc.mjs +37 -0
- package/lib/project.mjs +21 -2
- package/package.json +3 -1
package/hooks/precompact.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// trantor PreCompact hook — cannot stop compaction, so it writes a whole-session handoff and (macOS,
|
|
3
3
|
// by default) prompts to open a FRESH session that takes over; the at-the-wall backstop behind
|
|
4
4
|
// the heartbeat's early warning (hooks/lib/handoff.mjs).
|
|
5
|
-
import { readConfig, writeHandoff, pingBus, maybeSpawn, armBatonClose,
|
|
5
|
+
import { readConfig, writeHandoff, pingBus, maybeSpawn, armBatonClose, autoHandoffEnabled, manualContinueLine,
|
|
6
6
|
contextUsage, alreadyHandedOff, markHandedOff, controllingTty, terminalWindowForTty } from "./lib/handoff.mjs";
|
|
7
7
|
import { basename } from "node:path";
|
|
8
8
|
|
|
@@ -12,6 +12,7 @@ function readStdin() {
|
|
|
12
12
|
setTimeout(() => res(d), 100); });
|
|
13
13
|
}
|
|
14
14
|
|
|
15
|
+
let noteLine = "";
|
|
15
16
|
try {
|
|
16
17
|
const input = JSON.parse((await readStdin()) || "{}");
|
|
17
18
|
// input.cwd FIRST — every hook must derive the project the SAME way, or two hooks in one
|
|
@@ -39,6 +40,9 @@ try {
|
|
|
39
40
|
process.stderr.write(`[trantor] compaction trigger "${trigger}" is not auto/manual (idle compaction?) — handoff refreshed only, no fresh session\n`);
|
|
40
41
|
} else if (alreadyHandedOff(sessionId, cur)) {
|
|
41
42
|
process.stderr.write(`[trantor] fresh session already spawned for this window — handoff refreshed only\n`);
|
|
43
|
+
} else if (!autoHandoffEnabled(conf)) {
|
|
44
|
+
process.stderr.write(`[trantor] ${manualContinueLine(file)}\n`);
|
|
45
|
+
noteLine = manualContinueLine(file);
|
|
42
46
|
} else if (maybeSpawn(projectDir, conf)) {
|
|
43
47
|
markHandedOff(sessionId, cur);
|
|
44
48
|
// baton pass at the wall. Close THIS window ONLY when config.autoCloseOriginal is true: an auto
|
|
@@ -51,5 +55,5 @@ try {
|
|
|
51
55
|
} catch (err) {
|
|
52
56
|
process.stderr.write(`[trantor] precompact error: ${err?.message || err}\n`);
|
|
53
57
|
}
|
|
54
|
-
process.stdout.write("{}");
|
|
58
|
+
process.stdout.write(noteLine ? JSON.stringify({ systemMessage: noteLine }) : "{}");
|
|
55
59
|
process.exit(0);
|
package/hooks/sessionstart.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { join, basename, dirname } from "node:path";
|
|
|
7
7
|
import { homedir, hostname } from "node:os";
|
|
8
8
|
import { execSync, spawn } from "node:child_process";
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
|
-
import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, handoffDir, readOrchSession, writeOrchSession } from "../lib/project.mjs";
|
|
10
|
+
import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, readConfig as readBusConfig, handoffDir, readOrchSession, writeOrchSession } from "../lib/project.mjs";
|
|
11
11
|
import { formatSubagentManifest } from "../lib/subagent-manifest.mjs";
|
|
12
12
|
import { updateAvailable, maybeNotifyDesktop, readConfig } from "./lib/update-check.mjs";
|
|
13
13
|
import { renderStateBlock, capSummary } from "./lib/handoff.mjs";
|
|
@@ -17,6 +17,7 @@ import { maybeCheckBalances } from "./lib/balance-check.mjs";
|
|
|
17
17
|
import { getJSON, signedGet, signedPost, loadIdentity } from "./lib/api.mjs";
|
|
18
18
|
import { ledgerPaths, ensureStart, anchorCursor, writeCursor } from "./lib/inbox-ledger.mjs";
|
|
19
19
|
import { ensureEnrolled } from "../lib/enroll.mjs";
|
|
20
|
+
import { HUB_DOWN_LINE, loopbackUrl, shouldWarnUnpinned, wantsBuildDoctrine } from "./lib/start-gates.mjs";
|
|
20
21
|
import { memoryStartLine } from "./lib/memory-start.mjs";
|
|
21
22
|
import { staleResumeLine } from "./lib/cc-signals.mjs";
|
|
22
23
|
import { machineLabel } from "../lib/machine-label.mjs";
|
|
@@ -27,7 +28,7 @@ import { machineLabel } from "../lib/machine-label.mjs";
|
|
|
27
28
|
function buildDoctrineShortForm() {
|
|
28
29
|
const doc = join(dirname(dirname(fileURLToPath(import.meta.url))), "docs", "BUILD-DOCTRINE.md");
|
|
29
30
|
return `<trantor-build-doctrine>\n` +
|
|
30
|
-
`📐 **Build doctrine** (
|
|
31
|
+
`📐 **Build doctrine** (rules with a gate each, not advice). Full text: ${doc}\n` +
|
|
31
32
|
`1. The real path is the gate — every card names its DRILL (what a person does on the built artifact and must see); nothing merges until you ran it and wrote the result on the card; unit tests are never sufficient; the seat that wrote the code never closes its own card to done (testing is the seat's last move, done is yours after the drill).\n` +
|
|
32
33
|
`2. Red blocks merge — a red suite blocks merge; red for a day is an incident with a card; a flaky test is fixed or deleted within a week; no test inherits the runner's identity.\n` +
|
|
33
34
|
`3. One owner per subsystem — one named owner per wave who reviews every change; cross-seat edits go through the owner over the bus; you own the gates and merges, no seat merges to main.\n` +
|
|
@@ -202,7 +203,11 @@ try {
|
|
|
202
203
|
|
|
203
204
|
// fetch roster of OTHER online sessions
|
|
204
205
|
let peers = [], hubAnswered = false;
|
|
205
|
-
try {
|
|
206
|
+
try { const pr = await signedGet(`${url}/peers`, { timeoutMs: 2500, session }); hubAnswered = pr.status !== 0 && !pr.timedOut; peers = pr.json?.peers || []; } catch {}
|
|
207
|
+
if (!hubAnswered && loopbackUrl(url)) {
|
|
208
|
+
userBanner = userBanner ? `${userBanner}\n${HUB_DOWN_LINE}` : HUB_DOWN_LINE;
|
|
209
|
+
additionalContext += `<trantor-hub-down hub="${sanitize(url)}">${HUB_DOWN_LINE}</trantor-hub-down>\n`;
|
|
210
|
+
}
|
|
206
211
|
const others = peers.filter(p => p.online && p.session !== session);
|
|
207
212
|
|
|
208
213
|
process.stderr.write(`[trantor] registered as ${session} -> ${url} (via ${hubVia}, ${others.length} other live session(s))\n`);
|
|
@@ -211,7 +216,7 @@ try {
|
|
|
211
216
|
// the bus its crew is on: pins route the known projects to the remote hub, and anything unpinned
|
|
212
217
|
// drops to the global default. Two seats that believe they are the same project then read and
|
|
213
218
|
// write different stores, each looking perfectly healthy. Never let that be silent.
|
|
214
|
-
if (hubVia
|
|
219
|
+
if (shouldWarnUnpinned(hubVia, url, knownProjects())) {
|
|
215
220
|
const known = knownProjects();
|
|
216
221
|
const O = "\x1b[1;38;5;208m", R = "\x1b[0m";
|
|
217
222
|
const line = `🟠 ${O}"${project}" is not pinned to a hub${R} — falling back to ${url}. `
|
|
@@ -359,14 +364,14 @@ try {
|
|
|
359
364
|
try {
|
|
360
365
|
if (project && (process.env.TRANTOR_ORCH || "") === project) {
|
|
361
366
|
additionalContext += `<trantor-orchestrator-role project="${sanitize(project)}">\n` +
|
|
362
|
-
`🎛️ **You are this project's ORCHESTRATOR — a project manager, not a coder
|
|
367
|
+
`🎛️ **You are this project's ORCHESTRATOR — a project manager, not a coder**.\n` +
|
|
363
368
|
`- Building goes to the CREW: invoke the trantor:crew skill (Advisor → \`trantor up\` seats → contracts over the bus), or relay_scrooge for grunt one-shots.\n` +
|
|
364
369
|
`- Spend your own tokens on design, contracts, supervision, integration and VERIFICATION — run the seats' tests yourself; bounce hollow dones.\n` +
|
|
365
370
|
`- Write code yourself ONLY for small one-head seam work that needs this session's full context — and say so when you do.\n` +
|
|
366
371
|
`- Check relay_inbox and the board before asking the operator anything a peer may already have answered.\n` +
|
|
367
372
|
`- Dispatch rule: the target project is confirmed from the session's badge and cwd before any relay_send, relay_task_add or \`trantor up\` — an ambiguous instruction is not a project name; and a session asking the operator a question never triggers a wake (its messages batch until the answer).\n` +
|
|
368
373
|
`</trantor-orchestrator-role>\n`;
|
|
369
|
-
additionalContext += buildDoctrineShortForm();
|
|
374
|
+
if (wantsBuildDoctrine(readBusConfig())) additionalContext += buildDoctrineShortForm();
|
|
370
375
|
process.stderr.write(`[trantor] injected orchestrator-role doctrine for ${project}\n`);
|
|
371
376
|
}
|
|
372
377
|
} catch {}
|
package/hub/routes/insights.mjs
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
/* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: Ledger and card records are historical external formats; their compatibility probes remain unchanged in this structural split. */
|
|
2
|
-
import { readFileSync,
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
|
|
6
6
|
let ledgerCache = { mtimeMs: -1, rows: [] };
|
|
7
|
-
let telemetryCache = { maxMtimeMs: -1, turns: [] };
|
|
8
|
-
const LOGDIR = join(homedir(), ".agent-bus", "logs");
|
|
9
7
|
const TURN_OUTCOMES = new Set(["completed", "asked", "blocked", "no-delivery", "empty", "stalled", "cut", "rejected", "api-error"]);
|
|
10
8
|
const stringWithin = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
11
9
|
const safeInteger = (value, min = 0) => Number.isSafeInteger(value) && value >= min;
|
|
@@ -33,26 +31,8 @@ function validTurnRow(row, nowMs) {
|
|
|
33
31
|
return { ...row, id: row.id.toLowerCase(), verdict: row.verdict.slice(0, 600) };
|
|
34
32
|
}
|
|
35
33
|
|
|
36
|
-
function scanTelemetry() {
|
|
37
|
-
let files = [];
|
|
38
|
-
try { files = readdirSync(LOGDIR).filter(f => f.endsWith(".jsonl")); } catch { return telemetryCache.turns; }
|
|
39
|
-
let maxMtimeMs = 0;
|
|
40
|
-
for (const file of files) { try { maxMtimeMs = Math.max(maxMtimeMs, statSync(join(LOGDIR, file)).mtimeMs); } catch {} }
|
|
41
|
-
if (maxMtimeMs === telemetryCache.maxMtimeMs) return telemetryCache.turns;
|
|
42
|
-
const turns = [];
|
|
43
|
-
for (const file of files) {
|
|
44
|
-
let source = ""; try { source = readFileSync(join(LOGDIR, file), "utf8"); } catch { continue; }
|
|
45
|
-
for (const line of source.trim().split("\n")) {
|
|
46
|
-
if (!line) continue;
|
|
47
|
-
try { const row = JSON.parse(line); if (row?.agent) turns.push(row); } catch {}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
telemetryCache = { maxMtimeMs, turns };
|
|
51
|
-
return turns;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
34
|
export async function routeInsights({ res, q, P, req, auth, ctx }) {
|
|
55
|
-
const { state, json, canon, now, body, scopeAllows, turnTelemetry, AUTH_MODE } = ctx;
|
|
35
|
+
const { state, json, canon, now, body, scopeAllows, filterReadable, turnTelemetry, AUTH_MODE } = ctx;
|
|
56
36
|
if (req.method === "POST" && P === "/telemetry/turns") {
|
|
57
37
|
const b = await body(req);
|
|
58
38
|
if (!Array.isArray(b?.rows)) return json(res, 400, { error: "rows array required" });
|
|
@@ -76,6 +56,19 @@ export async function routeInsights({ res, q, P, req, auth, ctx }) {
|
|
|
76
56
|
return json(res, 500, { error: `turn telemetry store failed: ${reason}` });
|
|
77
57
|
}
|
|
78
58
|
}
|
|
59
|
+
if (req.method === "GET" && P === "/telemetry/turns") {
|
|
60
|
+
const numberQuery = (value, fallback) => {
|
|
61
|
+
if (value === undefined || value === "") return fallback;
|
|
62
|
+
const parsed = Number(value);
|
|
63
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
64
|
+
};
|
|
65
|
+
const limit = Math.min(1000, Math.max(1, Math.floor(numberQuery(q.limit, 1000))));
|
|
66
|
+
const rows = turnTelemetry.readRows({
|
|
67
|
+
project: q.project || "", agent: q.agent || "",
|
|
68
|
+
since: numberQuery(q.since, 0), until: numberQuery(q.until, Number.MAX_SAFE_INTEGER),
|
|
69
|
+
});
|
|
70
|
+
return json(res, 200, { rows: filterReadable(auth, rows, row => row.project || "").slice(0, limit) });
|
|
71
|
+
}
|
|
79
72
|
if (req.method === "GET" && P === "/economics") { // the brain's books, surfaced: scrooge ledger + quota profile
|
|
80
73
|
const out = { scrooge: null, lifetime: null, profile: null };
|
|
81
74
|
try { out.profile = JSON.parse(readFileSync(join(homedir(), ".agent-bus", "profile.json"), "utf8")).providers || {}; } catch {}
|
|
@@ -162,7 +155,7 @@ export async function routeInsights({ res, q, P, req, auth, ctx }) {
|
|
|
162
155
|
// charts), and the Scrooge guardrails baked into each model's prompt (+ per-model economics).
|
|
163
156
|
if (req.method === "GET" && P === "/learning") {
|
|
164
157
|
const projOf = by => (by && by.includes(":")) ? by.split(":").pop() : "";
|
|
165
|
-
// ts is ms (lessons
|
|
158
|
+
// ts is ms (lessons) or s (ledger). Null-safe: a malformed record with a missing/bad
|
|
166
159
|
// ts must not throw (new Date(NaN).toISOString() does) and 500 the whole endpoint — return null
|
|
167
160
|
// and let callers skip that day-bucket.
|
|
168
161
|
const dayOf = ts => { const n = Number(ts); if (!n) return null; const d = new Date(n > 2e10 ? n : n * 1000); return Number.isNaN(d.getTime()) ? null : d.toISOString().slice(0, 10); };
|
|
@@ -179,20 +172,25 @@ export async function routeInsights({ res, q, P, req, auth, ctx }) {
|
|
|
179
172
|
|
|
180
173
|
// per-LLM reliability from turn telemetry, bucketed BY PROJECT (+ a global ALL bucket) so the
|
|
181
174
|
// sidebar's project filter scopes the charts. Each turn carries its own project.
|
|
182
|
-
const
|
|
175
|
+
const totals = turnTelemetry.readTotals();
|
|
183
176
|
const relAgg = {}; // scope -> agent -> {turns,failures,models:Set,lastFailure,days}
|
|
184
177
|
const scopeModels = {}; // scope -> Set(model used)
|
|
185
178
|
let totalTurns = 0, totalFails = 0;
|
|
186
179
|
const bumpRel = (scope, t) => {
|
|
187
180
|
const a = ((relAgg[scope] ||= {})[t.agent] ||= { agent: t.agent, turns: 0, failures: 0, models: new Set(), lastFailure: null, days: {} });
|
|
188
|
-
a.turns
|
|
189
|
-
|
|
190
|
-
const
|
|
191
|
-
|
|
181
|
+
a.turns += t.turns;
|
|
182
|
+
a.failures += t.failed;
|
|
183
|
+
for (const model of t.models) { a.models.add(model); if (model !== "default") (scopeModels[scope] ||= new Set()).add(model); }
|
|
184
|
+
const d = (a.days[t.day] ||= { turns: 0, failures: 0 });
|
|
185
|
+
d.turns += t.turns;
|
|
186
|
+
d.failures += t.failed;
|
|
187
|
+
if (t.lastFailure && (!a.lastFailure || t.lastFailure.ts > a.lastFailure.ts)) {
|
|
188
|
+
a.lastFailure = { ts: t.lastFailure.ts, exit: t.lastFailure.exit, project: t.project || "" };
|
|
189
|
+
}
|
|
192
190
|
};
|
|
193
|
-
for (const t of
|
|
194
|
-
|
|
195
|
-
|
|
191
|
+
for (const t of totals) {
|
|
192
|
+
totalTurns += t.turns;
|
|
193
|
+
totalFails += t.failed;
|
|
196
194
|
bumpRel(ALL, t);
|
|
197
195
|
if (t.project) { bumpRel(t.project, t); projSet.add(t.project); }
|
|
198
196
|
}
|
package/hub/store.mjs
CHANGED
|
@@ -285,6 +285,13 @@ const readTurnTotals = () => [...dailyTurns.values()].flatMap(projects =>
|
|
|
285
285
|
models: [...total.models].sort(),
|
|
286
286
|
lastFailure: total.lastFailure ? { ...total.lastFailure } : null,
|
|
287
287
|
}))));
|
|
288
|
+
function readTurnRows({ project = "", agent = "", since = 0, until = Number.MAX_SAFE_INTEGER, limit } = {}) {
|
|
289
|
+
const rows = [...turnRows.values()]
|
|
290
|
+
.filter(row => (!project || row.project === project) && (!agent || row.agent === agent) && row.ts >= since && row.ts <= until)
|
|
291
|
+
.sort((a, b) => b.ts - a.ts || String(b.id).localeCompare(String(a.id)));
|
|
292
|
+
const capped = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 1000) : rows.length;
|
|
293
|
+
return rows.slice(0, capped).map(row => ({ ...row }));
|
|
294
|
+
}
|
|
288
295
|
function turnHealth() {
|
|
289
296
|
const cutoff = Date.now() - 86400000;
|
|
290
297
|
let lo = 0, hi = recentTurnTs.length;
|
|
@@ -306,7 +313,7 @@ const retentionTimer = setInterval(async () => {
|
|
|
306
313
|
}
|
|
307
314
|
}, 86400000);
|
|
308
315
|
retentionTimer.unref?.();
|
|
309
|
-
const turnTelemetry = { append: appendTurns, prune: pruneTurns, readTotals: readTurnTotals, health: turnHealth };
|
|
316
|
+
const turnTelemetry = { append: appendTurns, prune: pruneTurns, readTotals: readTurnTotals, readRows: readTurnRows, health: turnHealth };
|
|
310
317
|
|
|
311
318
|
let dirty = false;
|
|
312
319
|
// Persist the unified log under `events`, AND mirror the card-only subset under the legacy
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// trantor/kimi baton-close — the second half of the baton pass, Kimi Code port. Runs DETACHED,
|
|
3
|
+
// armed by the handoff hook. Waits until the FRESH session has consumed the handoff (consumed:true
|
|
4
|
+
// on the handoff file), THEN closes the ORIGINAL session's Terminal window.
|
|
5
|
+
// NON-DESTRUCTIVE by contract (incident 2026-06-21): never force-kills; runs only for opt-in
|
|
6
|
+
// auto-close or a manual baton; waits for the fresh session's first real turn (a loop event in its
|
|
7
|
+
// wire.jsonl at/after the claim); re-validates the window's tty; ABORTS if the original is still
|
|
8
|
+
// working (recent wire activity or live sub-agents). Args: <handoffFile> <originalWindowId> <originalTty>
|
|
9
|
+
import { readFileSync, existsSync, statSync } from "node:fs";
|
|
10
|
+
import { execSync } from "node:child_process";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { subagentsActive } from "./lib/handoff.mjs";
|
|
13
|
+
|
|
14
|
+
const [, , handoffFile, windowId, originalTty] = process.argv;
|
|
15
|
+
const POLL_MS = 1500, TIMEOUT_MS = 180_000;
|
|
16
|
+
const ORIG_QUIET_MS = 12_000, SUBAGENT_ACTIVE_MS = 90_000;
|
|
17
|
+
const ENGAGE_GRACE_MS = 45_000;
|
|
18
|
+
|
|
19
|
+
const handoff = () => { try { return JSON.parse(readFileSync(handoffFile, "utf8")); } catch { return null; } };
|
|
20
|
+
const consumed = () => handoff()?.consumed === true;
|
|
21
|
+
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
|
22
|
+
|
|
23
|
+
// True once the fresh session's wire.jsonl shows activity at/after the handoff was consumed —
|
|
24
|
+
// i.e. the new session booted and produced its first turn. Kimi wire timestamps are ms epoch;
|
|
25
|
+
// consumedAt is seconds.
|
|
26
|
+
export function freshEngaged(rec) {
|
|
27
|
+
try {
|
|
28
|
+
const tp = rec?.consumedBy?.transcript_path;
|
|
29
|
+
if (!tp || !existsSync(tp)) return false;
|
|
30
|
+
const consumedAtMs = (Number(rec.consumedAt) || 0) * 1000;
|
|
31
|
+
const lines = readFileSync(tp, "utf8").split("\n");
|
|
32
|
+
for (const ln of lines) {
|
|
33
|
+
if (!ln) continue;
|
|
34
|
+
let r; try { r = JSON.parse(ln); } catch { continue; }
|
|
35
|
+
if (r?.type !== "context.append_loop_event" && r?.type !== "turn.prompt" && r?.type !== "usage.record") continue;
|
|
36
|
+
const ts = Number(r.time) || 0;
|
|
37
|
+
if (!consumedAtMs || !ts || ts >= consumedAtMs - 5000) return true;
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
} catch { return false; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function waitForTakeover() {
|
|
44
|
+
const rec = handoff();
|
|
45
|
+
if (!rec?.consumedBy?.transcript_path) { await sleep(2500); return; }
|
|
46
|
+
const until = Date.now() + ENGAGE_GRACE_MS;
|
|
47
|
+
while (Date.now() < until) {
|
|
48
|
+
if (freshEngaged(handoff())) { await sleep(800); return; }
|
|
49
|
+
await sleep(POLL_MS);
|
|
50
|
+
}
|
|
51
|
+
process.stderr.write(`[trantor] kimi baton-close: fresh session consumed but produced no turn within ${ENGAGE_GRACE_MS / 1000}s — closing anyway (handoff already injected)\n`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// True if the ORIGINAL session is still doing real work — its wire was written very recently or it
|
|
55
|
+
// has live sub-agents. We NEVER close a working session.
|
|
56
|
+
export function originalStillWorking(rec, { quietMs = ORIG_QUIET_MS, subWithinMs = SUBAGENT_ACTIVE_MS } = {}) {
|
|
57
|
+
try {
|
|
58
|
+
const tp = rec?.transcript_path;
|
|
59
|
+
if (!tp || !existsSync(tp)) return false;
|
|
60
|
+
try { if (Date.now() - statSync(tp).mtimeMs < quietMs) return true; } catch {}
|
|
61
|
+
return subagentsActive(tp, subWithinMs);
|
|
62
|
+
} catch { return false; }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function ttyOfWindow(id) {
|
|
66
|
+
try {
|
|
67
|
+
return execSync(`osascript -e ${JSON.stringify(`tell application "Terminal" to get tty of selected tab of (first window whose id is ${id})`)}`,
|
|
68
|
+
{ encoding: "utf8", timeout: 3000 }).trim();
|
|
69
|
+
} catch { return ""; }
|
|
70
|
+
}
|
|
71
|
+
function closeWindow(id, tty) {
|
|
72
|
+
const cur = ttyOfWindow(id);
|
|
73
|
+
if (!cur || (originalTty && cur !== originalTty)) {
|
|
74
|
+
process.stderr.write(`[trantor] kimi baton-close: window ${id} tty changed (${cur} != ${originalTty}) — NOT closing\n`);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
// Gently ask the processes on that tty to exit (SIGTERM — never SIGKILL); only reached once the
|
|
79
|
+
// original is confirmed idle, so kimi exits cleanly.
|
|
80
|
+
const dev = (tty || cur).replace(/^\/dev\//, "");
|
|
81
|
+
for (const pid of execSync(`ps -t ${dev} -o pid= 2>/dev/null || true`, { encoding: "utf8" }).trim().split("\n").filter(Boolean)) {
|
|
82
|
+
try { execSync(`kill -TERM ${pid.trim()} 2>/dev/null || true`); } catch {}
|
|
83
|
+
}
|
|
84
|
+
} catch {}
|
|
85
|
+
try { execSync(`osascript -e ${JSON.stringify(`tell application "Terminal" to close (first window whose id is ${id})`)}`, { timeout: 3000 }); return true; } catch { return false; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const isMain = (() => { try { return import.meta.url === pathToFileURL(process.argv[1]).href; } catch { return false; } })();
|
|
89
|
+
|
|
90
|
+
if (isMain) (async () => {
|
|
91
|
+
if (!handoffFile || !windowId) process.exit(0);
|
|
92
|
+
const deadline = Date.now() + TIMEOUT_MS;
|
|
93
|
+
while (Date.now() < deadline) {
|
|
94
|
+
if (consumed()) {
|
|
95
|
+
await waitForTakeover();
|
|
96
|
+
if (originalStillWorking(handoff())) {
|
|
97
|
+
process.stderr.write(`[trantor] kimi baton-close: original session still working (recent activity / live sub-agents) — leaving it alive, NOT closing\n`);
|
|
98
|
+
process.exit(0);
|
|
99
|
+
}
|
|
100
|
+
const ok = closeWindow(windowId, originalTty);
|
|
101
|
+
process.stderr.write(`[trantor] kimi baton-close: fresh session took over → original window ${windowId} ${ok ? "closed" : "left (validation/close failed)"}\n`);
|
|
102
|
+
process.exit(0);
|
|
103
|
+
}
|
|
104
|
+
await sleep(POLL_MS);
|
|
105
|
+
}
|
|
106
|
+
process.stderr.write(`[trantor] kimi baton-close: fresh session never confirmed within ${TIMEOUT_MS / 1000}s — leaving the original alive (safe)\n`);
|
|
107
|
+
process.exit(0);
|
|
108
|
+
})();
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// trantor/kimi — kimi-specific baton-pass glue for kimi/bin/*. After the dialect-bridge de-fork
|
|
2
|
+
// (docs/KIMI-BRIDGE-CONTRACT.md, P2) all hook logic lives in the canonical hooks/**; what remains
|
|
3
|
+
// here is ONLY what cannot be canonical: the kimi wire.jsonl session layout (sub-agent liveness)
|
|
4
|
+
// and spawning a fresh `kimi` session (the canonical spawnFresh hardcodes `claude`).
|
|
5
|
+
// Everything else (open-session.sh, handoff-prompt.sh) is the canonical bin/ script.
|
|
6
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
7
|
+
import { join, dirname } from "node:path";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { execSync, spawn } from "node:child_process";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
|
|
12
|
+
const HERE = dirname(fileURLToPath(import.meta.url)); // <plugin>/kimi/bin/lib
|
|
13
|
+
const KIMI_BIN = join(HERE, ".."); // <plugin>/kimi/bin
|
|
14
|
+
const PLUGIN_BIN = join(HERE, "..", "..", "..", "bin"); // <plugin>/bin (canonical)
|
|
15
|
+
|
|
16
|
+
export function readConfig() {
|
|
17
|
+
try {
|
|
18
|
+
const cfg = join(homedir(), ".agent-bus", "config.json");
|
|
19
|
+
return existsSync(cfg) ? JSON.parse(readFileSync(cfg, "utf8")) : {};
|
|
20
|
+
} catch { return {}; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ---- in-flight guard (kimi session layout) ----------------------------------
|
|
24
|
+
// True when this session has live sub-agents: any agents/<not-main>/wire.jsonl written within
|
|
25
|
+
// `withinMs`. The baton-close ABORTS while sub-agents run (incident 2026-06-21).
|
|
26
|
+
export function subagentsActive(wirePath, withinMs = 90_000) {
|
|
27
|
+
try {
|
|
28
|
+
if (!wirePath) return false;
|
|
29
|
+
const agentsDir = dirname(dirname(wirePath)); // <session>/agents
|
|
30
|
+
const cutoff = Date.now() - withinMs;
|
|
31
|
+
for (const a of readdirSync(agentsDir)) {
|
|
32
|
+
if (a === "main") continue;
|
|
33
|
+
try { if (statSync(join(agentsDir, a, "wire.jsonl")).mtimeMs >= cutoff) return true; } catch {}
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
} catch { return false; }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// --- original window resolution (macOS Terminal.app) --------------------------
|
|
40
|
+
export function controllingTty() {
|
|
41
|
+
for (const pid of [process.pid, process.ppid, getPpid(process.ppid)]) {
|
|
42
|
+
if (!pid) continue;
|
|
43
|
+
try { const t = execSync(`ps -o tty= -p ${pid}`, { encoding: "utf8" }).trim(); if (t && t !== "??" && t !== "?") return "/dev/" + t; } catch {}
|
|
44
|
+
}
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
function getPpid(pid) { if (!pid) return 0; try { return Number(execSync(`ps -o ppid= -p ${pid}`, { encoding: "utf8" }).trim()) || 0; } catch { return 0; } }
|
|
48
|
+
|
|
49
|
+
export function terminalWindowForTty(tty) {
|
|
50
|
+
if (process.platform !== "darwin" || !tty) return "";
|
|
51
|
+
const osa = `tell application "Terminal"
|
|
52
|
+
repeat with w in windows
|
|
53
|
+
try
|
|
54
|
+
if (tty of selected tab of w) is "${tty}" then return (id of w) as string
|
|
55
|
+
end try
|
|
56
|
+
end repeat
|
|
57
|
+
return ""
|
|
58
|
+
end tell`;
|
|
59
|
+
// Multi-line script via stdin, never -e (see hooks/lib/handoff.mjs for the incident note).
|
|
60
|
+
try { return execSync(`osascript`, { input: osa, encoding: "utf8", timeout: 3000 }).trim(); } catch { return ""; }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function frontTerminalWindow() {
|
|
64
|
+
if (process.platform !== "darwin") return { id: "", tty: "" };
|
|
65
|
+
try {
|
|
66
|
+
const out = execSync(`osascript -e ${JSON.stringify(`tell application "Terminal" to return (id of front window as string) & "|" & (tty of selected tab of front window)`)}`,
|
|
67
|
+
{ encoding: "utf8", timeout: 3000 }).trim();
|
|
68
|
+
const [id, tty] = out.split("|"); return { id: id || "", tty: tty || "" };
|
|
69
|
+
} catch { return { id: "", tty: "" }; }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// MUST be called BEFORE spawning the fresh session (see hooks/lib/handoff.mjs — ordering is
|
|
73
|
+
// load-bearing; reversing it is the "successor closes ITSELF" bug).
|
|
74
|
+
export function resolveOriginalWindow() {
|
|
75
|
+
let tty = controllingTty(), windowId = tty ? terminalWindowForTty(tty) : "";
|
|
76
|
+
if (!windowId) { const f = frontTerminalWindow(); windowId = f.id; tty = f.tty; }
|
|
77
|
+
return { windowId, tty };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// --- fresh-session spawn (kimi) ----------------------------------------------
|
|
81
|
+
// Kimi Code has no positional-prompt interactive mode (-p is non-interactive and exits), so the
|
|
82
|
+
// baton opens a plain interactive `kimi`: its SessionStart hook claims the pending handoff.
|
|
83
|
+
export const RECAP_CMD = "kimi";
|
|
84
|
+
|
|
85
|
+
export function spawnFresh(projectDir) {
|
|
86
|
+
try {
|
|
87
|
+
if (process.platform !== "darwin" || process.env.TRANTOR_NO_HANDOFF_SPAWN === "1") return false;
|
|
88
|
+
const script = join(PLUGIN_BIN, "open-session.sh"); // canonical script — kimi's was identical
|
|
89
|
+
if (!existsSync(script)) return false;
|
|
90
|
+
const child = spawn("/bin/bash", [script, projectDir, RECAP_CMD], { detached: true, stdio: "ignore" });
|
|
91
|
+
child.unref();
|
|
92
|
+
return true;
|
|
93
|
+
} catch { return false; }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Arm the baton-close watcher (kimi variant — kimi/bin/baton-close.mjs reads kimi wire.jsonl).
|
|
97
|
+
// Same safety contract as canonical: auto-close strictly opt-in (config.autoCloseOriginal:true).
|
|
98
|
+
export function armBatonClose(handoffFile, originalWindowId, originalTty, conf = readConfig(), { auto = false } = {}) {
|
|
99
|
+
try {
|
|
100
|
+
if (process.platform !== "darwin" || !originalWindowId) return false;
|
|
101
|
+
if (process.env.TRANTOR_NO_BATON_CLOSE === "1" || conf.batonClose === false) return false;
|
|
102
|
+
if (auto && conf.autoCloseOriginal !== true) return false;
|
|
103
|
+
const closer = join(KIMI_BIN, "baton-close.mjs");
|
|
104
|
+
if (!existsSync(closer)) return false;
|
|
105
|
+
const child = spawn(process.execPath, [closer, handoffFile, String(originalWindowId), originalTty || ""], { detached: true, stdio: "ignore" });
|
|
106
|
+
child.unref();
|
|
107
|
+
return true;
|
|
108
|
+
} catch { return false; }
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// MANUAL one-command baton (ordering is load-bearing — see hooks/lib/handoff.mjs).
|
|
112
|
+
export function spawnBaton({ projectDir, handoffFile, conf = readConfig(),
|
|
113
|
+
_resolveWindow = resolveOriginalWindow, _spawnFresh = spawnFresh, _armClose = armBatonClose }) {
|
|
114
|
+
const { windowId, tty } = _resolveWindow();
|
|
115
|
+
const spawned = _spawnFresh(projectDir);
|
|
116
|
+
if (!spawned) return { spawned: false, armed: false, windowId: "" };
|
|
117
|
+
const armed = windowId ? _armClose(handoffFile, windowId, tty, conf) : false;
|
|
118
|
+
return { spawned, armed, windowId };
|
|
119
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// trantor/kimi — save a model-authored handoff (piped on stdin) for this project; the next Kimi
|
|
3
|
+
// session auto-loads it on SessionStart. With --baton: ALSO open a fresh `kimi` session and close
|
|
4
|
+
// THIS window once it takes over (the one-command manual baton behind the handoff skill).
|
|
5
|
+
// Without it: just write the file. Kimi port of bin/write-handoff.mjs.
|
|
6
|
+
import { writeFileSync, existsSync, mkdirSync } from "node:fs";
|
|
7
|
+
import { join, basename } from "node:path";
|
|
8
|
+
import { homedir, hostname } from "node:os";
|
|
9
|
+
import { execSync } from "node:child_process";
|
|
10
|
+
import { spawnBaton } from "./lib/handoff.mjs";
|
|
11
|
+
|
|
12
|
+
const baton = process.argv.includes("--baton");
|
|
13
|
+
// This runs through the agent's Bash tool, whose cwd IS the session's project directory.
|
|
14
|
+
const project = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
15
|
+
const name = basename(project);
|
|
16
|
+
let summary = ""; process.stdin.setEncoding("utf8");
|
|
17
|
+
for await (const c of process.stdin) summary += c;
|
|
18
|
+
const dir = join(homedir(), ".agent-bus", "handoffs");
|
|
19
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
20
|
+
const stamp = (() => { try { return execSync("date +%s", { encoding: "utf8" }).trim(); } catch { return String(process.pid); } })();
|
|
21
|
+
let git = ""; try { git = execSync("git -C " + JSON.stringify(project) + " status --short 2>/dev/null | head -30", { encoding: "utf8" }).trim(); } catch {}
|
|
22
|
+
const rec = { id: `${name}-${stamp}`, project, projectName: name, machine: hostname(), agent: "kimi", trigger: baton ? "manual-baton" : "manual-skill", stamp: Number(stamp) || 0, summary: summary.trim() || "(empty)", gitStatus: git, consumed: false };
|
|
23
|
+
const file = join(dir, `${rec.id}.json`);
|
|
24
|
+
writeFileSync(file, JSON.stringify(rec, null, 2));
|
|
25
|
+
console.log(`handoff saved: ${file}`);
|
|
26
|
+
|
|
27
|
+
if (baton) {
|
|
28
|
+
const { spawned, armed, windowId } = spawnBaton({ projectDir: project, handoffFile: file });
|
|
29
|
+
if (spawned) console.log(`baton: fresh kimi session opening (the handoff loads on its SessionStart)${armed ? ` — this window (${windowId}) closes once it takes over` : " — original window left open (couldn't detect it)"}`);
|
|
30
|
+
else console.log(`baton: could not spawn a fresh session (non-macOS or spawn disabled) — handoff saved, open a new session manually`);
|
|
31
|
+
}
|