trantor 0.18.148 → 0.18.149
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/bin/crew/state.mjs +1 -1
- package/bin/crew-runner.mjs +4 -2
- package/bin/docker-seat.mjs +33 -0
- package/bin/heavy-gate-shim/docker +2 -0
- package/bin/migrate-dispatcher.mjs +50 -0
- package/hub/auth.mjs +3 -3
- package/hub/routes/cards.mjs +13 -1
- package/hub/routes/dispatcher-operations.mjs +122 -0
- package/hub/routes/dispatcher.mjs +18 -9
- package/hub/store.mjs +20 -0
- package/hub.mjs +16 -1
- package/kimi.plugin.json +1 -1
- package/lib/dispatcher/admission.mjs +15 -3
- package/lib/dispatcher/operations.mjs +401 -0
- package/lib/dispatcher/preflight.mjs +2 -0
- package/lib/dispatcher/snapshot.mjs +72 -1
- package/lib/dispatcher/verifier.mjs +246 -0
- package/lib/docker-janitor.mjs +24 -14
- package/lib/store-contract.mjs +57 -0
- package/lib/store-pg.mjs +38 -3
- package/package.json +1 -1
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"metadata": {
|
|
8
8
|
"description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
|
|
9
|
-
"version": "0.18.
|
|
9
|
+
"version": "0.18.149"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "trantor",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
|
|
16
|
-
"version": "0.18.
|
|
16
|
+
"version": "0.18.149",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Sasha Bogojevic"
|
|
19
19
|
},
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.149",
|
|
4
4
|
"description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
|
|
5
5
|
"mcpServers": {
|
|
6
6
|
"relay": {
|
package/bin/crew/state.mjs
CHANGED
|
@@ -53,7 +53,7 @@ export function dropState(ctx, project, kind, agent = "", handle = "") {
|
|
|
53
53
|
// never rm, never volumes; docker absent skips silently. Same kill-switch as the process kill.
|
|
54
54
|
async function stopSeatContainers(ctx, project, agent) {
|
|
55
55
|
if (ctx.dry || ctx.env?.CREW_NO_PROC_KILL === "1" || !project || !agent) return;
|
|
56
|
-
const r = dockerSweep({ path: dockerStatePathFor(agent, project) });
|
|
56
|
+
const r = dockerSweep({ path: dockerStatePathFor(agent, project), owner: `${agent}:${project}` });
|
|
57
57
|
if (r.skipped || !r.stopped.length) return;
|
|
58
58
|
console.log(` 🧹 ${agent}:${project} — stopped ${r.stopped.length} container(s): ${r.stopped.join(", ")}`);
|
|
59
59
|
try {
|
package/bin/crew-runner.mjs
CHANGED
|
@@ -414,9 +414,10 @@ const PARKF = join(homedir(), ".agent-bus", `park-${PERSONA}-${PROJ}.json`);
|
|
|
414
414
|
// #9778: the seat's recorded containers, persisted per seat so a card close, a park or
|
|
415
415
|
// `trantor down <seat>` can stop what the seat started even after this runner is gone.
|
|
416
416
|
const DOCKERF = dockerStatePathFor(PERSONA, PROJ);
|
|
417
|
+
const DOCKER_SEAT = `${PERSONA}:${PROJ}`;
|
|
417
418
|
// One bus line per sweep, naming what was stopped; docker absent sweeps stay silent by contract.
|
|
418
419
|
async function janitorStop(why, card) {
|
|
419
|
-
const r = dockerSweep({ path: DOCKERF, card });
|
|
420
|
+
const r = dockerSweep({ path: DOCKERF, card, owner: DOCKER_SEAT });
|
|
420
421
|
if (r.skipped || !r.stopped.length) return;
|
|
421
422
|
const text = `🧹 ${SESSION} stopped ${r.stopped.length} container(s) (${why}): ${r.stopped.join(", ")}${r.failed.length ? ` · could not stop: ${r.failed.join(", ")}` : ""}`;
|
|
422
423
|
log(text);
|
|
@@ -1121,6 +1122,7 @@ exit $turn_exit`;
|
|
|
1121
1122
|
// so a handoff spawn would only leak an unmanaged interactive window.
|
|
1122
1123
|
TRANTOR_NO_HANDOFF_SPAWN: "1", TRANTOR_NO_BATON_SPAWN: "1",
|
|
1123
1124
|
TRANTOR_HEAVY_GATE_WAIT_DIR: HEAVY_WAIT_DIR,
|
|
1125
|
+
TRANTOR_DOCKER_SEAT: `${PERSONA}:${PROJ}`,
|
|
1124
1126
|
// Spelled out here, not HEAVY_SHIM_DIR: the turn drills run this function alone, without the module's constants (#14048).
|
|
1125
1127
|
PATH: `${join(import.meta.dirname, "heavy-gate-shim")}:${process.env.PATH || ""}`,
|
|
1126
1128
|
// #6206: the seat's transcript dir — a real CLI ignores it, a drill's fake CLI writes
|
|
@@ -1250,7 +1252,7 @@ exit $turn_exit`;
|
|
|
1250
1252
|
const busActive = await busActivitySince(busSeqBefore);
|
|
1251
1253
|
// #9778: containers this turn created are recorded against its card — and land on the telemetry
|
|
1252
1254
|
// row, which is the ledger the seat record (#7762) is derived from.
|
|
1253
|
-
const dockerNew = newContainers(dockerBefore, listContainers());
|
|
1255
|
+
const dockerNew = newContainers(dockerBefore, listContainers(), `${PERSONA}:${PROJ}`);
|
|
1254
1256
|
if (dockerNew.length) {
|
|
1255
1257
|
recordContainers({ path: DOCKERF, card: sessionCard || 0, containers: dockerNew });
|
|
1256
1258
|
log(`turn started ${dockerNew.length} container(s) — recorded against #${sessionCard || 0}: ${dockerNew.map(c => c.name || c.id).join(", ")}`);
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { accessSync, constants } from "node:fs";
|
|
4
|
+
import { delimiter, join, resolve } from "node:path";
|
|
5
|
+
import { SEAT_LABEL } from "../lib/docker-janitor.mjs";
|
|
6
|
+
|
|
7
|
+
const shim = resolve(import.meta.dirname, "heavy-gate-shim", "docker");
|
|
8
|
+
let binary = "";
|
|
9
|
+
for (const dir of String(process.env.PATH || "").split(delimiter)) {
|
|
10
|
+
if (!dir) continue;
|
|
11
|
+
const candidate = resolve(dir, "docker");
|
|
12
|
+
if (candidate === shim) continue;
|
|
13
|
+
try {
|
|
14
|
+
accessSync(candidate, constants.X_OK);
|
|
15
|
+
binary = candidate;
|
|
16
|
+
break;
|
|
17
|
+
} catch {}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
if (!binary) {
|
|
21
|
+
console.error("docker: executable not found");
|
|
22
|
+
process.exit(127);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const args = process.argv.slice(2);
|
|
26
|
+
const owner = process.env.TRANTOR_DOCKER_SEAT || "";
|
|
27
|
+
const command = args[0] === "container" ? 1 : 0;
|
|
28
|
+
if (owner && ["run", "create"].includes(args[command])) {
|
|
29
|
+
args.splice(command + 1, 0, "--label", `${SEAT_LABEL}=${owner}`);
|
|
30
|
+
}
|
|
31
|
+
const result = spawnSync(binary, args, { stdio: "inherit" });
|
|
32
|
+
if (result.error) console.error(`docker: ${result.error.message}`);
|
|
33
|
+
process.exit(result.status ?? 1);
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { PgStore } from '../lib/store-pg.mjs';
|
|
5
|
+
import { DISPATCHER_MIGRATION_ID, DISPATCHER_MIGRATION_LOCK_SQL,
|
|
6
|
+
DISPATCHER_SCHEMA_SQL, DISPATCHER_SCHEMA_VERSION } from '../lib/dispatcher/store.mjs';
|
|
7
|
+
import { backfillAttempts } from '../lib/dispatcher/migrate-attempts.mjs';
|
|
8
|
+
import { DISPATCHER_INTEGRATION_SQL } from '../lib/store-contract.mjs';
|
|
9
|
+
|
|
10
|
+
export async function migrateDispatcher({ store, batchSize = 1000, onCheckpoint = () => {} }) {
|
|
11
|
+
if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > 1000) {
|
|
12
|
+
throw new RangeError('batch size must be between 1 and 1000');
|
|
13
|
+
}
|
|
14
|
+
const transaction = store.transaction.bind(store);
|
|
15
|
+
await transaction(async client => {
|
|
16
|
+
await client.query(DISPATCHER_MIGRATION_LOCK_SQL);
|
|
17
|
+
await client.query(DISPATCHER_SCHEMA_SQL);
|
|
18
|
+
await client.query(DISPATCHER_INTEGRATION_SQL);
|
|
19
|
+
await client.query(`INSERT INTO dispatcher_migrations(id,schema_version,checkpoint,completed_at_ms)
|
|
20
|
+
VALUES($1,$2,$3,NULL) ON CONFLICT(id) DO NOTHING`,
|
|
21
|
+
[DISPATCHER_MIGRATION_ID, DISPATCHER_SCHEMA_VERSION, { lastKey: null, scanned: 0 }]);
|
|
22
|
+
});
|
|
23
|
+
let checkpoint;
|
|
24
|
+
do {
|
|
25
|
+
checkpoint = await backfillAttempts({ transaction, batchSize });
|
|
26
|
+
await onCheckpoint(checkpoint);
|
|
27
|
+
} while (!checkpoint.complete);
|
|
28
|
+
return checkpoint;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function main() {
|
|
32
|
+
const { values } = parseArgs({ options: { 'batch-size': { type: 'string', default: '1000' },
|
|
33
|
+
help: { type: 'boolean', default: false } } });
|
|
34
|
+
if (values.help) {
|
|
35
|
+
process.stdout.write('Usage: node bin/migrate-dispatcher.mjs [--batch-size 1..1000]\nUses RELAY_DATABASE_URL or DATABASE_URL for an initialized PostgreSQL hub.\n');
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const url = process.env.RELAY_DATABASE_URL || process.env.DATABASE_URL;
|
|
39
|
+
if (!url) throw new Error('RELAY_DATABASE_URL or DATABASE_URL is required');
|
|
40
|
+
const { default: pg } = await import('pg');
|
|
41
|
+
const pool = new pg.Pool({ connectionString: url });
|
|
42
|
+
try {
|
|
43
|
+
await migrateDispatcher({ store: new PgStore({ pool }), batchSize: Number(values['batch-size']),
|
|
44
|
+
onCheckpoint: checkpoint => process.stdout.write(`${JSON.stringify(checkpoint)}\n`) });
|
|
45
|
+
} finally { await pool.end(); }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
49
|
+
main().catch(error => { process.stderr.write(`Dispatcher migration failed: ${error.message}\n`); process.exitCode = 1; });
|
|
50
|
+
}
|
package/hub/auth.mjs
CHANGED
|
@@ -17,7 +17,7 @@ const OWNER_BODY_CAPS = new Map([
|
|
|
17
17
|
["/session/chat", BODY_CAP_OWNER_CHAT],
|
|
18
18
|
["/handoff", BODY_CAP_DEFAULT], ["/task", BODY_CAP_DEFAULT], ["/task/update", BODY_CAP_DEFAULT],
|
|
19
19
|
]);
|
|
20
|
-
function bodyCap(P) { return P === "/session/prompt" ? BODY_CAP_PROMPT : BODY_CAP_DEFAULT; }
|
|
20
|
+
function bodyCap(P) { return P === "/advise" ? 1024 * 1024 : P === "/session/prompt" ? BODY_CAP_PROMPT : BODY_CAP_DEFAULT; }
|
|
21
21
|
function ownerBodyCap(req, P) {
|
|
22
22
|
const cap = OWNER_BODY_CAPS.get(P) || bodyCap(P);
|
|
23
23
|
if (cap <= bodyCap(P) || !Object.values(HDR).every(h => req.headers[h])) return bodyCap(P);
|
|
@@ -170,7 +170,7 @@ function projectFromRequest(P, q, b, method) {
|
|
|
170
170
|
return canon(String(b?.project || q?.project || "").slice(0, 80));
|
|
171
171
|
}
|
|
172
172
|
// Cross-project actions require a declared link or the operator identity, even with wildcard scopes (#6228).
|
|
173
|
-
const CROSS_PROJECT_ENDPOINTS = new Set(["/send", "/task", "/task/update", "/register", "/invite"]);
|
|
173
|
+
const CROSS_PROJECT_ENDPOINTS = new Set(["/send", "/task", "/task/update", "/register", "/invite", "/dispatch"]);
|
|
174
174
|
function projectsLinked(a, b) {
|
|
175
175
|
if (!a || !b || a === b) return true;
|
|
176
176
|
return overseerPolicy().links.some(l => {
|
|
@@ -204,7 +204,7 @@ function crossProjectTarget(P, b) {
|
|
|
204
204
|
const to = String(b.to);
|
|
205
205
|
return canon(state.peers[to]?.project || (to.includes(":") ? to.slice(to.lastIndexOf(":") + 1) : ""));
|
|
206
206
|
}
|
|
207
|
-
if (P === "/task" || P === "/register") return canon(String(b?.project || "").slice(0, 80));
|
|
207
|
+
if (P === "/task" || P === "/register" || P === "/dispatch") return canon(String(b?.project || "").slice(0, 80));
|
|
208
208
|
if (P === "/task/update") {
|
|
209
209
|
const t = state.tasks.find(x => x.id === Number(b?.id));
|
|
210
210
|
return t?.project || "";
|
package/hub/routes/cards.mjs
CHANGED
|
@@ -206,7 +206,19 @@ export async function routeCards({ req, res, q, P, auth, ctx }) {
|
|
|
206
206
|
markDirty(); return json(res, 200, { ok: true, task: t });
|
|
207
207
|
}
|
|
208
208
|
if (req.method === "POST" && P === "/task/update") { // move/edit a card
|
|
209
|
-
const b = await body(req);
|
|
209
|
+
const b = await body(req);
|
|
210
|
+
if (ctx.dispatcher) {
|
|
211
|
+
try {
|
|
212
|
+
const guarded = crossProjectGuard(auth, P, b);
|
|
213
|
+
if (!guarded.ok) return json(res, guarded.code, { error: guarded.error });
|
|
214
|
+
const task = await ctx.mutateDispatcherCard(b, auth);
|
|
215
|
+
if (task) return json(res, 200, { ok: true, task });
|
|
216
|
+
} catch (error) {
|
|
217
|
+
const status = error.name === 'ZodError' ? 422 : error.status || 503;
|
|
218
|
+
return json(res, status, { code: error.code || 'schema_invalid' });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const found = state.tasks.find(x => x.id === Number(b.id));
|
|
210
222
|
const t = found && copyTask(found);
|
|
211
223
|
if (!t) return json(res, 404, { error: "no such task" });
|
|
212
224
|
const cpg = crossProjectGuard(auth, P, b);
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { reject } from '../../lib/dispatcher/admission.mjs';
|
|
3
|
+
import { requireRole } from '../../lib/dispatcher/operations.mjs';
|
|
4
|
+
|
|
5
|
+
export function dispatcherEndpoint(method, path, query) {
|
|
6
|
+
return path === '/dispatch' || path.startsWith('/dispatch/') || path.startsWith('/dispatcher/')
|
|
7
|
+
|| method === 'POST' && path === '/advise'
|
|
8
|
+
|| method === 'GET' && path === '/capacity' && query.version !== undefined;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
|
|
12
|
+
if (!dispatcherEndpoint(req.method, P, q) || P === '/dispatch' || P === '/advise'
|
|
13
|
+
|| /^\/dispatch\/[^/]+(?:\/(heartbeat|events|stop))?$/.test(P)) return false;
|
|
14
|
+
try {
|
|
15
|
+
if (ctx.AUTH_MODE === 'off' || !ctx.dispatcher) reject('dispatch_unavailable', 503);
|
|
16
|
+
if (!auth?.ok || !auth.identity || !auth.pubkey || auth.warning) reject('permission_denied', 403);
|
|
17
|
+
const service = ctx.dispatcher;
|
|
18
|
+
const orgId = service.orgId(auth);
|
|
19
|
+
if (!orgId) reject('permission_denied', 403);
|
|
20
|
+
const actor = { pubkey: auth.pubkey };
|
|
21
|
+
if (req.method === 'POST' && P === '/dispatcher/verifiers') {
|
|
22
|
+
return ctx.json(res, 200, await service.verifier.registerGrant(orgId, await ctx.body(req), actor));
|
|
23
|
+
}
|
|
24
|
+
if (req.method === 'POST' && P === '/dispatcher/verification-jobs/claim') {
|
|
25
|
+
return ctx.json(res, 200, await service.verifier.claim(orgId, await ctx.body(req), actor));
|
|
26
|
+
}
|
|
27
|
+
const beat = /^\/dispatcher\/verification-jobs\/([^/]+)\/heartbeat$/.exec(P);
|
|
28
|
+
if (req.method === 'POST' && beat) {
|
|
29
|
+
return ctx.json(res, 200, await service.verifier.heartbeat(orgId, decodeURIComponent(beat[1]), await ctx.body(req), actor));
|
|
30
|
+
}
|
|
31
|
+
const verify = /^\/dispatch\/([^/]+)\/(verify|acceptance)$/.exec(P);
|
|
32
|
+
if (req.method === 'POST' && verify) {
|
|
33
|
+
const id = decodeURIComponent(verify[1]);
|
|
34
|
+
const attempt = await service.store.attempt(orgId, id);
|
|
35
|
+
if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
|
|
36
|
+
const result = verify[2] === 'verify'
|
|
37
|
+
? await service.verifier.enqueue(orgId, id, await ctx.body(req), actor)
|
|
38
|
+
: await service.verifier.accept(orgId, id, await ctx.body(req), actor);
|
|
39
|
+
return ctx.json(res, verify[2] === 'verify' && !result.replayed ? 202 : 200, result);
|
|
40
|
+
}
|
|
41
|
+
const read = async (project, operation) => service.store.locked(orgId, async client => {
|
|
42
|
+
await requireRole(client, orgId, actor, project, ['read', 'write', 'approver', 'owner']);
|
|
43
|
+
return operation(client);
|
|
44
|
+
});
|
|
45
|
+
if (req.method === 'GET' && P === '/dispatcher/pacing') {
|
|
46
|
+
const request = z.strictObject({ project: z.string().min(1).max(8192) }).parse(q);
|
|
47
|
+
return ctx.json(res, 200, await service.pacing(orgId, request, actor));
|
|
48
|
+
}
|
|
49
|
+
if (req.method === 'GET' && P === '/capacity') {
|
|
50
|
+
if (q.version !== '1' || !q.project) reject('schema_invalid', 422);
|
|
51
|
+
return ctx.json(res, 200, await service.capacity(orgId, q, actor));
|
|
52
|
+
}
|
|
53
|
+
if (req.method === 'POST' && P === '/dispatcher/evidence') {
|
|
54
|
+
return ctx.json(res, 201, await service.registerEvidence(orgId, await ctx.body(req), actor));
|
|
55
|
+
}
|
|
56
|
+
if (req.method === 'POST' && P === '/dispatcher/cards') {
|
|
57
|
+
return ctx.json(res, 201, await service.registerCard(orgId, await ctx.body(req), actor));
|
|
58
|
+
}
|
|
59
|
+
if (req.method === 'POST' && P === '/dispatcher/collectors') {
|
|
60
|
+
return ctx.json(res, 200, await service.registerCollector(orgId, await ctx.body(req), actor));
|
|
61
|
+
}
|
|
62
|
+
if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
|
|
63
|
+
return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
|
|
64
|
+
}
|
|
65
|
+
if (req.method === 'POST' && P === '/dispatcher/control') {
|
|
66
|
+
return ctx.json(res, 200, await service.executor.kill(orgId, await ctx.body(req), actor));
|
|
67
|
+
}
|
|
68
|
+
if (req.method === 'GET' && P === '/dispatcher/policy') {
|
|
69
|
+
const result = await service.store.locked(orgId, async client => {
|
|
70
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
71
|
+
return (await client.query(`SELECT p.row FROM dispatcher_policies p JOIN dispatcher_authority_state s
|
|
72
|
+
ON s.org_id=p.org_id AND s.policy_version=p.version WHERE p.org_id=$1`, [orgId])).rows[0]?.row || null;
|
|
73
|
+
});
|
|
74
|
+
return ctx.json(res, 200, { schemaVersion: 1, policy: result });
|
|
75
|
+
}
|
|
76
|
+
const topUp = /^\/dispatch\/([^/]+)\/top-up$/.exec(P);
|
|
77
|
+
const decide = /^\/dispatch\/([^/]+)\/top-ups\/([^/]+)\/decision$/.exec(P);
|
|
78
|
+
if (topUp || decide) {
|
|
79
|
+
const id = decodeURIComponent((topUp || decide)[1]);
|
|
80
|
+
const attempt = await service.store.attempt(orgId, id);
|
|
81
|
+
if (!attempt || !ctx.canRead(auth, attempt.project)) reject('attempt_missing', 404);
|
|
82
|
+
if (topUp && req.method === 'GET') {
|
|
83
|
+
const asks = await read(attempt.project, async client => (await client.query(
|
|
84
|
+
'SELECT row FROM dispatcher_budget_asks WHERE org_id=$1 AND attempt_id=$2 ORDER BY expires_at_ms DESC', [orgId, id])).rows.map(r => r.row));
|
|
85
|
+
return ctx.json(res, 200, { schemaVersion: 1, asks });
|
|
86
|
+
}
|
|
87
|
+
if (decide && req.method === 'POST') {
|
|
88
|
+
const result = await service.finance.topUp(orgId, id, decodeURIComponent(decide[2]), await ctx.body(req), actor);
|
|
89
|
+
return ctx.json(res, result.replayed ? 200 : result.state === 'cancelled' ? 200 : 202, { schemaVersion: 1, ...result });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const repair = /^\/dispatcher\/account-bindings\/([^/]+)\/repairs$/.exec(P);
|
|
93
|
+
if (repair && req.method === 'POST') {
|
|
94
|
+
const result = await service.finance.repairBinding(orgId, decodeURIComponent(repair[1]), await ctx.body(req), actor);
|
|
95
|
+
return ctx.json(res, result.state === 'applied' || result.replayed ? 200 : 202, { schemaVersion: 1, ...result });
|
|
96
|
+
}
|
|
97
|
+
const repairRead = /^\/dispatcher\/account-binding-repairs\/([^/]+)$/.exec(P);
|
|
98
|
+
if (repairRead && req.method === 'GET') {
|
|
99
|
+
const row = await service.store.locked(orgId, async client => {
|
|
100
|
+
await requireRole(client, orgId, actor, '*', ['owner'], true);
|
|
101
|
+
return (await client.query('SELECT row FROM dispatcher_account_binding_repairs WHERE org_id=$1 AND id=$2',
|
|
102
|
+
[orgId, decodeURIComponent(repairRead[1])])).rows[0]?.row;
|
|
103
|
+
});
|
|
104
|
+
if (!row) reject('repair_missing', 404);
|
|
105
|
+
return ctx.json(res, 200, { schemaVersion: 1, repair: row });
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
} catch (error) {
|
|
109
|
+
const status = error instanceof z.ZodError || error instanceof URIError ? 422 : error.status || 503;
|
|
110
|
+
const code = status === 422 ? 'schema_invalid' : error.code || 'dispatch_unavailable';
|
|
111
|
+
return ctx.json(res, status, { schemaVersion: 1, code,
|
|
112
|
+
reasons: [{ code, resource: null, retryAtMs: null }], retryable: status === 429 || status === 503 });
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function dispatcherUnavailable({ req, res, P, q, ctx }) {
|
|
117
|
+
if (!dispatcherEndpoint(req.method, P, q)) return false;
|
|
118
|
+
if (ctx.AUTH_MODE !== 'off' && ctx.dispatcher) return false;
|
|
119
|
+
const code = 'dispatch_unavailable';
|
|
120
|
+
return ctx.json(res, 503, { schemaVersion: 1, code,
|
|
121
|
+
reasons: [{ code, resource: null, retryAtMs: null }], retryable: true });
|
|
122
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { WorkCardSchema, UsageEventSchema, ArtifactSchema, SnapshotSchema, PolicySchema } from '../../lib/dispatcher/schemas.mjs';
|
|
3
|
-
import { DispatchRequestSchema, reject } from '../../lib/dispatcher/admission.mjs';
|
|
2
|
+
import { WorkCardSchema, UsageEventSchema, ArtifactSchema, SnapshotSchema, PolicySchema, MAX_ADVISE_CARDS } from '../../lib/dispatcher/schemas.mjs';
|
|
3
|
+
import { DispatchRequestSchema, reject, storedScopeAllows } from '../../lib/dispatcher/admission.mjs';
|
|
4
4
|
import { canonicalJson, verifySnapshot } from '../../lib/dispatcher/snapshot.mjs';
|
|
5
5
|
import { verifyPolicy } from '../../lib/dispatcher/policy.mjs';
|
|
6
6
|
import { plan } from '../../lib/dispatcher/planner.mjs';
|
|
@@ -8,8 +8,8 @@ import { plan } from '../../lib/dispatcher/planner.mjs';
|
|
|
8
8
|
const text = z.string().min(1).max(8192);
|
|
9
9
|
const positive = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
|
|
10
10
|
export const AdviceRequestSchema = z.strictObject({ schemaVersion: z.literal(1), project: text,
|
|
11
|
-
snapshotId: text.optional(), policyVersion: text.optional(), cards: z.array(WorkCardSchema),
|
|
12
|
-
drafts: z.array(WorkCardSchema).optional() });
|
|
11
|
+
snapshotId: text.optional(), policyVersion: text.optional(), cards: z.array(WorkCardSchema).max(MAX_ADVISE_CARDS),
|
|
12
|
+
drafts: z.array(WorkCardSchema).max(MAX_ADVISE_CARDS).optional() }).refine(r => r.cards.length + (r.drafts?.length || 0) <= MAX_ADVISE_CARDS);
|
|
13
13
|
export const AdviceAuthoritySchema = z.strictObject({ snapshot: SnapshotSchema, policy: PolicySchema });
|
|
14
14
|
export const AttemptEventSchema = z.discriminatedUnion('kind', [
|
|
15
15
|
z.strictObject({ kind: z.literal('usage'), event: UsageEventSchema }),
|
|
@@ -19,15 +19,17 @@ export const AttemptEventSchema = z.discriminatedUnion('kind', [
|
|
|
19
19
|
|
|
20
20
|
async function readable(client, orgId, actor, project) {
|
|
21
21
|
const row = (await client.query('SELECT scopes,revoked_at FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
|
|
22
|
-
if (!row || row.revoked_at != null || !['read','write','approver','owner']
|
|
23
|
-
|
|
22
|
+
if (!row || row.revoked_at != null || !storedScopeAllows(row, project, ['read','write','approver','owner'])) {
|
|
23
|
+
reject('permission_denied', 403);
|
|
24
|
+
}
|
|
25
|
+
return row;
|
|
24
26
|
}
|
|
25
27
|
|
|
26
28
|
async function advise(service, orgId, input, actor, auth) {
|
|
27
29
|
const request = AdviceRequestSchema.parse(input);
|
|
28
30
|
if ([...request.cards, ...request.drafts || []].some(c => c.project !== request.project)) reject('permission_denied', 403);
|
|
29
31
|
return service.store.locked(orgId, async client => {
|
|
30
|
-
await readable(client, orgId, actor, request.project);
|
|
32
|
+
const identity = await readable(client, orgId, actor, request.project);
|
|
31
33
|
const authority = AdviceAuthoritySchema.parse(await service.readAdvice(client, { orgId, request, actor }));
|
|
32
34
|
let snapshot;
|
|
33
35
|
try { snapshot = verifySnapshot(authority.snapshot); verifyPolicy(authority.policy); } catch { reject('snapshot_invalid'); }
|
|
@@ -37,12 +39,15 @@ async function advise(service, orgId, input, actor, auth) {
|
|
|
37
39
|
const stored = snapshot.readyQueue.find(c => c.project === card.project && c.card === card.card);
|
|
38
40
|
if (!stored || canonicalJson(stored) !== canonicalJson(card)) reject('card_stale');
|
|
39
41
|
}
|
|
40
|
-
const
|
|
42
|
+
const cards = [...request.cards, ...request.drafts || []].sort((a,b) => a.project < b.project ? -1 : a.project > b.project ? 1 : a.card - b.card);
|
|
43
|
+
if (new Set(cards.map(c => `${c.project}:${c.card}`)).size !== cards.length
|
|
44
|
+
|| request.drafts?.some(c => snapshot.readyQueue.some(s => s.project === c.project && s.card === c.card))) reject('schema_invalid', 422);
|
|
45
|
+
const decision = plan({ ...authority, cards });
|
|
41
46
|
const dispatchable = !request.drafts?.length;
|
|
42
47
|
if (dispatchable) await client.query(`INSERT INTO dispatcher_decisions VALUES($1,$2,$3,$4,$5,$6,$7)
|
|
43
48
|
ON CONFLICT(org_id,id) DO NOTHING`, [orgId, decision.id, request.project, decision.snapshotId,
|
|
44
49
|
decision.policyVersion, decision.createdAtMs, decision]);
|
|
45
|
-
return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, auth) };
|
|
50
|
+
return { schemaVersion: 1, dispatchable, decision: service.projectDecision(decision, { ...auth, identity }) };
|
|
46
51
|
});
|
|
47
52
|
}
|
|
48
53
|
|
|
@@ -61,6 +66,10 @@ export async function routeDispatcher({ req, res, q: _q, P, auth, ctx }) {
|
|
|
61
66
|
if (advice) return ctx.json(res, 200, await advise(service, orgId, await ctx.body(req), actor, auth));
|
|
62
67
|
if (dispatch) {
|
|
63
68
|
const input = DispatchRequestSchema.parse(await ctx.body(req));
|
|
69
|
+
if (ctx.crossProjectGuard) {
|
|
70
|
+
const cross = ctx.crossProjectGuard(auth, '/dispatch', input);
|
|
71
|
+
if (!cross.ok) reject('permission_denied', 403);
|
|
72
|
+
}
|
|
64
73
|
const result = await service.admission.dispatch(orgId, input, actor);
|
|
65
74
|
return ctx.json(res, result.replayed ? 200 : 202, result);
|
|
66
75
|
}
|
package/hub/store.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import { randomBytes } from "node:crypto";
|
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { createPersistHealth } from "../lib/persist-health.mjs";
|
|
6
6
|
import { DEFAULT_ORG } from "../lib/store-contract.mjs";
|
|
7
|
+
import { createDispatcherOperations } from "../lib/dispatcher/operations.mjs";
|
|
7
8
|
|
|
8
9
|
export async function createStoreRuntime({ STORE_KIND, PG_URL, ORG_ID, DATA, diagnostics = null }) {
|
|
9
10
|
function emptyState() {
|
|
@@ -351,6 +352,7 @@ const HUB_SRC = `hub-${process.pid}-${randomBytes(4).toString("hex")}`;
|
|
|
351
352
|
if (runTaskBootMigrations()) dirty = true;
|
|
352
353
|
let lastPersisted = durableStore ? snapshotState() : null;
|
|
353
354
|
const recordPersistFailure = (kind, error) => {
|
|
355
|
+
dispatcher?.store.closeAdmission();
|
|
354
356
|
dirty = true;
|
|
355
357
|
const failure = persistHealth.failed(error);
|
|
356
358
|
if (failure.shouldLog) {
|
|
@@ -432,7 +434,25 @@ setInterval(persist, persistTickMs).unref?.();
|
|
|
432
434
|
}).catch(error => process.stderr.write(`[trantor] LISTEN ${error.message || error} — external writes will NOT surface until restart\n`));
|
|
433
435
|
};
|
|
434
436
|
|
|
437
|
+
let dispatcher = null;
|
|
438
|
+
if (durableStore) {
|
|
439
|
+
const migrated = (await durableStore.pool.query("SELECT to_regclass('dispatcher_integration_migrations') AS name")).rows[0]?.name;
|
|
440
|
+
if (migrated) dispatcher = createDispatcherOperations({ durableStore, orgId: ORG_ID, source: HUB_SRC });
|
|
441
|
+
}
|
|
435
442
|
return {
|
|
443
|
+
dispatcher,
|
|
444
|
+
async mutateDispatcherCard(input, auth) {
|
|
445
|
+
if (!dispatcher) return null;
|
|
446
|
+
const managed = (await durableStore.pool.query('SELECT card FROM dispatcher_cards WHERE org_id=$1 AND card=$2', [ORG_ID, input.id])).rows[0];
|
|
447
|
+
if (!managed) return null;
|
|
448
|
+
if (!auth?.pubkey || !auth.identity || auth.warning) throw Object.assign(new Error('permission_denied'), { status: 403, code: 'permission_denied' });
|
|
449
|
+
const task = await dispatcher.mutateCard(ORG_ID, input, { pubkey: auth.pubkey });
|
|
450
|
+
const at = state.tasks.findIndex(t => t.id === task.id);
|
|
451
|
+
if (at !== -1) state.tasks[at] = task;
|
|
452
|
+
const previous = lastPersisted.tasks.findIndex(t => t.id === task.id);
|
|
453
|
+
if (previous !== -1) lastPersisted.tasks[previous] = task;
|
|
454
|
+
return task;
|
|
455
|
+
},
|
|
436
456
|
state, durableStore, persist, persistHealth, markDirty, copyTask, copyMessage, reload, startChangeSubscription,
|
|
437
457
|
turnTelemetry, HUB_SRC, appendTaskLog, appendTaskNote, cleanChecklist, cleanDrill, hasDrillLine, stripNulText,
|
|
438
458
|
};
|
package/hub.mjs
CHANGED
|
@@ -23,6 +23,8 @@ import { migrateReviews } from "./hub/review-store.mjs";
|
|
|
23
23
|
import { routeDevices } from "./hub/routes/devices.mjs";
|
|
24
24
|
import { createSessionRuntime } from "./hub/routes/session.mjs";
|
|
25
25
|
import { routeWorktreeStatus } from "./hub/routes/worktree-status.mjs";
|
|
26
|
+
import { routeDispatcher } from "./hub/routes/dispatcher.mjs";
|
|
27
|
+
import { dispatcherUnavailable, routeDispatcherOperations } from "./hub/routes/dispatcher-operations.mjs";
|
|
26
28
|
import { routeCapacity } from "./hub/routes/capacity.mjs"; // #14653: registered ahead of sessionChat so the /machines/health mirror runs first
|
|
27
29
|
import { createNotifier } from "./hub/notifier.mjs";
|
|
28
30
|
import { createHubDiagnostics } from "./lib/hub-diagnostics.mjs";
|
|
@@ -136,12 +138,24 @@ const context = {
|
|
|
136
138
|
hubSend: duty.hubSend, assertNoSecrets, AUTH_MODE, ONLINE_MS, PEER_TTL_MS,
|
|
137
139
|
REAP_GRACE_MS, CONTRACT_WINDOW_MS, PUBLIC_URL,
|
|
138
140
|
};
|
|
141
|
+
if (store.dispatcher && AUTH_MODE !== 'off') {
|
|
142
|
+
let ticking = false;
|
|
143
|
+
setInterval(async () => {
|
|
144
|
+
if (ticking) return;
|
|
145
|
+
ticking = true;
|
|
146
|
+
try { await store.dispatcher.tick(); }
|
|
147
|
+
catch (error) {
|
|
148
|
+
store.dispatcher.store.closeAdmission();
|
|
149
|
+
console.error(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
|
|
150
|
+
} finally { ticking = false; }
|
|
151
|
+
}, 1000).unref();
|
|
152
|
+
}
|
|
139
153
|
const sessionChat = createSessionRuntime({
|
|
140
154
|
state: store.state, markDirty: store.markDirty,
|
|
141
155
|
appendEvent: events.appendEvent, pushEventToStreams: events.pushEventToStreams, notifier,
|
|
142
156
|
attachmentsDir: join(DATA_DIR, "attachments"),
|
|
143
157
|
});
|
|
144
|
-
const routes = [routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
|
|
158
|
+
const routes = [routeDispatcher, routeDispatcherOperations, routeWorktreeStatus, routeDevices, routeAdmin, routeCards, routeInsights, routeMessages, routeReviews, routeCapacity, sessionChat.route];
|
|
145
159
|
|
|
146
160
|
const publicAuth = createAuthRuntime({
|
|
147
161
|
state: store.state, markDirty: store.markDirty, AUTH_MODE: "enforce", SUPERSEDE_GRACE_MS,
|
|
@@ -160,6 +174,7 @@ function requestHandler(runtime, ctx, gate = null) {
|
|
|
160
174
|
const q = Object.fromEntries(u.searchParams);
|
|
161
175
|
const P = u.pathname;
|
|
162
176
|
if (gate && !gate.admit(req, res, P)) return;
|
|
177
|
+
if (dispatcherUnavailable({ req, res, P, q, ctx })) return;
|
|
163
178
|
const cap = gate ? runtime.bodyCap(P) : runtime.ownerBodyCap(req, P);
|
|
164
179
|
let ownerAuth;
|
|
165
180
|
if (req.method === "POST") {
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.149",
|
|
4
4
|
"description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
|
|
5
5
|
"interface": {
|
|
6
6
|
"displayName": "Trantor",
|
|
@@ -60,15 +60,27 @@ export function reject(code, status = 409, resource = null, retryAtMs = null) {
|
|
|
60
60
|
throw error;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
const RoleSchema = z.enum(['read', 'write', 'approver', 'owner']);
|
|
64
|
+
const StoredScopesSchema = z.union([z.array(z.strictObject({ project: text, role: RoleSchema })),
|
|
65
|
+
z.record(text, RoleSchema)]);
|
|
66
|
+
|
|
67
|
+
export function storedScopeAllows(identity, project, roles, wildcardOnly = false) {
|
|
68
|
+
const parsed = StoredScopesSchema.safeParse(identity?.scopes);
|
|
69
|
+
if (!parsed.success) return false;
|
|
70
|
+
const scopes = Array.isArray(parsed.data) ? parsed.data
|
|
71
|
+
: Object.entries(parsed.data).map(([project, role]) => ({ project, role }));
|
|
72
|
+
return scopes.some(scope => roles.includes(scope.role)
|
|
73
|
+
&& (scope.project === '*' || !wildcardOnly && scope.project === project));
|
|
74
|
+
}
|
|
75
|
+
|
|
63
76
|
export async function requireIdentity(client, orgId, actor, project, financial = false, producers = []) {
|
|
64
77
|
const identity = (await client.query('SELECT * FROM identities WHERE org_id=$1 AND pubkey=$2', [orgId, actor.pubkey])).rows[0];
|
|
65
78
|
if (!identity || identity.revoked_at != null) reject('permission_denied', 403);
|
|
66
79
|
if (financial) {
|
|
67
|
-
if (identity.kind !== 'human' || identity
|
|
80
|
+
if (identity.kind !== 'human' || !storedScopeAllows(identity, project, ['owner'], true) || producers.includes(identity.pubkey)) {
|
|
68
81
|
reject('permission_denied', 403);
|
|
69
82
|
}
|
|
70
|
-
} else if (!['write', 'approver', 'owner']
|
|
71
|
-
&& !['write', 'approver', 'owner'].includes(identity.scopes['*'])) reject('permission_denied', 403);
|
|
83
|
+
} else if (!storedScopeAllows(identity, project, ['write', 'approver', 'owner'])) reject('permission_denied', 403);
|
|
72
84
|
return identity;
|
|
73
85
|
}
|
|
74
86
|
|