trantor 0.18.159 → 0.18.160

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.
@@ -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.159"
9
+ "version": "0.18.160"
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.159",
16
+ "version": "0.18.160",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.159",
3
+ "version": "0.18.160",
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": {
@@ -2,6 +2,7 @@
2
2
  // trantor crew runner — keeps a crew agent alive without burning tokens: it long-polls the bus
3
3
  // (zero tokens) and resumes the CLI with each message. Usage: node crew-runner.mjs <agent> [dir]
4
4
  import { resolveKeys } from "../lib/provider-keys.mjs";
5
+ import { CREW_ADAPTER_VERSION } from "../lib/dispatcher/harness/contract.mjs";
5
6
  import { runnerAccountIdentity } from "../lib/dispatcher/accounts.mjs";
6
7
  import { execSync, spawnSync, spawn } from "node:child_process";
7
8
  import { randomUUID } from "node:crypto";
@@ -502,7 +503,7 @@ async function reportFailure(exit, trigger, undelivered = 0, reasonOverride = ""
502
503
  const reason = reasonOverride || classify(exit);
503
504
  const down = consecFails >= 2;
504
505
  const status = down ? `down: ${reason} · ${consecFails} fails` : `errored: ${reason}`;
505
- await api("/register", { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
506
+ await api("/register", { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
506
507
  const hint = reason === "exhausted" ? " — needs `trantor swap`"
507
508
  : reason === "stalled" ? " — CLI silent for the whole watchdog window: check the provider, or `trantor swap`"
508
509
  : reason === "auth" ? " — check credentials"
@@ -701,6 +702,7 @@ async function registerStatus(status, extra = {}) {
701
702
  const payload = { session: SESSION, project: PROJ, status, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, ...extra };
702
703
  payload.machine = MACHINE_LABEL;
703
704
  payload.accountIdentity = cachedAccountIdentity;
705
+ payload.adapterVersion = CREW_ADAPTER_VERSION;
704
706
  const body = JSON.stringify(payload);
705
707
  try {
706
708
  const opts = { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body };
@@ -762,7 +764,7 @@ async function reportHealthy() {
762
764
  // Recovery is a change too, so the next failure is news again — a park included.
763
765
  announced = "";
764
766
  parkAnnounced = false;
765
- await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
767
+ await api("/register", { session: SESSION, project: PROJ, status: `active in ${PROJ}`, persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
766
768
  // #13949: a landing that ended a park already said "recovered" once, with the reason and the
767
769
  // duration — the ladder's echo would be the second recovery message for one event.
768
770
  if (!saidParkRecovered) await api("/send", { from: SESSION, to: "all", text: `✅ ${SESSION} recovered`, project: PROJ, kind: "status" }).catch(() => {});
@@ -1066,6 +1068,7 @@ async function runTurn(prompt, isFirst, trigger = "kickoff", opts = {}) {
1066
1068
  agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", phase: "working", phaseSince: t0, card: sessionCard || 0 };
1067
1069
  presencePayload.machine = MACHINE_LABEL;
1068
1070
  presencePayload.accountIdentity = cachedAccountIdentity;
1071
+ presencePayload.adapterVersion = CREW_ADAPTER_VERSION;
1069
1072
  writeFileSync(STAMPF, JSON.stringify({ turn: TURN, startedAt: Date.now(), runner: RUNNER_ID, box: boxPlan, activity,
1070
1073
  presence: { intervalMs: PRESENCE_MS, payload: presencePayload },
1071
1074
  worktree: { cwd: TURN_DIR, seat: PERSONA, project: PROJ, machine: presencePayload.machine } }));
@@ -1664,7 +1667,7 @@ async function resolveWakeCard(messages, { session }) {
1664
1667
  // session is — the overseer's declared-crew exemption reads it, and on the remote hub there is
1665
1668
  // no crew-windows.txt to fall back to. /register preserves absent fields, so a seat running an
1666
1669
  // older runner never loses a kind an updated one stamped.
1667
- await api("/register", { session: SESSION, project: PROJ, status: "crew member booting", persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent" }).catch(() => {});
1670
+ await api("/register", { session: SESSION, project: PROJ, status: "crew member booting", persona: PERSONA, agent: AGENT, llm: AGENT, model: MODEL, kind: "agent", adapterVersion: CREW_ADAPTER_VERSION }).catch(() => {});
1668
1671
  // Announce runner-side, signed as THIS seat: the runner process is per-seat by construction, so
1669
1672
  // its signature cannot be borrowed the way a shared opencode MCP daemon once borrowed identities.
1670
1673
  try {
@@ -70,6 +70,10 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
70
70
  if (pr) { if (b.model) pr.model = String(b.model).slice(0, 80); if (b.llm) pr.llm = String(b.llm).slice(0, 40); if (b.kind) pr.kind = String(b.kind).slice(0, 40); }
71
71
  // Hooks and MCP beats share the runner's session name; only the runner may rotate or clear its account binding.
72
72
  const fromRunner = typeof b.persona === "string" && b.persona.length > 0 && typeof b.agent === "string" && b.agent.length > 0;
73
+ if (pr && fromRunner && typeof b.adapterVersion === 'string' && /^[a-zA-Z0-9._-]{1,80}$/.test(b.adapterVersion)) {
74
+ pr.adapterVersion = b.adapterVersion;
75
+ markDirty();
76
+ }
73
77
  if (pr && fromRunner && Object.hasOwn(b, 'accountIdentity')) {
74
78
  const identity = b.accountIdentity;
75
79
  const provider = typeof identity?.provider === "string" && /^[a-z0-9-]{1,60}$/.test(identity.provider) ? identity.provider : 'unknown';
@@ -361,7 +365,7 @@ export async function routeAdmin({ req, res, q, P, auth, ctx }) {
361
365
  return json(res, 200, { hubVersion: HUB_VERSION, authMode: AUTH_MODE, peers: peerRows.map(([s, v]) => ({ session: s, lastSeen: v.lastSeen, online: v.lastSeen > cutoff, status: v.status || "", health: healthOf(v.status), project: v.project || "", phase: v.phase || "", phaseSince: v.phaseSince || 0,
362
366
  pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "",
363
367
  kind: peerKindOf(v), // #8723 bounce-3: same resolver declaredCrewFor reads — never a roster-only answer
364
- llm: v.llm || "", model: v.model || "", machine: v.machine || undefined, hookVersion: v.hookVersion || "", staleHooks: !!(v.lastSeen > cutoff && v.hookVersion && HUB_VERSION && cmpSemver(v.hookVersion, HUB_VERSION) < 0) })) });
368
+ llm: v.llm || "", model: v.model || "", machine: v.machine || undefined, adapterVersion: v.adapterVersion || null, hookVersion: v.hookVersion || "", staleHooks: !!(v.lastSeen > cutoff && v.hookVersion && HUB_VERSION && cmpSemver(v.hookVersion, HUB_VERSION) < 0) })) });
365
369
  }
366
370
  // --- Provider balances (prepaid credit) ---
367
371
  // The hub runs under launchd with no provider keys, so it can't fetch balances itself. Env-having
package/hub/store.mjs CHANGED
@@ -154,7 +154,7 @@ function normalizeState(loaded = {}) {
154
154
  s.peers[session] = typeof v === "number"
155
155
  ? { lastSeen: v, status: "", project: "" }
156
156
  // #6170/#14760: this explicit projection must retain every durable peer field.
157
- : { lastSeen: v.lastSeen || 0, status: v.status || "", project: v.project || "", pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "", hookVersion: v.hookVersion || "", kind: v.kind || "", machine: v.machine || "", llm: v.llm || "", model: v.model || "", accountIdentity: v.accountIdentity || null, gitRoot: v.gitRoot || loaded.overseerState?.roots?.[session] || "", deliveredUpTo: v.deliveredUpTo || v.delivered_up_to || 0, _on: v._on === true || v.online === true };
157
+ : { lastSeen: v.lastSeen || 0, status: v.status || "", project: v.project || "", pubkey: v.pubkey || "", identity: v.identity || null, authWarning: v.authWarning || "", hookVersion: v.hookVersion || "", kind: v.kind || "", machine: v.machine || "", llm: v.llm || "", model: v.model || "", accountIdentity: v.accountIdentity || null, adapterVersion: v.adapterVersion || null, gitRoot: v.gitRoot || loaded.overseerState?.roots?.[session] || "", deliveredUpTo: v.deliveredUpTo || v.delivered_up_to || 0, _on: v._on === true || v.online === true };
158
158
  }
159
159
  return s;
160
160
  }
@@ -450,10 +450,16 @@ setInterval(persist, persistTickMs).unref?.();
450
450
  machines: () => machineHealthRows(Date.now()),
451
451
  seats: () => {
452
452
  const nowMs = Date.now();
453
+ const lastRows = turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 });
453
454
  return seatsView({ peers: state.peers, messages: state.messages, nowMs,
454
- onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000),
455
- lastRows: turnTelemetry.readRows({ since: nowMs - 7 * 86400e3 }) })
456
- .map(seat => ({ ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity }));
455
+ onlineMs: Number(process.env.RELAY_ONLINE_MS || 5 * 60 * 1000), lastRows })
456
+ .map(seat => {
457
+ const turn = lastRows.find(row => `${row.persona}:${row.project}` === seat.session && row.ts === seat.lastTurn?.ts);
458
+ return { ...seat, accountIdentity: state.peers[seat.session]?.accountIdentity,
459
+ adapterVersion: state.peers[seat.session]?.adapterVersion,
460
+ lastTurn: seat.lastTurn ? { ...seat.lastTurn, attemptId: turn?.executionAttemptId ?? turn?.attempt?.id ?? null,
461
+ effort: turn?.attempt?.effort ?? 'default' } : null };
462
+ });
457
463
  },
458
464
  discovery: () => {
459
465
  if (!discovery || Date.now() - discoveryAt >= CACHE_TTL_MS) {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.159",
3
+ "version": "0.18.160",
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",
@@ -1,3 +1,4 @@
1
+ import { z } from 'zod';
1
2
  import { bindAccounts, resolveSeatAccount } from './accounts.mjs';
2
3
  import { canonicalHash } from './snapshot.mjs';
3
4
  import { heldLiability } from './spend.mjs';
@@ -136,6 +137,17 @@ function activeSeats(seats, id) {
136
137
  return seats.filter(seat => seat?.online && text(seat.machine, 60).toLowerCase() === id.toLowerCase()).length;
137
138
  }
138
139
 
140
+ const AdapterVersionSchema = z.string().regex(/^[a-zA-Z0-9._-]{1,80}$/);
141
+ function reportedAdapters(seats, machine, nowMs, policy) {
142
+ return [...new Set(seats.filter(seat => seat.kind === 'agent' && seat.online === true
143
+ && text(seat.machine, 60).toLowerCase() === machine.toLowerCase()
144
+ && fresh(timestamp(seat.lastSeen), nowMs, policy.machineTtlMs))
145
+ .flatMap(seat => {
146
+ const version = AdapterVersionSchema.safeParse(seat.adapterVersion);
147
+ return version.success ? [version.data] : [];
148
+ }))].sort();
149
+ }
150
+
139
151
  function machineEvidence({ rows, seats, nowMs, policy }) {
140
152
  const evidence = [];
141
153
  const emitted = new Set();
@@ -159,7 +171,7 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
159
171
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
160
172
  record: { id, health: observation({ value: health, observedAtMs, receivedAtMs: nowMs,
161
173
  source: 'machine-beats', status: 'ok', sourceRevision: observedAtMs }),
162
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
174
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
163
175
  }
164
176
  for (const seat of seats) {
165
177
  const id = text(seat?.machine, 60);
@@ -172,7 +184,7 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
172
184
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
173
185
  record: { id, health: observation({ value: null, observedAtMs, receivedAtMs: nowMs,
174
186
  source: 'presence', status: 'unknown', reason: 'no fresh machine health beat', sourceRevision: observedAtMs }),
175
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: [] } });
187
+ tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
176
188
  }
177
189
  return evidence;
178
190
  }
@@ -265,11 +277,29 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
265
277
  export function buildEvidence({ balances = [], machines = [], seats = [], discovery = [], orgId, nowMs,
266
278
  policy = DEFAULT_POLICY, catalog = loadCatalog() }) {
267
279
  const presentSeats = presenceMachines({ rows: machines, seats });
280
+ const accounts = balanceEvidence({ snapshots: balances, orgId, nowMs, policy });
281
+ const boundSeats = seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy });
282
+ const defaults = [];
283
+ for (const { record: seat } of boundSeats) {
284
+ const turn = presentSeats.find(row => row.session === seat.id)?.lastTurn;
285
+ const account = accounts.find(row => row.kind === 'account' && row.id === seat.accountId)?.record;
286
+ if (seat.model !== null || !turn?.attemptId || account?.status !== 'verified'
287
+ || !fresh(timestamp(turn.ts), nowMs, policy.invocationTtlMs)) continue;
288
+ const envelope = modelEnvelope({ provider: account.provider, model: null, observedAtMs: turn.ts,
289
+ expiresAtMs: turn.ts + policy.invocationTtlMs, nowMs, catalog });
290
+ envelope.id = `default:${seat.id}`;
291
+ envelope.sourceRef = `presence:${seat.id}:${turn.ts}`;
292
+ envelope.record.accountId = account.id;
293
+ envelope.record.liveUse = { seatId: seat.id, harness: seat.harness, attemptId: turn.attemptId };
294
+ envelope.record.efforts = [!turn.effort || turn.effort === 'unknown' ? 'default' : turn.effort];
295
+ defaults.push(envelope);
296
+ }
268
297
  return [
269
- ...balanceEvidence({ snapshots: balances, orgId, nowMs, policy }),
298
+ ...accounts,
270
299
  ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
271
- ...seatEvidence({ rows: presentSeats, balances, orgId, nowMs, policy }),
300
+ ...boundSeats,
272
301
  ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
302
+ ...defaults,
273
303
  ];
274
304
  }
275
305
 
@@ -72,7 +72,11 @@ export function deriveCandidates(snapshot, policy) {
72
72
  for (const modelId of identities) {
73
73
  if (modelId === null && (seat.model !== null || model.liveUse?.seatId !== seat.id
74
74
  || model.liveUse.harness !== seat.harness)) continue;
75
- for (const effort of model.efforts) {
75
+ const efforts = new Set(model.efforts);
76
+ if (policy.qualityPriors.some(prior => prior.provider === account.provider && prior.model === modelId
77
+ && prior.effort === 'default' && (prior.harness === undefined || prior.harness === seat.harness)
78
+ && (prior.seatId === undefined || prior.seatId === seat.id))) efforts.add('default');
79
+ for (const effort of efforts) {
76
80
  const identity = { provider: account.provider, model: modelId, effort, accountId: account.id,
77
81
  harness: seat.harness, machine: seat.machine, seatId: seat.id };
78
82
  const candidate = { id: candidateId(identity), ...identity };
@@ -89,6 +93,7 @@ function priorFor(candidate, card, policy, snapshot) {
89
93
  && seat.harness === candidate.harness && seat.model === null)) return null;
90
94
  const matching = policy.qualityPriors.filter(prior => prior.provider === candidate.provider
91
95
  && prior.model === candidate.model && prior.effort === candidate.effort
96
+ && (prior.seatId === undefined || prior.seatId === candidate.seatId)
92
97
  && (prior.harness === undefined || prior.harness === candidate.harness)
93
98
  && prior.difficulty === card.difficulty && ((kinds.has(card.kind) && prior.kind === card.kind) || prior.kind === '*'));
94
99
  return matching.sort((a, b) => Number(b.harness === candidate.harness) - Number(a.harness === candidate.harness)
@@ -2,18 +2,21 @@ import { z } from 'zod';
2
2
  import { createPolicy, verifyPolicy, LEGACY_RATE_INPUTS } from './policy.mjs';
3
3
  import { verifySnapshot, canonicalHash, canonicalJson } from './snapshot.mjs';
4
4
  import { classifyAttemptVerification } from './acceptance.mjs';
5
+ import { isInfraFailure } from '../fitness.mjs';
5
6
 
6
7
  const text = z.string().min(1).max(8192);
7
8
  const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
8
- const SampleSchema = z.object({ id: text, project: text, ts: integer,
9
- duration_ms: integer, tokens: integer.nullable(),
9
+ const difficulty = z.enum(['easy', 'medium', 'hard']);
10
+ const SampleSchema = z.object({ id: text, project: text, ts: integer, duration_ms: integer,
11
+ card: integer.optional(), persona: text.optional(), agent: text.optional(), model: text.nullable().optional(),
10
12
  attempt: z.object({ id: text, provider: text, harness: text, model: text.nullable(),
11
- difficulty: z.enum(['easy', 'medium', 'hard']), infraFailure: z.boolean() }).passthrough(),
12
- usage: z.object({ priceVersion: text.nullable().optional() }).passthrough().optional(),
13
- executionAttemptId: text.nullable().optional(),
13
+ seat: text.optional(), effort: text.nullable().optional(), difficulty: text, infraFailure: z.boolean() }).passthrough().nullish(),
14
+ usage: z.unknown().optional(), executionAttemptId: text.nullable().optional(),
14
15
  }).passthrough();
16
+ const UsageSchema = z.object({ input: integer, output: integer, cacheRead: integer.optional(),
17
+ cacheWrite: integer.optional(), priceVersion: text.nullable().optional() }).passthrough();
15
18
  export const PolicyDraftRequestSchema = z.strictObject({ project: text, version: text.optional() });
16
- const key = row => JSON.stringify([row.provider, row.harness, row.model, row.difficulty]);
19
+ const key = row => JSON.stringify([row.provider, row.harness, row.model, row.difficulty, row.effort, row.seatId ?? null]);
17
20
  const median = values => {
18
21
  const sorted = [...values].sort((a, b) => a - b);
19
22
  const middle = Math.floor(sorted.length / 2);
@@ -29,32 +32,63 @@ function supportsModel(seat, model, snapshot, policy) {
29
32
  && snapshot.asOfMs - entry.invocation.observedAtMs <= policy.invocationTtlMs);
30
33
  }
31
34
 
32
- function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances) {
35
+ const increment = (counts, reason) => { counts[reason] = (counts[reason] || 0) + 1; };
36
+
37
+ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances, cards) {
33
38
  const groups = new Map();
34
39
  const seen = new Set();
35
- const excluded = { invalid: 0, duplicate: 0, future: 0, unknownModel: 0, infrastructure: 0 };
40
+ const excluded = {};
41
+ const tokenExcluded = {};
42
+ const recovered = { withoutAttempt: 0, cardDifficulty: 0 };
36
43
  for (const input of turns) {
37
44
  const parsed = SampleSchema.safeParse(input);
38
- if (!parsed.success) { excluded.invalid++; continue; }
45
+ if (!parsed.success) {
46
+ const issue = parsed.error.issues[0];
47
+ increment(excluded, `invalid_${issue.path.join('_') || 'row'}_${issue.code}`);
48
+ continue;
49
+ }
39
50
  const row = parsed.data;
40
51
  if (row.project !== project) continue;
41
- if (seen.has(row.id)) { excluded.duplicate++; continue; }
52
+ if (seen.has(row.id)) { increment(excluded, 'duplicate'); continue; }
42
53
  seen.add(row.id);
43
- if (row.ts > nowMs) { excluded.future++; continue; }
44
- if (row.attempt.model === 'unknown') { excluded.unknownModel++; continue; }
45
- if (row.attempt.infraFailure) { excluded.infrastructure++; continue; }
46
- const seat = bound.find(entry => entry.id === row.attempt.seat
47
- && (entry.harness === row.attempt.harness || entry.harness === 'crew' && entry.agent === row.attempt.harness)
48
- && supportsModel(entry, row.attempt.model, snapshot, policy));
49
- const account = seat && snapshot.accounts.find(entry => entry.id === seat.accountId);
50
- const identity = { provider: account?.provider ?? row.attempt.provider, harness: seat?.harness ?? row.attempt.harness,
51
- model: row.attempt.model, difficulty: row.attempt.difficulty };
54
+ if (row.ts > nowMs) { increment(excluded, 'future'); continue; }
55
+ if (row.attempt?.infraFailure || isInfraFailure(row.outcome)) { increment(excluded, 'infrastructure'); continue; }
56
+ const card = cards.find(card => card.project === project && card.card === row.card);
57
+ const recordedDifficulty = difficulty.safeParse(row.attempt?.difficulty);
58
+ const cardDifficulty = difficulty.safeParse(card?.difficulty);
59
+ if (!recordedDifficulty.success && !cardDifficulty.success) { increment(excluded, 'difficulty_unknown'); continue; }
60
+ const seatId = row.attempt?.seat ?? (row.persona ? `${row.persona}:${project}` : null);
61
+ const recordedModel = row.attempt?.model ?? row.model ?? null;
62
+ const harness = row.attempt?.harness ?? row.agent;
63
+ const seat = bound.find(entry => entry.id === seatId
64
+ && (entry.harness === harness || entry.harness === 'crew' && entry.agent === harness)
65
+ && (entry.model === null || supportsModel(entry, recordedModel, snapshot, policy)));
66
+ if (!seat) { increment(excluded, 'no_bound_seat'); continue; }
67
+ if (recordedModel === 'unknown' && seat.model !== null) { increment(excluded, 'unknownModel'); continue; }
68
+ const account = snapshot.accounts.find(entry => entry.id === seat.accountId);
69
+ const effort = row.attempt?.effort;
70
+ const identity = { provider: account.provider, harness: seat.harness, model: seat.model === null ? null : recordedModel,
71
+ difficulty: recordedDifficulty.success ? recordedDifficulty.data : cardDifficulty.data,
72
+ effort: !effort || effort === 'unknown' ? 'default' : effort };
73
+ if (seat.model === null) identity.seatId = seat.id;
74
+ if (!row.attempt) recovered.withoutAttempt++;
75
+ if (!recordedDifficulty.success) recovered.cardDifficulty++;
52
76
  const groupKey = key(identity);
53
- if (!groups.has(groupKey)) groups.set(groupKey, { ...identity, rows: [], tokens: [], durations: [], judged: 0, passes: 0, acceptances: new Set() });
77
+ if (!groups.has(groupKey)) groups.set(groupKey, { ...identity, rows: [], tokens: [], cacheReads: [],
78
+ tokenExcluded: {}, durations: [], judged: 0, passes: 0, acceptances: new Set() });
54
79
  const group = groups.get(groupKey);
55
80
  group.rows.push(row);
56
- if (row.tokens !== null) group.tokens.push(row.tokens);
81
+ const usage = UsageSchema.safeParse(row.usage);
82
+ const tokens = usage.success ? usage.data.input + usage.data.output : null;
83
+ const tokenReason = row.usage == null ? 'no_structured_usage' : !usage.success ? 'invalid_structured_usage'
84
+ : !Number.isSafeInteger(tokens) ? 'token_sum_overflow' : null;
85
+ if (tokenReason) { increment(tokenExcluded, tokenReason); increment(group.tokenExcluded, tokenReason); }
86
+ else {
87
+ group.tokens.push(tokens);
88
+ if (usage.data.cacheRead !== undefined) group.cacheReads.push(usage.data.cacheRead);
89
+ }
57
90
  if (row.duration_ms > 0) group.durations.push(row.duration_ms);
91
+ if (!row.attempt) continue;
58
92
  const acceptance = acceptances.find(record => record.attemptId === (row.executionAttemptId ?? row.attempt.id)
59
93
  && record.atMs <= nowMs);
60
94
  const verification = classifyAttemptVerification({ ...row.attempt, acceptance, executionAttemptId: row.executionAttemptId });
@@ -64,12 +98,13 @@ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptan
64
98
  if (verification.status === 'accepted') group.passes++;
65
99
  }
66
100
  }
67
- return { groups, excluded };
101
+ return { groups, excluded, tokenExcluded, recovered };
68
102
  }
69
103
 
70
104
  function ratesFor(group, policy) {
71
105
  const prior = policy.qualityPriors.filter(row => row.provider === group.provider && row.model === group.model
72
- && (row.harness === undefined || row.harness === group.harness) && row.difficulty === group.difficulty)
106
+ && (row.harness === undefined || row.harness === group.harness) && row.difficulty === group.difficulty
107
+ && (row.seatId === undefined || row.seatId === group.seatId))
73
108
  .sort((a, b) => b.rateAsOfMs - a.rateAsOfMs || canonicalJson(a).localeCompare(canonicalJson(b)))[0];
74
109
  if (prior) return { rates: prior.rates, priceVersion: prior.priceVersion,
75
110
  rateSource: `policy:${policy.version}:${prior.rateSource}`, rateAsOfMs: prior.rateAsOfMs };
@@ -79,7 +114,7 @@ function ratesFor(group, policy) {
79
114
  rateSource: 'unobserved: no active policy rate or legacy model rate', rateAsOfMs: 0 };
80
115
  }
81
116
 
82
- export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], project, version, createdBy, nowMs }) {
117
+ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], cards, project, version, createdBy, nowMs }) {
83
118
  const policy = verifyPolicy(inputPolicy);
84
119
  const snapshot = verifySnapshot(inputSnapshot);
85
120
  if (snapshot.policyVersion !== policy.version) throw new Error('policy_stale');
@@ -92,39 +127,40 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
92
127
  if (seat.agent !== undefined) entry.agent = seat.agent;
93
128
  return entry;
94
129
  });
