trantor 0.18.154 → 0.18.157
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-runner.mjs +7 -7
- package/hub/routes/messages.mjs +5 -0
- package/hub.mjs +2 -10
- package/kimi.plugin.json +1 -1
- package/lib/dispatcher/accounts.mjs +17 -9
- package/lib/dispatcher/evidence-bridge.mjs +12 -13
- package/lib/dispatcher/operations.mjs +74 -40
- package/lib/dispatcher/store.mjs +27 -0
- 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.157"
|
|
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.157",
|
|
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.157",
|
|
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-runner.mjs
CHANGED
|
@@ -112,7 +112,7 @@ const DIR = RUNNER_ARGV[1] || process.cwd();
|
|
|
112
112
|
const PROJ = process.env.RELAY_PROJECT || runnerOption("project") || resolveProject(DIR);
|
|
113
113
|
let machineConfig = {};
|
|
114
114
|
try { machineConfig = JSON.parse(readFileSync(join(process.env.AGENT_BUS_DIR || process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus"), "config.json"), "utf8")); } catch {}
|
|
115
|
-
const MACHINE_LABEL = machineLabel(machineConfig);
|
|
115
|
+
const MACHINE_LABEL = machineLabel(machineConfig) || hostId();
|
|
116
116
|
|
|
117
117
|
function gitOut(args, cwd = DIR) {
|
|
118
118
|
const r = spawnSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], timeout: 8000 });
|
|
@@ -228,7 +228,7 @@ async function api(path, body) {
|
|
|
228
228
|
let payload;
|
|
229
229
|
if (body) {
|
|
230
230
|
payload = { ...body };
|
|
231
|
-
if (path === "/register") payload.machine = MACHINE_LABEL
|
|
231
|
+
if (path === "/register") payload.machine = MACHINE_LABEL;
|
|
232
232
|
}
|
|
233
233
|
const opts = body
|
|
234
234
|
? { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body: JSON.stringify(payload) }
|
|
@@ -699,7 +699,7 @@ async function registerStatus(status, extra = {}) {
|
|
|
699
699
|
}
|
|
700
700
|
const url = HUB + "/register";
|
|
701
701
|
const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
|
|
702
|
-
payload.machine = MACHINE_LABEL
|
|
702
|
+
payload.machine = MACHINE_LABEL;
|
|
703
703
|
payload.accountIdentity = cachedAccountIdentity;
|
|
704
704
|
const body = JSON.stringify(payload);
|
|
705
705
|
try {
|
|
@@ -1064,7 +1064,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
|
|
|
1064
1064
|
} : undefined;
|
|
1065
1065
|
const presencePayload = { session: SESSION, project: PROJ, status: `working · ${trigger}`, persona: PERSONA,
|
|
1066
1066
|
agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
|
|
1067
|
-
presencePayload.machine = MACHINE_LABEL
|
|
1067
|
+
presencePayload.machine = MACHINE_LABEL;
|
|
1068
1068
|
presencePayload.accountIdentity = cachedAccountIdentity;
|
|
1069
1069
|
writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
|
|
1070
1070
|
presence: { intervalMs: PRESENCE_MS, payload: presencePayload },
|
|
@@ -1379,7 +1379,7 @@ exit $turn_exit`;
|
|
|
1379
1379
|
provider: providerForModel(DRIVER, actualModel), model: actualModel,
|
|
1380
1380
|
effort: effortName(turnEffort.effort), harness: DRIVER,
|
|
1381
1381
|
taskKind: cardKind || "unknown", difficulty: cardDifficulty || "unknown",
|
|
1382
|
-
machine: MACHINE_LABEL
|
|
1382
|
+
machine: MACHINE_LABEL, start: new Date(t0).toISOString(), end: new Date(endedAt).toISOString(),
|
|
1383
1383
|
commit: newCommit ? headAfter : "", outcome: finalOutcome,
|
|
1384
1384
|
infraFailure: isInfraFailure(finalOutcome, failureReason), tokens: Number.isFinite(tokens) ? tokens : null,
|
|
1385
1385
|
};
|
|
@@ -1717,7 +1717,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1717
1717
|
if (pendingWake.length) log(`\x1b[33m${pendingWake.length} message(s) survived from a previous run — redelivering\x1b[0m`);
|
|
1718
1718
|
|
|
1719
1719
|
const worktreeStatus = createWorktreeStatusReporter({
|
|
1720
|
-
cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: MACHINE_LABEL
|
|
1720
|
+
cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: MACHINE_LABEL,
|
|
1721
1721
|
post: async status => {
|
|
1722
1722
|
const result = await api("/worktree-status", status);
|
|
1723
1723
|
if (!result?.ok) throw new Error(result?.error || "hub rejected snapshot");
|
|
@@ -1815,7 +1815,7 @@ async function resolveWakeCard(messages, { session }) {
|
|
|
1815
1815
|
// machineLabel, read at boot). One small signed POST every HEALTH_BEAT_MS; failures stay silent
|
|
1816
1816
|
// by the monitoring doctrine (state not event — a machine that stops beating reads stale on the
|
|
1817
1817
|
// hub, which IS the honest "unreachable" signal, not an error to alert on).
|
|
1818
|
-
if (machineConfig.healthHeartbeat === true &&
|
|
1818
|
+
if (machineConfig.healthHeartbeat === true && machineLabel(machineConfig)) {
|
|
1819
1819
|
// A throw while building the payload must never reach the process: an unhandled rejection
|
|
1820
1820
|
// here took a seat runner down on 0.18.131.
|
|
1821
1821
|
const beat = () => {
|
package/hub/routes/messages.mjs
CHANGED
|
@@ -2,6 +2,9 @@ import { sendMessage } from "../send-message.mjs";
|
|
|
2
2
|
import { routeContractTransfer } from "./contract-transfer.mjs";
|
|
3
3
|
import { setTimeout, setInterval, clearInterval } from "node:timers";
|
|
4
4
|
|
|
5
|
+
// #14765: a parked long poll is a live seat; refresh lastSeen while it waits, under the 90 s seat TTL.
|
|
6
|
+
const POLL_TOUCH_MS = Math.max(1000, Number(process.env.RELAY_POLL_TOUCH_MS) || 30_000);
|
|
7
|
+
|
|
5
8
|
export async function routeMessages({ req, res, q, P, auth, ctx }) {
|
|
6
9
|
if (await routeContractTransfer({ req, res, q, P, auth, ctx })) return true;
|
|
7
10
|
const { state, body, json, touch, markDelivered, contractsFor, CONTRACT_WINDOW_MS } = ctx;
|
|
@@ -81,11 +84,13 @@ function routeDelivery({ req, res, q, P, auth, ctx }) {
|
|
|
81
84
|
const waitMs = Math.min(Number(q.wait || 25), 290) * 1000; // allow long idle-park
|
|
82
85
|
const deadline = now() + waitMs;
|
|
83
86
|
let settled = false;
|
|
87
|
+
let touchedAt = now();
|
|
84
88
|
const tick = () => {
|
|
85
89
|
if (settled || res.headersSent || res.writableEnded || res.destroyed) {
|
|
86
90
|
settled = true;
|
|
87
91
|
return;
|
|
88
92
|
}
|
|
93
|
+
if (now() - touchedAt >= POLL_TOUCH_MS) { touchedAt = now(); touch(q.session, undefined, undefined, undefined, auth); }
|
|
89
94
|
const msgs = state.messages.filter(m => m.id > since && deliverable(m, q.session) && inboxReadable(auth, m, q.session));
|
|
90
95
|
if (msgs.length || now() >= deadline) { settled = true; touch(q.session, undefined, undefined, undefined, auth); const cursor = msgs.length ? msgs[msgs.length - 1].id : since; markDelivered(q.session, cursor); return json(res, 200, inboxResponse(auth, msgs, cursor)); }
|
|
91
96
|
setTimeout(tick, 300);
|
package/hub.mjs
CHANGED
|
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
|
5
5
|
import { homedir } from "node:os";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { assertNoSecrets } from "./lib/scrub.mjs";
|
|
8
|
+
import { createDispatcherTick } from "./lib/dispatcher/store.mjs";
|
|
8
9
|
import { DEFAULT_ORG } from "./lib/store-contract.mjs";
|
|
9
10
|
import { createStoreRuntime } from "./hub/store.mjs";
|
|
10
11
|
import { createAuthRuntime } from "./hub/auth.mjs";
|
|
@@ -141,16 +142,7 @@ const context = {
|
|
|
141
142
|
REAP_GRACE_MS, CONTRACT_WINDOW_MS, PUBLIC_URL,
|
|
142
143
|
};
|
|
143
144
|
if (store.dispatcher && AUTH_MODE !== 'off') {
|
|
144
|
-
|
|
145
|
-
setInterval(async () => {
|
|
146
|
-
if (ticking) return;
|
|
147
|
-
ticking = true;
|
|
148
|
-
try { await store.dispatcher.tick(); }
|
|
149
|
-
catch (error) {
|
|
150
|
-
store.dispatcher.store.closeAdmission();
|
|
151
|
-
console.error(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
|
|
152
|
-
} finally { ticking = false; }
|
|
153
|
-
}, 1000).unref();
|
|
145
|
+
setInterval(createDispatcherTick({ dispatcher: store.dispatcher }), 1000).unref();
|
|
154
146
|
}
|
|
155
147
|
const sessionChat = createSessionRuntime({
|
|
156
148
|
state: store.state, markDirty: store.markDirty,
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "trantor",
|
|
3
|
-
"version": "0.18.
|
|
3
|
+
"version": "0.18.157",
|
|
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",
|
|
@@ -10,6 +10,8 @@ import { homedir } from 'node:os';
|
|
|
10
10
|
|
|
11
11
|
// Stable IDs and internal key fingerprints become subjects; credentials never leave the reader.
|
|
12
12
|
// no zod here: lib/balances.mjs pulls this into the hook snapshot, which ships no node_modules (#14754)
|
|
13
|
+
// SAFETY: loginId comes from credential JSON or public caller input; reject non-strings before hashing.
|
|
14
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
13
15
|
const isLoginId = value => typeof value === 'string' && value.length >= 1 && value.length <= 512
|
|
14
16
|
&& value === value.trim() && !value.includes('@');
|
|
15
17
|
export function providerSubject({ provider, loginId }) {
|
|
@@ -28,12 +30,16 @@ function oneLoginId(values) {
|
|
|
28
30
|
}
|
|
29
31
|
|
|
30
32
|
function tokenIdentity(token) {
|
|
33
|
+
// SAFETY: access_token is untrusted credential JSON; only strings can be JWT-decoded.
|
|
34
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
31
35
|
if (typeof token !== 'string') return null;
|
|
32
36
|
try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString()); }
|
|
33
37
|
catch { return null; }
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
function credentialLogin(key) {
|
|
41
|
+
// SAFETY: key can come from untrusted credential JSON; never coerce non-strings into a login.
|
|
42
|
+
// oxlint-disable-next-line anti-slop/no-runtime-typeof
|
|
37
43
|
return typeof key === 'string' && key.length > 0 ? `key:${createHash('sha256').update(key).digest('hex')}` : null;
|
|
38
44
|
}
|
|
39
45
|
|
|
@@ -43,7 +49,17 @@ export function readProviderIdentity({ provider, home = homedir(), env = process
|
|
|
43
49
|
deepseek: ['DEEPSEEK_API_KEY'], openrouter: ['OPENROUTER_API_KEY'],
|
|
44
50
|
moonshot: ['MOONSHOT_API_KEY'], qwen: ['QWEN_API_KEY'] };
|
|
45
51
|
const key = (keyNames[provider] || []).map(name => env[name]).find(Boolean);
|
|
46
|
-
if (
|
|
52
|
+
if (provider === 'kimi') {
|
|
53
|
+
const auth = ['.kimi-code', '.kimi'].map(directory => loginFile(join(home, directory, 'credentials', 'kimi-code.json')))
|
|
54
|
+
.find(value => value?.access_token);
|
|
55
|
+
if (auth) {
|
|
56
|
+
const token = tokenIdentity(auth.access_token);
|
|
57
|
+
const ids = [auth.user_id, auth.userId, auth.user?.id, token?.user_id].filter(value => value != null && value !== '');
|
|
58
|
+
loginId = ids.length ? oneLoginId(ids) : token?.sub;
|
|
59
|
+
} else if (key) {
|
|
60
|
+
loginId = credentialLogin(key);
|
|
61
|
+
}
|
|
62
|
+
} else if (key) {
|
|
47
63
|
loginId = credentialLogin(key);
|
|
48
64
|
} else if (provider === 'codex') {
|
|
49
65
|
const auth = loginFile(join(env.CODEX_HOME || join(home, '.codex'), 'auth.json'));
|
|
@@ -56,14 +72,6 @@ export function readProviderIdentity({ provider, home = homedir(), env = process
|
|
|
56
72
|
const config = loginFile(env.CLAUDE_CONFIG_DIR ? join(env.CLAUDE_CONFIG_DIR, '.claude.json') : join(home, '.claude.json'));
|
|
57
73
|
loginId = oneLoginId([auth?.claudeAiOauth?.accountUuid, config?.oauthAccount?.accountUuid]);
|
|
58
74
|
}
|
|
59
|
-
} else if (provider === 'kimi' && !env.KIMI_API_KEY) {
|
|
60
|
-
const auth = ['.kimi-code', '.kimi'].map(directory => loginFile(join(home, directory, 'credentials', 'kimi-code.json')))
|
|
61
|
-
.find(value => value?.access_token);
|
|
62
|
-
if (auth) {
|
|
63
|
-
const token = tokenIdentity(auth.access_token);
|
|
64
|
-
const ids = [auth.user_id, auth.userId, auth.user?.id, token?.user_id].filter(value => value != null && value !== '');
|
|
65
|
-
loginId = ids.length ? oneLoginId(ids) : token?.sub;
|
|
66
|
-
}
|
|
67
75
|
} else {
|
|
68
76
|
const auth = loginFile(join(env.XDG_DATA_HOME || join(home, '.local', 'share'), 'opencode', 'auth.json'));
|
|
69
77
|
const names = provider === 'zai' ? ['zai', 'zai-coding-plan'] : [provider];
|
|
@@ -186,6 +186,7 @@ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
|
|
|
186
186
|
const { accounts } = bindAccounts({ org: orgId, bindings });
|
|
187
187
|
const evidence = [];
|
|
188
188
|
for (const row of Array.isArray(rows) ? rows : []) {
|
|
189
|
+
if (row?.kind !== 'agent') continue;
|
|
189
190
|
const id = text(row?.session, 200);
|
|
190
191
|
const machine = text(row?.machine, 60);
|
|
191
192
|
const harness = text(row?.llm, 200);
|
|
@@ -308,7 +309,7 @@ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
|
|
|
308
309
|
const keys = new Set(pending.map(envelope => JSON.stringify([envelope.kind, envelope.id])));
|
|
309
310
|
for (const key of state.accepted.keys()) if (!keys.has(key)) state.accepted.delete(key);
|
|
310
311
|
for (const key of state.failures) if (!keys.has(key)) state.failures.delete(key);
|
|
311
|
-
|
|
312
|
+
const entries = pending.map(envelope => {
|
|
312
313
|
const key = JSON.stringify([envelope.kind, envelope.id]);
|
|
313
314
|
const sourceTime = envelope.observedAtMs;
|
|
314
315
|
const hash = contentHash(envelope);
|
|
@@ -316,21 +317,19 @@ export function createEvidenceBridge({ service, orgId, grant: grantId, sources,
|
|
|
316
317
|
if (previous && sourceTime >= previous.sourceTime && sourceTime <= previous.observedAtMs) {
|
|
317
318
|
envelope.observedAtMs = hash === previous.hash ? previous.observedAtMs : nowMs;
|
|
318
319
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
result = await service.registerEvidence(orgId, envelope, { grant: grantId });
|
|
329
|
-
}
|
|
320
|
+
return { envelope, key, sourceTime, hash,
|
|
321
|
+
retryObservedAtMs: !previous && envelope.observedAtMs < nowMs ? nowMs : undefined };
|
|
322
|
+
});
|
|
323
|
+
const outcomes = await service.registerEvidenceBatch(orgId, entries, { grant: grantId });
|
|
324
|
+
for (const [index, entry] of entries.entries()) {
|
|
325
|
+
const { envelope, key, sourceTime, hash } = entry;
|
|
326
|
+
const { result, error, observedAtMs } = outcomes[index];
|
|
327
|
+
if (!error) {
|
|
328
|
+
envelope.observedAtMs = observedAtMs;
|
|
330
329
|
state.accepted.set(key, { sourceTime, hash, observedAtMs: envelope.observedAtMs });
|
|
331
330
|
state.failures.delete(key);
|
|
332
331
|
if (!result.replayed) written++;
|
|
333
|
-
}
|
|
332
|
+
} else {
|
|
334
333
|
rejected++;
|
|
335
334
|
if (!state.failures.has(key)) {
|
|
336
335
|
state.failures.add(key);
|
|
@@ -82,6 +82,53 @@ export async function requireRole(client, orgId, actor, project, roles, wildcard
|
|
|
82
82
|
export function createDispatcherOperations({ durableStore, orgId: configuredOrg, adapters = new Map(), clock = Date.now, source = '', advisorWorld,
|
|
83
83
|
evidenceSources, dispatcherBridgeGrant = process.env.RELAY_DISPATCHER_BRIDGE_GRANT || null }) {
|
|
84
84
|
const store = durableStore.createDispatcherStore();
|
|
85
|
+
function prepareEvidence(input) {
|
|
86
|
+
const request = RegisterEvidenceSchema.parse(input);
|
|
87
|
+
const record = EvidenceSchemas[request.kind].parse(request.record);
|
|
88
|
+
if (!sources[request.kind].includes(request.source) || request.observedAtMs > clock()
|
|
89
|
+
|| request.expiresAtMs <= clock() || request.expiresAtMs <= request.observedAtMs) reject('evidence_unverified', 422);
|
|
90
|
+
return { request, record };
|
|
91
|
+
}
|
|
92
|
+
async function registerEvidenceWithClient(client, orgId, { request, record }, actor) {
|
|
93
|
+
const nowMs = clock();
|
|
94
|
+
const { approvedBy, grantId } = await evidenceActor(client, orgId, actor, request, nowMs);
|
|
95
|
+
if (request.expiresAtMs <= nowMs) reject('evidence_unverified', 422);
|
|
96
|
+
const previous = (await client.query(`SELECT * FROM dispatcher_evidence WHERE org_id=$1 AND kind=$2 AND id=$3
|
|
97
|
+
ORDER BY revision DESC LIMIT 1`, [orgId, request.kind, request.id])).rows[0];
|
|
98
|
+
const previousRevision = Number(previous?.revision || 0);
|
|
99
|
+
if (request.expectedRevision !== undefined && previousRevision !== request.expectedRevision) reject('evidence_stale');
|
|
100
|
+
if (record.id !== undefined && record.id !== request.id) reject('schema_invalid', 422);
|
|
101
|
+
if (grantId && previous) {
|
|
102
|
+
if (request.observedAtMs < Number(previous.observed_at_ms)) reject('evidence_stale');
|
|
103
|
+
if (request.observedAtMs === Number(previous.observed_at_ms)) {
|
|
104
|
+
if (previous.grant_id !== grantId || previous.registered_by !== approvedBy || previous.source !== request.source
|
|
105
|
+
|| previous.source_ref !== request.sourceRef
|
|
106
|
+
|| canonicalHash(observationContent(request.kind, previous.row)) !== canonicalHash(observationContent(request.kind, record))) reject('evidence_conflict');
|
|
107
|
+
return { id: request.id, revision: previousRevision, replayed: true };
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (request.kind === 'launch' && record.adapter.version !== CREW_ADAPTER_VERSION) reject('adapter_unqualified', 422);
|
|
111
|
+
if (request.kind === 'promotion') {
|
|
112
|
+
if (record.approvalId !== request.id) reject('evidence_unverified', 422);
|
|
113
|
+
const validated = await validateRolloutApproval(client, orgId, record);
|
|
114
|
+
await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
|
|
115
|
+
approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
|
|
116
|
+
}
|
|
117
|
+
const revision = previousRevision + 1;
|
|
118
|
+
await client.query(`INSERT INTO dispatcher_evidence
|
|
119
|
+
(org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
|
|
120
|
+
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
|
|
121
|
+
[orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
|
|
122
|
+
request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
|
|
123
|
+
if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
|
|
124
|
+
ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
|
|
125
|
+
[orgId, record.accountId, record.windowId, revision, record]);
|
|
126
|
+
await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
|
|
127
|
+
ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
|
|
128
|
+
await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
|
|
129
|
+
kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
|
|
130
|
+
return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
|
|
131
|
+
}
|
|
85
132
|
const configuredGrant = text.nullable().parse(dispatcherBridgeGrant);
|
|
86
133
|
const bridgeBinding = async (client, orgId, nowMs) => {
|
|
87
134
|
const active = (await client.query(`SELECT grant_id FROM dispatcher_bridge_grants
|
|
@@ -305,49 +352,36 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
|
|
|
305
352
|
});
|
|
306
353
|
},
|
|
307
354
|
async registerEvidence(orgId, input, actor) {
|
|
308
|
-
const
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
355
|
+
const prepared = prepareEvidence(input);
|
|
356
|
+
return store.locked(orgId, client => registerEvidenceWithClient(client, orgId, prepared, actor));
|
|
357
|
+
},
|
|
358
|
+
async registerEvidenceBatch(orgId, entries, actor) {
|
|
359
|
+
if (!entries.length) return [];
|
|
312
360
|
return store.locked(orgId, async client => {
|
|
313
|
-
const
|
|
314
|
-
const {
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
361
|
+
const outcomes = [];
|
|
362
|
+
for (const { envelope, retryObservedAtMs } of entries) {
|
|
363
|
+
let input = envelope;
|
|
364
|
+
await client.query('SAVEPOINT bridge_envelope');
|
|
365
|
+
try {
|
|
366
|
+
let result;
|
|
367
|
+
try {
|
|
368
|
+
result = await registerEvidenceWithClient(client, orgId, prepareEvidence(input), actor);
|
|
369
|
+
} catch (error) {
|
|
370
|
+
if (retryObservedAtMs === undefined || !['evidence_conflict', 'evidence_stale'].includes(error.code)) throw error;
|
|
371
|
+
await client.query('ROLLBACK TO SAVEPOINT bridge_envelope');
|
|
372
|
+
input = { ...envelope, observedAtMs: retryObservedAtMs };
|
|
373
|
+
result = await registerEvidenceWithClient(client, orgId, prepareEvidence(input), actor);
|
|
374
|
+
}
|
|
375
|
+
outcomes.push({ result, observedAtMs: input.observedAtMs });
|
|
376
|
+
} catch (error) {
|
|
377
|
+
// Transient database failures retry/abort the whole transaction, never individual evidence.
|
|
378
|
+
if (!error.status && !(error instanceof z.ZodError) || error.status >= 500) throw error;
|
|
379
|
+
await client.query('ROLLBACK TO SAVEPOINT bridge_envelope');
|
|
380
|
+
outcomes.push({ error });
|
|
328
381
|
}
|
|
382
|
+
await client.query('RELEASE SAVEPOINT bridge_envelope');
|
|
329
383
|
}
|
|
330
|
-
|
|
331
|
-
if (request.kind === 'promotion') {
|
|
332
|
-
if (record.approvalId !== request.id) reject('evidence_unverified', 422);
|
|
333
|
-
const validated = await validateRolloutApproval(client, orgId, record);
|
|
334
|
-
await store.audit(client, orgId, { action: 'rollout-approved', atMs: clock(), actor: actor.pubkey,
|
|
335
|
-
approvalId: request.id, approvalHash: canonicalHash(record), ...validated });
|
|
336
|
-
}
|
|
337
|
-
const revision = previousRevision + 1;
|
|
338
|
-
await client.query(`INSERT INTO dispatcher_evidence
|
|
339
|
-
(org_id,kind,id,revision,source,source_ref,observed_at_ms,expires_at_ms,registered_by,registered_at_ms,hash,row,grant_id)
|
|
340
|
-
VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`,
|
|
341
|
-
[orgId, request.kind, request.id, revision, request.source, request.sourceRef, request.observedAtMs,
|
|
342
|
-
request.expiresAtMs, approvedBy, nowMs, canonicalHash(record), record, grantId]);
|
|
343
|
-
if (request.kind === 'ledger') await client.query(`INSERT INTO dispatcher_window_balances VALUES($1,$2,$3,$4,$5)
|
|
344
|
-
ON CONFLICT(org_id,account_id,window_id) DO UPDATE SET revision=EXCLUDED.revision,row=EXCLUDED.row`,
|
|
345
|
-
[orgId, record.accountId, record.windowId, revision, record]);
|
|
346
|
-
await client.query(`INSERT INTO dispatcher_authority_state(org_id,revision) VALUES($1,1)
|
|
347
|
-
ON CONFLICT(org_id) DO UPDATE SET revision=dispatcher_authority_state.revision+1`, [orgId]);
|
|
348
|
-
await store.audit(client, orgId, { action: 'evidence-registered', actor: approvedBy, approvedBy, grantId, atMs: nowMs,
|
|
349
|
-
kind: request.kind, id: request.id, revision, source: request.source, sourceRef: request.sourceRef, hash: canonicalHash(record) });
|
|
350
|
-
return grantId ? { id: request.id, revision, replayed: false } : { id: request.id, revision };
|
|
384
|
+
return outcomes;
|
|
351
385
|
});
|
|
352
386
|
},
|
|
353
387
|
async registerBridgeGrant(orgId, input, actor) {
|
package/lib/dispatcher/store.mjs
CHANGED
|
@@ -329,3 +329,30 @@ export function createDispatcherStore({ pool, transaction }) {
|
|
|
329
329
|
},
|
|
330
330
|
};
|
|
331
331
|
}
|
|
332
|
+
|
|
333
|
+
// Busy ticks leave readiness alone: every admission still obtains its own bounded lock.
|
|
334
|
+
export function createDispatcherTick({ dispatcher, clock = Date.now, log = console.error }) {
|
|
335
|
+
let ticking = false;
|
|
336
|
+
let busySince = null;
|
|
337
|
+
return async () => {
|
|
338
|
+
if (ticking) return;
|
|
339
|
+
ticking = true;
|
|
340
|
+
try {
|
|
341
|
+
await dispatcher.tick();
|
|
342
|
+
if (busySince !== null) {
|
|
343
|
+
log(`[trantor] dispatcher contention recovered after ${clock() - busySince}ms`);
|
|
344
|
+
busySince = null;
|
|
345
|
+
}
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (error.code === 'admission_busy') {
|
|
348
|
+
if (busySince === null) {
|
|
349
|
+
busySince = clock();
|
|
350
|
+
log('[trantor] dispatcher contention started: admission_busy');
|
|
351
|
+
}
|
|
352
|
+
} else {
|
|
353
|
+
dispatcher.store.closeAdmission();
|
|
354
|
+
log(`[trantor] dispatcher unavailable: ${error.code || 'store_failure'}`);
|
|
355
|
+
}
|
|
356
|
+
} finally { ticking = false; }
|
|
357
|
+
};
|
|
358
|
+
}
|