95
- const { groups, excluded } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances);
130
+ const { groups, excluded, tokenExcluded, recovered } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances, cards ?? snapshot.readyQueue);
96
131
  const qualityPriors = [];
97
132
  const samples = [];
98
133
  for (const group of [...groups.values()].sort((a, b) => key(a).localeCompare(key(b)))) {
99
134
  const sampleCount = group.rows.length;
100
- const priceVersions = [...new Set(group.rows.map(row => row.usage?.priceVersion ?? null))]
135
+ const priceVersions = [...new Set(group.rows.map(row => { const usage = UsageSchema.safeParse(row.usage); return usage.success ? usage.data.priceVersion ?? null : null; }))]
101
136
  .sort((a, b) => String(a).localeCompare(String(b)));
102
137
  const sample = { provider: group.provider, harness: group.harness, model: group.model, difficulty: group.difficulty,
138
+ effort: group.effort,
103
139
  sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
140
+ tokenExcluded: group.tokenExcluded, cacheReadSampleCount: group.cacheReads.length,
141
+ medianCacheReadTokens: group.cacheReads.length ? median(group.cacheReads) : null,
104
142
  judged: group.judged, passes: group.passes, priceVersions,
105
- recordedProviders: [...new Set(group.rows.map(row => row.attempt.provider))].sort(),
106
- recordedHarnesses: [...new Set(group.rows.map(row => row.attempt.harness))].sort(),
143
+ recordedProviders: [...new Set(group.rows.map(row => row.attempt?.provider ?? null))].sort(),
144
+ recordedHarnesses: [...new Set(group.rows.map(row => row.attempt?.harness ?? row.agent ?? null))].sort(),
145
+ recordedModels: [...new Set(group.rows.map(row => row.attempt?.model ?? row.model ?? null))].sort(),
107
146
  medianTokens: group.tokens.length ? median(group.tokens) : null,
108
147
  medianDurationMs: group.durations.length ? median(group.durations) : null };
109
- const matchingSeats = bound.filter(seat => seat.harness === group.harness && supportsModel(seat, group.model, snapshot, policy)
110
- && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === group.provider);
111
- const efforts = [...new Set(snapshot.models.filter(model => model.provider === group.provider && model.model === group.model
112
- && matchingSeats.some(seat => model.accountId === null || model.accountId === seat.accountId))
113
- .flatMap(model => model.efforts))].sort();
114
- const reason = !group.tokens.length || !group.durations.length ? 'no_measurements'
115
- : !matchingSeats.length ? 'no_bound_seat' : !efforts.length ? 'no_effort_evidence' : null;
148
+ if (group.seatId) sample.seatId = group.seatId;
149
+ const reason = !group.tokens.length || !group.durations.length ? 'no_measurements' : null;
116
150
  samples.push({ ...sample, reason });
117
151
  if (reason) continue;
118
152
  const qualityPpm = Number((BigInt(group.passes) + 1n) * 1_000_000n / (BigInt(group.judged) + 2n));
119
153
  const rates = ratesFor(group, policy);
120
- for (const effort of efforts) qualityPriors.push({ provider: group.provider, harness: group.harness,
121
- model: group.model, effort, kind: '*', difficulty: group.difficulty,
154
+ const prior = { provider: group.provider, harness: group.harness,
155
+ model: group.model, effort: group.effort, kind: '*', difficulty: group.difficulty,
122
156
  durationMs: sample.medianDurationMs, tokenEstimate: sample.medianTokens,
123
157
  capabilityScorePpm: qualityPpm, successPseudoCount: group.passes, failurePseudoCount: group.judged - group.passes,
124
158
  sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
125
159
  judged: group.judged, passes: group.passes, priceVersions,
126
- source: `turn-history:${project}:${canonicalHash(group.rows.map(row => row.id).sort())}; pooled across effort and kind`,
127
- sourceDateMs: group.rows.reduce((latest, row) => Math.max(latest, row.ts), 0), ...rates });
160
+ source: `turn-history:${project}:${canonicalHash(group.rows.map(row => row.id).sort())}; pooled across kind`,
161
+ sourceDateMs: group.rows.reduce((latest, row) => Math.max(latest, row.ts), 0), ...rates };
162
+ if (group.seatId) prior.seatId = group.seatId;
163
+ qualityPriors.push(prior);
128
164
  }
129
165
  const { hash: _hash, ...previous } = policy;
130
166
  const draft = createPolicy({ ...previous, parentVersion: policy.version,
@@ -136,8 +172,10 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
136
172
  if (draft.version === policy.version) throw new Error('draft_version_must_change');
137
173
  return { policy: draft, summary: { project, snapshotId: snapshot.id, parentVersion: policy.version,
138
174
  rosterEntries: roster.length, priorsDerived: qualityPriors.length, rowsRead: turns.length,
139
- verifiedAcceptancesRead: acceptances.length, excluded, samples,
140
- seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model))
175
+ verifiedAcceptancesRead: acceptances.length, excluded, tokenExcluded, recovered, samples,
176
+ tokenBasis: 'non-cache input + output',
177
+ seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model
178
+ && (prior.seatId === undefined || prior.seatId === seat.seatId)))
141
179
  .map(seat => seat.seatId),
142
180
  priorsWithUnknownRates: qualityPriors.filter(prior => Object.values(prior.rates).some(rate => rate === null)).length } };
143
181
  }
@@ -149,10 +187,15 @@ export async function draftPolicyFromStore({ service, orgId, input, actor, requi
149
187
  const authority = await service.readAdvice(client, { orgId, request: { project: request.project } });
150
188
  const turns = (await client.query("SELECT row FROM turns WHERE org_id=$1 AND row->>'project'=$2 ORDER BY ts,id",
151
189
  [orgId, request.project])).rows.map(row => row.row);
190
+ const ids = [...new Set(turns.map(row => row.card).filter(id => Number.isSafeInteger(id) && id > 0))];
191
+ const cards = (await client.query(`SELECT id AS card,project,difficulty FROM tasks
192
+ WHERE org_id=$1 AND project=$2 AND id=ANY($3::bigint[])`, [orgId, request.project, ids])).rows
193
+ .map(row => ({ ...row, card: Number(row.card) }));
194
+ for (const card of authority.snapshot.readyQueue) if (!cards.some(row => row.card === card.card)) cards.push(card);
152
195
  const acceptances = (await client.query(`SELECT a.row FROM dispatcher_acceptances a
153
196
  JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id AND j.acceptance_id=a.id
154
197
  WHERE a.org_id=$1 AND j.project=$2 AND j.state IN ('passed','failed') ORDER BY (a.row->>'atMs')::bigint DESC,a.id`,
155
198
  [orgId, request.project])).rows.map(row => row.row);
156
- return draftPolicy({ ...authority, ...request, turns, acceptances, createdBy: actor.pubkey, nowMs: clock() });
199
+ return draftPolicy({ ...authority, ...request, turns, acceptances, cards, createdBy: actor.pubkey, nowMs: clock() });
157
200
  });
158
201
  }
@@ -126,7 +126,7 @@ export const AccountOverrideSchema = object({
126
126
  });
127
127
  export const QualityPriorSchema = object({
128
128
  provider: text, model: nullable(text), effort: text, kind: text, difficulty: text,
129
- harness: text.optional(), sampleCount: integer.optional(), tokenSampleCount: integer.optional(),
129
+ harness: text.optional(), seatId: text.optional(), sampleCount: integer.optional(), tokenSampleCount: integer.optional(),
130
130
  durationSampleCount: integer.optional(), judged: integer.optional(), passes: integer.optional(),
131
131
  priceVersions: list(nullable(text)).optional(),
132
132
  durationMs: positive, tokenEstimate: integer, capabilityScorePpm: ppm,
@@ -145,6 +145,7 @@ CREATE TABLE IF NOT EXISTS peers (
145
145
  llm TEXT,
146
146
  model TEXT,
147
147
  account_identity JSONB,
148
+ adapter_version TEXT,
148
149
  PRIMARY KEY (org_id, session)
149
150
  );
150
151
  -- additive migrations for hubs whose peers table predates these columns
@@ -153,6 +154,7 @@ ALTER TABLE peers ADD COLUMN IF NOT EXISTS machine TEXT;
153
154
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS llm TEXT;
154
155
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS model TEXT;
155
156
  ALTER TABLE peers ADD COLUMN IF NOT EXISTS account_identity JSONB;
157
+ ALTER TABLE peers ADD COLUMN IF NOT EXISTS adapter_version TEXT;
156
158
  -- DELIBERATELY no CHECK on peers.kind, unlike identities.kind above. The hub accepts whatever a
157
159
  -- client stamps (hub.mjs /register takes any string up to 40 chars) and the vocabulary grows with
158
160
  -- the product — 'genesis' arrived in #6068, 'orch' in #6075. #6169 is the cost of getting this
package/lib/store-pg.mjs CHANGED
@@ -166,6 +166,7 @@ function peerFromRow(row) {
166
166
  llm: row.llm || "",
167
167
  model: row.model || "",
168
168
  accountIdentity: row.account_identity || null,
169
+ adapterVersion: row.adapter_version || null,
169
170
  };
170
171
  }
171
172
 
@@ -473,8 +474,8 @@ export class PgStore {
473
474
  async touchPeer(orgId, session, patch = {}) {
474
475
  if (!session || session === "all") return;
475
476
  await this.pool.query(
476
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
477
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
477
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity, adapter_version)
478
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb,$15)
478
479
  ON CONFLICT(org_id, session) DO UPDATE SET
479
480
  pubkey=COALESCE(EXCLUDED.pubkey, peers.pubkey),
480
481
  project=COALESCE(NULLIF(EXCLUDED.project,''), peers.project),
@@ -491,13 +492,14 @@ export class PgStore {
491
492
  machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
492
493
  llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
493
494
  model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
494
- account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
495
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity),
496
+ adapter_version=COALESCE(NULLIF(EXCLUDED.adapter_version,''), peers.adapter_version)`,
495
497
  [
496
498
  session, orgId, patch.pubkey || null, patch.project || "", patch.status ?? null,
497
499
  patch.hookVersion || patch.hook_version || "", ms(patch.lastSeen || patch.last_seen),
498
500
  patch.online ?? true, Number(patch.deliveredUpTo || patch.delivered_up_to || 0),
499
501
  patch.kind || "", patch.machine || "", patch.llm || "", patch.model || "",
500
- patch.accountIdentity ? JSON.stringify(patch.accountIdentity) : null,
502
+ patch.accountIdentity ? JSON.stringify(patch.accountIdentity) : null, patch.adapterVersion || null,
501
503
  ],
502
504
  );
503
505
  }
@@ -627,8 +629,8 @@ export class PgStore {
627
629
  );
628
630
  for (const [session, p] of Object.entries(state.peers || {})) {
629
631
  await c.query(
630
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
631
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
632
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity, adapter_version)
633
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb,$15)
632
634
  ON CONFLICT(org_id, session) DO UPDATE SET pubkey=EXCLUDED.pubkey, project=EXCLUDED.project, status=EXCLUDED.status,
633
635
  hook_version=EXCLUDED.hook_version, last_seen=EXCLUDED.last_seen, online=EXCLUDED.online, delivered_up_to=GREATEST(peers.delivered_up_to, EXCLUDED.delivered_up_to),
634
636
  -- #6170: same non-demoting rule as touchPeer. A snapshot is written from MEMORY, and
@@ -638,8 +640,9 @@ export class PgStore {
638
640
  machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
639
641
  llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
640
642
  model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
641
- account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
642
- [session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null],
643
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity),
644
+ adapter_version=COALESCE(NULLIF(EXCLUDED.adapter_version,''), peers.adapter_version)`,
645
+ [session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null, p.adapterVersion || null],
643
646
  );
644
647
  }
645
648
  await c.query(
@@ -772,8 +775,8 @@ export class PgStore {
772
775
  for (const raw of peers.upserts) {
773
776
  const p = stripNulDeep(raw);
774
777
  await c.query(
775
- `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity)
776
- VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb)
778
+ `INSERT INTO peers(session, org_id, pubkey, project, status, hook_version, last_seen, online, delivered_up_to, kind, machine, llm, model, account_identity, adapter_version)
779
+ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14::jsonb,$15)
777
780
  ON CONFLICT(org_id, session) DO UPDATE SET pubkey=EXCLUDED.pubkey, project=EXCLUDED.project, status=EXCLUDED.status,
778
781
  hook_version=EXCLUDED.hook_version, last_seen=EXCLUDED.last_seen, online=EXCLUDED.online, delivered_up_to=GREATEST(peers.delivered_up_to, EXCLUDED.delivered_up_to),
779
782
  -- #6170: THIS is the path a running hub actually persists through — saveDelta on the
@@ -783,8 +786,9 @@ export class PgStore {
783
786
  machine=COALESCE(NULLIF(EXCLUDED.machine,''), peers.machine),
784
787
  llm=COALESCE(NULLIF(EXCLUDED.llm,''), peers.llm),
785
788
  model=COALESCE(NULLIF(EXCLUDED.model,''), peers.model),
786
- account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity)`,
787
- [p.session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null],
789
+ account_identity=COALESCE(EXCLUDED.account_identity, peers.account_identity),
790
+ adapter_version=COALESCE(NULLIF(EXCLUDED.adapter_version,''), peers.adapter_version)`,
791
+ [p.session, orgId, p.pubkey || "", p.project || "", p.status || "", p.hookVersion || "", Number(p.lastSeen || 0), p._on === true || p.online === true, Number(p.deliveredUpTo || 0), p.kind || "", p.machine || "", p.llm || "", p.model || "", p.accountIdentity ? JSON.stringify(p.accountIdentity) : null, p.adapterVersion || null],
788
792
  );
789
793
  }
790
794
  if (peers.deletes.length) await c.query("DELETE FROM peers WHERE org_id=$1 AND session = ANY($2::text[])", [orgId, peers.deletes]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.159",
3
+ "version": "0.18.160",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"