trantor 0.18.161 → 0.18.163

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.161"
9
+ "version": "0.18.163"
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.161",
16
+ "version": "0.18.163",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.161",
3
+ "version": "0.18.163",
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": {
@@ -39,7 +39,7 @@ import {
39
39
  CUT_CHAIN_PARK_MIN, cutChainEvidence, isBoundedPark, askDuringTurn, askedVerdict,
40
40
  } from "../lib/turn-policy.mjs";
41
41
  import { snapshotBeforeCut } from "./cut-snapshot.mjs";
42
- import { ocTurnUsage, ocSessionId, kimiTurnUsage, dshTurnUsage, codexTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput, codexTurnModel, kimiTurnModel, claudeTurnModel } from "../lib/turn-usage.mjs";
42
+ import { ocTurnUsage, ocSessionId, kimiTurnUsage, dshTurnUsage, codexTurnUsage, claudeTurnUsage, usageTotal, processedInput, codexStepInput, kimiStepInput, claudeStepInput, codexTurnModel, kimiTurnModel, claudeTurnModel } from "../lib/turn-usage.mjs";
43
43
  import { effortName, isInfraFailure, providerForModel } from "../lib/fitness.mjs";
44
44
  import { capConfig, capDecision, capHandoffPrompt, capPointerLine, capExhaustedNote } from "../lib/context-cap.mjs";
45
45
  import { ocCompactionContent, ocCompactionLogLine, readOpencodeUserConfig, seatMcpOverlay, seatPermissionOverlay, seatConfigContent } from "../lib/seat-compaction.mjs";
@@ -1220,6 +1220,7 @@ exit $turn_exit`;
1220
1220
  if (DRIVER === "codex") {
1221
1221
  const found = codexSessionId(join(homedir(), ".codex", "sessions"), TURN_DIR, t0);
1222
1222
  if (found) sid = found;
1223
+ log(`codex usage lookup: sid=${sid || "none"} cwd=${TURN_DIR} t0=${new Date(t0).toISOString()}`);
1223
1224
  }
1224
1225
  if (DRIVER === "gemini") {
1225
1226
  const found = geminiSessionId(join(homedir(), ".gemini"), TURN_DIR, t0);
@@ -1286,14 +1287,13 @@ exit $turn_exit`;
1286
1287
  // 0 means "this CLI printed no usage", never "free" — so only overwrite when the envelope
1287
1288
  // actually carried counts.
1288
1289
  if (c) tokens = c.input + c.output + c.cache_read + c.cache_creation;
1289
- } // #8234: the CLIs that print no usage on stdout keep the counts in their own session records —
1290
- // opencode's db, kimi's wire, the dsh session log, codex's rollout. Sum this turn's window there;
1291
- // null (unknown) leaves the stdout paths above standing — never 0 ("free"). #14663: the sqlite
1292
- // reads go through node's built-in SQLite (netcup has no sqlite3 binary), else glm/openrouter ~0.
1290
+ } // Provider session records carry usage missing from stdout; Claude's result envelope carries it.
1291
+ // Null leaves the stdout total alone: unknown is never zero. #14663 uses node:sqlite for opencode.
1293
1292
  const usage = cli.pinned && sid ? ocTurnUsage(OC_DB, sid, t0, Date.now())
1294
1293
  : AGENT === "dsh" ? dshTurnUsage(join(homedir(), ".dsh", "sessions"), TURN_DIR, t0, Date.now())
1295
1294
  : DRIVER === "codex" && sid ? codexTurnUsage(join(homedir(), ".codex", "sessions"), sid, TURN_DIR, t0, Date.now())
1296
1295
  : DRIVER === "kimi" ? kimiTurnUsage(join(homedir(), ".kimi-code", "sessions"), sid, t0, Date.now())
1296
+ : DRIVER === "claude" ? claudeTurnUsage(lastEnvelope || ownOut)
1297
1297
  : null;
1298
1298
  if (usage) tokens = usageTotal(usage);
1299
1299
  // #11559: every token this turn spent rides the card it served. A card-0 turn (kickoff, pulse,
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.161",
3
+ "version": "0.18.163",
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",
@@ -0,0 +1,17 @@
1
+ import { z } from 'zod';
2
+
3
+ const numeric = z.union([z.number().finite(), z.string().regex(/^\d+(?:\.\d+)?$/)]);
4
+ const iso = z.string().regex(/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/);
5
+
6
+ export function balanceResetMs(value, observedAtMs) {
7
+ const number = numeric.safeParse(value);
8
+ if (number.success) {
9
+ const raw = Number(number.data);
10
+ // Contemporary provider epochs arrive in both seconds and milliseconds; synthetic clocks keep their unit.
11
+ const ms = raw > 0 && raw < 1e12 && observedAtMs >= 1e12 ? raw * 1000 : raw;
12
+ return Number.isSafeInteger(ms) && ms > 0 ? ms : null;
13
+ }
14
+ const date = iso.safeParse(value);
15
+ const ms = date.success ? Date.parse(date.data) : NaN;
16
+ return Number.isSafeInteger(ms) && ms >= 0 ? ms : null;
17
+ }
@@ -17,7 +17,7 @@ function closedAt(task) {
17
17
  return closed?.ts ?? null;
18
18
  }
19
19
 
20
- function projectCard(task, tasks, featureRegistryHash) {
20
+ function projectCard(task, tasks, featureRegistryHash, shadow) {
21
21
  const parsedDrill = z.string().min(1).refine(value => value.trim().length > 0).safeParse(task.extra?.drill);
22
22
  if (task.status !== 'todo' || !parsedDrill.success) return null;
23
23
  const deps = (task.deps || []).map(id => tasks.get(Number(id)));
@@ -30,7 +30,8 @@ function projectCard(task, tasks, featureRegistryHash) {
30
30
  kind: task.extra.kind || 'unknown', difficulty: task.difficulty,
31
31
  subsystem: task.extra.subsystem || 'unknown', size: { easy: 's', medium: 'm', hard: 'l' }[task.difficulty],
32
32
  deps: deps.map(dep => ({ project: dep.project, card: Number(dep.id) })), depsBasis: 'board',
33
- resources: [], needs: [], features: [], effectClass: 'workspace', artifactKind: 'commit',
33
+ resources: shadow ? [{ repoId: task.project, kind: 'tree', key: '.', mode: 'write' }] : [],
34
+ needs: [], features: [], effectClass: 'workspace', artifactKind: 'commit',
34
35
  drillSpecId: `board:${task.project}#${task.id}:${createHash('sha256').update(drill).digest('hex').slice(0, 16)}`,
35
36
  featureRegistryHash, drill, readySinceMs: deps.length ? Math.max(...closeTimes) : Number(task.created), pin: null,
36
37
  };
@@ -53,7 +54,7 @@ export async function projectBoardCards(client, orgId, policy, { featureRegistry
53
54
  const id = Number(task.id);
54
55
  const managed = existing.get(id);
55
56
  if (managed && managed.row.depsBasis !== 'board') continue;
56
- const card = projectCard(task, byId, featureRegistryHash);
57
+ const card = projectCard(task, byId, featureRegistryHash, policy.modeByProject[task.project] === 'shadow');
57
58
  if (!card) continue;
58
59
  retained.add(id);
59
60
  const contentHash = canonicalHash(card);
@@ -4,6 +4,7 @@ import { canonicalHash } from './snapshot.mjs';
4
4
  import { heldLiability } from './spend.mjs';
5
5
  import { DEFAULT_POLICY } from './policy.mjs';
6
6
  import { loadCatalog, lookup } from '../model-catalog.mjs';
7
+ import { balanceResetMs } from './balance-time.mjs';
7
8
 
8
9
  const text = (value, max = 8192) => String(value ?? '').slice(0, max);
9
10
  const numberOrNull = value => value == null || value === '' || !Number.isFinite(Number(value)) ? null : Number(value);
@@ -24,7 +25,7 @@ function windowRecord({ accountId, id, kind, unit, value, observedAtMs, received
24
25
  const known = value != null;
25
26
  return {
26
27
  id: text(id), accountId, kind, unit, startsAtMs: null,
27
- resetsAtMs: integerOrNull(resetsAtMs), capacity: unit === 'quotaMillionths' && known ? 1_000_000 : null,
28
+ resetsAtMs: balanceResetMs(resetsAtMs, observedAtMs), capacity: unit === 'quotaMillionths' && known ? 1_000_000 : null,
28
29
  remaining: observation({ value, observedAtMs, receivedAtMs, source, sourceRevision,
29
30
  status: known ? 'ok' : 'unknown', reason }),
30
31
  accountedThroughEvent: null, reserve: 0, heldLiability: heldLiability(0), dailyTimeZone: null,
@@ -148,11 +149,15 @@ function reportedAdapters(seats, machine, nowMs, policy) {
148
149
  }))].sort();
149
150
  }
150
151
 
151
- function machineEvidence({ rows, seats, nowMs, policy }) {
152
+ function machineEvidence({ rows, seats, boundSeats, nowMs, policy }) {
152
153
  const evidence = [];
153
154
  const emitted = new Set();
155
+ const credentials = machine => [...new Set(boundSeats.filter(({ record: seat }) => seat.machine === machine
156
+ && seat.accountId !== null && seats.some(row => row.session === seat.id && row.online === true))
157
+ .map(({ record: seat }) => seat.accountId))].sort();
154
158
  for (const row of Array.isArray(rows) ? rows : []) {
155
- const id = text(row?.machine, 60);
159
+ const reportedId = text(row?.machine, 60);
160
+ const id = seats.find(seat => text(seat.machine, 60).toLowerCase() === reportedId.toLowerCase())?.machine || reportedId;
156
161
  const observedAtMs = timestamp(row?.ts);
157
162
  if (!id || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
158
163
  const key = id.toLowerCase();
@@ -171,7 +176,8 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
171
176
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
172
177
  record: { id, health: observation({ value: health, observedAtMs, receivedAtMs: nowMs,
173
178
  source: 'machine-beats', status: 'ok', sourceRevision: observedAtMs }),
174
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
179
+ tools: [], credentialBindings: credentials(id), maxSeats: policy.machineLimits.maxSeatsByMachine?.[id] ?? 0,
180
+ activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
175
181
  }
176
182
  for (const seat of seats) {
177
183
  const id = text(seat?.machine, 60);
@@ -184,7 +190,8 @@ function machineEvidence({ rows, seats, nowMs, policy }) {
184
190
  observedAtMs, expiresAtMs: observedAtMs + policy.machineTtlMs,
185
191
  record: { id, health: observation({ value: null, observedAtMs, receivedAtMs: nowMs,
186
192
  source: 'presence', status: 'unknown', reason: 'no fresh machine health beat', sourceRevision: observedAtMs }),
187
- tools: [], credentialBindings: [], maxSeats: 0, activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
193
+ tools: [], credentialBindings: credentials(id), maxSeats: policy.machineLimits.maxSeatsByMachine?.[id] ?? 0,
194
+ activeSeats: seatCount, adapterVersions: reportedAdapters(seats, id, nowMs, policy) } });
188
195
  }
189
196
  return evidence;
190
197
  }
@@ -231,7 +238,7 @@ function modelEnvelope({ provider, model, observedAtMs, expiresAtMs, nowMs, cata
231
238
  efforts: details?.found && details.effort ? Object.keys(details.effort).sort() : [], breakerId: null } };
232
239
  }
233
240
 
234
- function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
241
+ function modelEvidence({ rows, seats, boundSeats, accounts, nowMs, policy, catalog }) {
235
242
  const models = new Map();
236
243
  for (const row of Array.isArray(rows) ? rows : []) {
237
244
  const provider = text(row?.provider, 200);
@@ -260,10 +267,16 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
260
267
  const agent = text(seat?.llm, 200);
261
268
  const observedAtMs = timestamp(seat?.lastTurn?.ts);
262
269
  if (!model || !seatId || !agent || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
263
- const provider = model.includes('/') ? text(model.split('/')[0], 200) : agent;
264
- const key = `${provider}\0${model}`;
270
+ const bound = boundSeats.find(row => row.id === seatId)?.record;
271
+ const account = accounts.find(row => row.kind === 'account' && row.id === bound?.accountId)?.record;
272
+ if (account?.status !== 'verified') continue;
273
+ const provider = account.provider;
274
+ const key = `${provider}\0${model}\0${account.id}`;
275
+ if (models.get(key)?.record.invocation.observedAtMs >= observedAtMs) continue;
265
276
  const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
266
277
  expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
278
+ envelope.id = `invocation:${account.id}:${model}`;
279
+ envelope.record.accountId = account.id;
267
280
  envelope.record.invocation = observation({ value: { model, seatId, harness: 'crew' }, observedAtMs,
268
281
  receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
269
282
  envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
@@ -283,22 +296,23 @@ export function buildEvidence({ balances = [], machines = [], seats = [], discov
283
296
  for (const { record: seat } of boundSeats) {
284
297
  const turn = presentSeats.find(row => row.session === seat.id)?.lastTurn;
285
298
  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;
299
+ if (seat.model !== null || account?.status !== 'verified'
300
+ || !fresh(timestamp(turn?.ts), nowMs, policy.invocationTtlMs)) continue;
288
301
  const envelope = modelEnvelope({ provider: account.provider, model: null, observedAtMs: turn.ts,
289
302
  expiresAtMs: turn.ts + policy.invocationTtlMs, nowMs, catalog });
290
303
  envelope.id = `default:${seat.id}`;
291
304
  envelope.sourceRef = `presence:${seat.id}:${turn.ts}`;
292
305
  envelope.record.accountId = account.id;
293
- envelope.record.liveUse = { seatId: seat.id, harness: seat.harness, attemptId: turn.attemptId };
306
+ envelope.record.liveUse = { seatId: seat.id, harness: seat.harness };
307
+ if (turn.attemptId) envelope.record.liveUse.attemptId = text(turn.attemptId);
294
308
  envelope.record.efforts = [!turn.effort || turn.effort === 'unknown' ? 'default' : turn.effort];
295
309
  defaults.push(envelope);
296
310
  }
297
311
  return [
298
312
  ...accounts,
299
- ...machineEvidence({ rows: machines, seats: presentSeats, nowMs, policy }),
313
+ ...machineEvidence({ rows: machines, seats: presentSeats, boundSeats, nowMs, policy }),
300
314
  ...boundSeats,
301
- ...modelEvidence({ rows: discovery, seats: presentSeats, nowMs, policy, catalog }),
315
+ ...modelEvidence({ rows: discovery, seats: presentSeats, boundSeats, accounts, nowMs, policy, catalog }),
302
316
  ...defaults,
303
317
  ];
304
318
  }
@@ -3,6 +3,8 @@ 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
5
  import { isInfraFailure } from '../fitness.mjs';
6
+ import { CREW_ADAPTER_VERSION } from './harness/contract.mjs';
7
+ import { calibrateQuotaRates } from './quota-calibration.mjs';
6
8
 
7
9
  const text = z.string().min(1).max(8192);
8
10
  const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@@ -100,7 +102,7 @@ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptan
100
102
  const identity = { provider: account.provider, harness: seat.harness, model: seat.model === null ? null : recordedModel,
101
103
  difficulty: recordedDifficulty.success ? recordedDifficulty.data : cardDifficulty.data,
102
104
  effort: !effort || effort === 'unknown' ? 'default' : effort };
103
- if (seat.model === null) identity.seatId = seat.id;
105
+ if (seat.model === null || account.windows.some(window => window.unit === 'quotaMillionths')) identity.seatId = seat.id;
104
106
  if (!measurementReason && !row.attempt) recovered.withoutAttempt++;
105
107
  if (!measurementReason && !recordedDifficulty.success) recovered.cardDifficulty++;
106
108
  const groupKey = key(identity);
@@ -158,7 +160,36 @@ function ratesFor(group, policy) {
158
160
  rateSource: 'unobserved: no active policy rate or legacy model rate', rateAsOfMs: 0 };
159
161
  }
160
162
 
161
- export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], cards, project, version, createdBy, nowMs }) {
163
+ function measuredRatesFor(group, policy, bound, calibration) {
164
+ const existing = ratesFor(group, policy);
165
+ const seat = bound.find(row => row.id === group.seatId);
166
+ const account = calibration.accounts.find(row => row.accountId === seat?.accountId);
167
+ if (!account?.windows.length) return existing;
168
+ return { ...existing, rates: { ...existing.rates, quotaMillionthsPerMTok: account.quotaMillionthsPerMTok },
169
+ rateSource: account.rateSource ?? `unobserved:${account.reason}`, rateAsOfMs: account.rateAsOfMs ?? 0 };
170
+ }
171
+
172
+ function draftPlacement(policy, snapshot, roster, priors) {
173
+ const hosts = new Map();
174
+ for (const seat of roster) {
175
+ const machine = snapshot.machines.find(row => row.id === seat.host);
176
+ const bound = snapshot.seats.find(row => row.id === seat.seatId);
177
+ const account = snapshot.accounts.find(row => row.id === bound.accountId);
178
+ if (seat.harness !== 'crew' || !seat.adapterVersions.includes(CREW_ADAPTER_VERSION)
179
+ || bound.busy || machine.health.status !== 'ok' || machine.health.observedAtMs === null
180
+ || machine.health.observedAtMs > snapshot.asOfMs || snapshot.asOfMs - machine.health.observedAtMs > policy.machineTtlMs
181
+ || !machine.credentialBindings.includes(account.id) || machine.maxSeats <= machine.activeSeats
182
+ || !priors.some(prior => prior.provider === account.provider && prior.harness === seat.harness
183
+ && prior.model === seat.model && (prior.seatId === undefined || prior.seatId === seat.seatId))) continue;
184
+ hosts.set(seat.host, (hosts.get(seat.host) ?? 0) + 1);
185
+ }
186
+ const host = policy.placementByKind.default ?? [...hosts].sort((a, b) => b[1] - a[1]
187
+ || a[0].localeCompare(b[0]))[0]?.[0] ?? null;
188
+ return { host, excludedSeats: roster.filter(seat => seat.host !== host).map(seat => seat.seatId).sort() };
189
+ }
190
+
191
+ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], cards, project, version, createdBy, nowMs,
192
+ balanceHistory = [], seatHistory = [], calibrationTurns = turns }) {
162
193
  const policy = verifyPolicy(inputPolicy);
163
194
  const snapshot = verifySnapshot(inputSnapshot);
164
195
  if (snapshot.policyVersion !== policy.version) throw new Error('policy_stale');
@@ -172,6 +203,8 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
172
203
  return entry;
173
204
  });
174
205
  const minimumSamples = policy.priorMinimumSamples ?? 5;
206
+ const quotaCalibration = calibrateQuotaRates({ accounts: snapshot.accounts, balanceHistory, seatHistory,
207
+ turns: calibrationTurns, nowMs, minimumIntervals: policy.quotaCalibrationMinimumIntervals ?? 5 });
175
208
  const { groups, excluded, tokenExcluded, recovered, seats } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances, cards ?? snapshot.readyQueue);
176
209
  const qualityPriors = [];
177
210
  const samples = [];
@@ -199,7 +232,7 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
199
232
  samples.push({ ...sample, reason, reasons, estimateStatus: reason ? 'no_estimate' : 'estimated' });
200
233
  if (reason) continue;
201
234
  const qualityPpm = Number((BigInt(group.passes) + 1n) * 1_000_000n / (BigInt(group.judged) + 2n));
202
- const rates = ratesFor(group, policy);
235
+ const rates = measuredRatesFor(group, policy, bound, quotaCalibration);
203
236
  const prior = { provider: group.provider, harness: group.harness,
204
237
  model: group.model, effort: group.effort, kind: '*', difficulty: group.difficulty,
205
238
  durationMs: sample.medianDurationMs, tokenEstimate: sample.medianTokens,
@@ -222,8 +255,11 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
222
255
  : !seat.rowsRead ? 'no_turns' : !seat.qualifyingTurns ? 'no_qualifying_turns' : 'insufficient_samples' };
223
256
  });
224
257
  const { hash: _hash, ...previous } = policy;
258
+ const placement = draftPlacement(policy, snapshot, roster, qualityPriors);
225
259
  const draft = createPolicy({ ...previous, parentVersion: policy.version,
226
260
  priorMinimumSamples: minimumSamples,
261
+ quotaCalibrationMinimumIntervals: quotaCalibration.minimumIntervals,
262
+ placementByKind: placement.host ? { ...policy.placementByKind, default: placement.host } : policy.placementByKind,
227
263
  version: version || `${policy.version}-draft-${nowMs}`, createdAtMs: nowMs, createdBy,
228
264
  roster: [...policy.roster.filter(row => !snapshot.seats.some(seat => seat.id === row.seatId
229
265
  && (seat.project === project || seat.project === undefined))), ...roster],
@@ -233,7 +269,10 @@ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turn
233
269
  return { policy: draft, summary: { project, snapshotId: snapshot.id, parentVersion: policy.version,
234
270
  rosterEntries: roster.length, priorsDerived: qualityPriors.length, rowsRead: turns.length,
235
271
  verifiedAcceptancesRead: acceptances.length, excluded, tokenExcluded, recovered, samples,
236
- priorMinimumSamples: minimumSamples, seats: seatSummaries,
272
+ priorMinimumSamples: minimumSamples, seats: seatSummaries, quotaCalibration,
273
+ placement,
274
+ machineCapacity: { maxSeatsByMachine: policy.machineLimits.maxSeatsByMachine ?? {},
275
+ source: policy.machineLimits.maxSeatsSource ?? null },
237
276
  tokenBasis: 'non-cache input + output',
238
277
  seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model
239
278
  && (prior.seatId === undefined || prior.seatId === seat.seatId)))
@@ -246,8 +285,11 @@ export async function draftPolicyFromStore({ service, orgId, input, actor, requi
246
285
  return service.store.locked(orgId, async client => {
247
286
  await requireRole(client, orgId, actor, '*', ['owner'], true);
248
287
  const authority = await service.readAdvice(client, { orgId, request: { project: request.project } });
249
- const turns = (await client.query("SELECT row FROM turns WHERE org_id=$1 AND row->>'project'=$2 ORDER BY ts,id",
250
- [orgId, request.project])).rows.map(row => row.row);
288
+ const calibrationTurns = (await client.query('SELECT row FROM turns WHERE org_id=$1 ORDER BY ts,id',
289
+ [orgId])).rows.map(row => row.row);
290
+ const turns = calibrationTurns.filter(row => row.project === request.project);
291
+ const history = (await client.query(`SELECT kind,row FROM dispatcher_evidence
292
+ WHERE org_id=$1 AND kind IN ('account','seat') ORDER BY observed_at_ms,id,revision`, [orgId])).rows;
251
293
  const ids = [...new Set(turns.map(row => row.card).filter(id => Number.isSafeInteger(id) && id > 0))];
252
294
  const cards = (await client.query(`SELECT id AS card,project,difficulty FROM tasks
253
295
  WHERE org_id=$1 AND project=$2 AND id=ANY($3::bigint[])`, [orgId, request.project, ids])).rows
@@ -257,6 +299,8 @@ export async function draftPolicyFromStore({ service, orgId, input, actor, requi
257
299
  JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id AND j.acceptance_id=a.id
258
300
  WHERE a.org_id=$1 AND j.project=$2 AND j.state IN ('passed','failed') ORDER BY (a.row->>'atMs')::bigint DESC,a.id`,
259
301
  [orgId, request.project])).rows.map(row => row.row);
260
- return draftPolicy({ ...authority, ...request, turns, acceptances, cards, createdBy: actor.pubkey, nowMs: clock() });
302
+ return draftPolicy({ ...authority, ...request, turns, calibrationTurns, acceptances, cards,
303
+ balanceHistory: history.filter(row => row.kind === 'account').map(row => row.row),
304
+ seatHistory: history.filter(row => row.kind === 'seat').map(row => row.row), createdBy: actor.pubkey, nowMs: clock() });
261
305
  });
262
306
  }
@@ -0,0 +1,193 @@
1
+ import { z } from 'zod';
2
+ import { AccountSchema, SeatSchema } from './schemas.mjs';
3
+ import { balanceResetMs } from './balance-time.mjs';
4
+
5
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
6
+ const text = z.string().min(1);
7
+ const TurnSchema = z.object({ id: text, ts: integer, project: text, persona: text.optional(),
8
+ attempt: z.object({ seat: text.optional() }).passthrough().nullish(), usage: z.unknown().optional() }).passthrough();
9
+ const UsageSchema = z.object({ input: integer, output: integer, cacheRead: integer.optional(),
10
+ cacheWrite: integer.optional() }).passthrough();
11
+ const increment = (counts, reason) => { counts[reason] = (counts[reason] ?? 0) + 1; };
12
+ const observationKey = row => JSON.stringify([row.source, row.value, row.status, row.resetsAtMs, row.detail]);
13
+
14
+ function bindingAt(history, ts) {
15
+ let low = 0;
16
+ let high = history.length;
17
+ while (low < high) {
18
+ const middle = Math.floor((low + high) / 2);
19
+ if (history[middle].lastBeatMs <= ts) low = middle + 1;
20
+ else high = middle;
21
+ }
22
+ const seat = history[low - 1];
23
+ return { accountId: seat?.accountId ?? null, reason: !history.length ? 'no_seat_history'
24
+ : !seat ? 'before_seat_history' : !seat.accountId ? 'unbound_account' : null };
25
+ }
26
+
27
+ function accountTurns(turns, seatHistory, nowMs) {
28
+ const bindings = new Map();
29
+ for (const input of seatHistory) {
30
+ const parsed = SeatSchema.safeParse(input);
31
+ if (!parsed.success || parsed.data.lastBeatMs === null || parsed.data.lastBeatMs > nowMs) continue;
32
+ const seat = parsed.data;
33
+ if (!bindings.has(seat.id)) bindings.set(seat.id, []);
34
+ bindings.get(seat.id).push(seat);
35
+ }
36
+ for (const [id, rows] of bindings) {
37
+ const times = new Map();
38
+ for (const row of rows) {
39
+ const previous = times.get(row.lastBeatMs);
40
+ times.set(row.lastBeatMs, previous && previous.accountId !== row.accountId ? { ...row, accountId: null } : row);
41
+ }
42
+ bindings.set(id, [...times.values()].sort((a, b) => a.lastBeatMs - b.lastBeatMs));
43
+ }
44
+ const excluded = {};
45
+ const accounts = new Map();
46
+ const seen = new Set();
47
+ for (const input of turns) {
48
+ const parsed = TurnSchema.safeParse(input);
49
+ if (!parsed.success) { increment(excluded, 'invalid_turn'); continue; }
50
+ const row = parsed.data;
51
+ if (seen.has(row.id)) { increment(excluded, 'duplicate_turn'); continue; }
52
+ seen.add(row.id);
53
+ if (row.ts > nowMs) { increment(excluded, 'future_turn'); continue; }
54
+ const seatId = row.attempt?.seat ?? (row.persona ? `${row.persona}:${row.project}` : null);
55
+ const { accountId, reason } = bindingAt(bindings.get(seatId) ?? [], row.ts);
56
+ if (!accountId) { increment(excluded, reason); continue; }
57
+ const usage = UsageSchema.safeParse(row.usage);
58
+ const tokens = usage.success ? BigInt(usage.data.input) + BigInt(usage.data.output) : null;
59
+ if (!accounts.has(accountId)) accounts.set(accountId, []);
60
+ accounts.get(accountId).push({ ts: row.ts, tokens,
61
+ reason: row.usage == null ? 'no_structured_usage' : !usage.success ? 'invalid_structured_usage' : null });
62
+ }
63
+ for (const rows of accounts.values()) rows.sort((a, b) => a.ts - b.ts);
64
+ return { accounts, excluded };
65
+ }
66
+
67
+ function observationsByWindow(balanceHistory, nowMs) {
68
+ const accounts = new Map();
69
+ for (const input of balanceHistory) {
70
+ const parsed = AccountSchema.safeParse(input);
71
+ if (!parsed.success || parsed.data.status !== 'verified') continue;
72
+ const account = parsed.data;
73
+ if (!accounts.has(account.id)) accounts.set(account.id, new Map());
74
+ const windows = accounts.get(account.id);
75
+ for (const window of account.windows) {
76
+ const atMs = window.remaining.observedAtMs;
77
+ if (window.accountId !== account.id || window.unit !== 'quotaMillionths' || atMs === null || atMs > nowMs
78
+ || window.remaining.receivedAtMs > nowMs) continue;
79
+ if (!windows.has(window.id)) windows.set(window.id, new Map());
80
+ const times = windows.get(window.id);
81
+ const row = { atMs, value: window.remaining.value, status: window.remaining.status,
82
+ receivedAtMs: window.remaining.receivedAtMs, source: window.remaining.source,
83
+ detail: window.remaining.reason, resetsAtMs: balanceResetMs(window.resetsAtMs, atMs), conflict: false };
84
+ const previous = times.get(atMs);
85
+ if (previous && previous.receivedAtMs > row.receivedAtMs) continue;
86
+ row.conflict = previous !== undefined && previous.receivedAtMs === row.receivedAtMs
87
+ && (previous.conflict || previous.value !== row.value || previous.status !== row.status
88
+ || previous.resetsAtMs !== row.resetsAtMs);
89
+ if (previous && previous.receivedAtMs === row.receivedAtMs && observationKey(previous) < observationKey(row)) {
90
+ times.set(atMs, { ...previous, conflict: row.conflict });
91
+ continue;
92
+ }
93
+ times.set(atMs, row);
94
+ }
95
+ }
96
+ return accounts;
97
+ }
98
+
99
+ function intervalReason(before, after) {
100
+ if (before.conflict || after.conflict) return 'conflicting_observation';
101
+ if ([before, after].some(row => row.value === null && row.status === 'unknown')) return 'balance_not_reported';
102
+ if (before.status !== 'ok' || after.status !== 'ok' || before.value === null || after.value === null
103
+ || before.value > 1_000_000 || after.value > 1_000_000) return 'unknown_balance';
104
+ if (before.resetsAtMs === null || after.resetsAtMs === null) return 'unknown_reset';
105
+ if (before.resetsAtMs !== after.resetsAtMs || before.resetsAtMs <= after.atMs) return 'reset';
106
+ if (after.value > before.value) return 'balance_increased';
107
+ return null;
108
+ }
109
+
110
+ function medianRate(intervals) {
111
+ const sorted = [...intervals].sort((a, b) => {
112
+ const difference = a.numerator * b.tokens - b.numerator * a.tokens;
113
+ return difference < 0n ? -1 : difference > 0n ? 1 : 0;
114
+ });
115
+ const middle = Math.floor(sorted.length / 2);
116
+ const upper = sorted[middle];
117
+ const lower = sorted.length % 2 ? upper : sorted[middle - 1];
118
+ const numerator = lower.numerator * upper.tokens + upper.numerator * lower.tokens;
119
+ const denominator = 2n * lower.tokens * upper.tokens;
120
+ return Number((numerator + denominator - 1n) / denominator);
121
+ }
122
+
123
+ function calibrateWindow(windowId, times, turns, minimumIntervals) {
124
+ const observations = [...times.values()].sort((a, b) => a.atMs - b.atMs);
125
+ const excluded = {};
126
+ const intervals = [];
127
+ let turnIndex = 0;
128
+ for (let index = 1; index < observations.length; index++) {
129
+ const before = observations[index - 1];
130
+ const after = observations[index];
131
+ let reason = intervalReason(before, after);
132
+ let tokens = 0n;
133
+ while (turnIndex < turns.length && turns[turnIndex].ts <= after.atMs) {
134
+ const turn = turns[turnIndex++];
135
+ if (turn.ts <= before.atMs) continue;
136
+ if (turn.reason) reason ??= turn.reason;
137
+ else tokens += turn.tokens;
138
+ }
139
+ if (tokens === 0n) reason ??= 'no_known_tokens';
140
+ if (reason) { increment(excluded, reason); continue; }
141
+ intervals.push({ numerator: BigInt(before.value - after.value) * 1_000_000n, tokens,
142
+ startMs: before.atMs, endMs: after.atMs });
143
+ }
144
+ const noBalance = observations.length > 0 && (observations.every(row => row.value === null && row.status === 'unknown')
145
+ || observations.length > 1 && excluded.balance_not_reported === observations.length - 1);
146
+ const reason = noBalance ? 'balance_not_reported' : intervals.length < minimumIntervals ? 'insufficient_intervals' : null;
147
+ const latest = observations.at(-1);
148
+ return { windowId, observationsRead: observations.length, intervalsUsed: intervals.length, excluded,
149
+ observationRule: 'latest_received_at_per_observed_at', sources: [...new Set(observations.map(row => row.source))].sort(),
150
+ balanceDetails: [...new Set(observations.map(row => row.detail).filter(Boolean))].sort(),
151
+ latestObservation: latest ? { observedAtMs: latest.atMs, receivedAtMs: latest.receivedAtMs,
152
+ source: latest.source, value: latest.value, status: latest.status, resetsAtMs: latest.resetsAtMs,
153
+ conflicting: latest.conflict } : null,
154
+ quotaMillionthsPerMTok: reason ? null : medianRate(intervals), reason,
155
+ windowStartMs: intervals[0]?.startMs ?? null, windowEndMs: intervals.at(-1)?.endMs ?? null,
156
+ rateAsOfMs: reason ? null : intervals.at(-1).endMs };
157
+ }
158
+
159
+ export function calibrateQuotaRates({ accounts, balanceHistory = [], seatHistory = [], turns = [], nowMs,
160
+ minimumIntervals = 5 }) {
161
+ integer.min(1).parse(minimumIntervals);
162
+ integer.parse(nowMs);
163
+ const observations = observationsByWindow(balanceHistory, nowMs);
164
+ const attributed = accountTurns(turns, seatHistory, nowMs);
165
+ const summaries = accounts.map(account => {
166
+ const windowIds = [...new Set(account.windows.filter(window => window.unit === 'quotaMillionths').map(window => window.id))].sort();
167
+ const windows = windowIds.map(id => calibrateWindow(id, observations.get(account.id)?.get(id) ?? new Map(),
168
+ attributed.accounts.get(account.id) ?? [], minimumIntervals));
169
+ const missing = windows.filter(window => window.reason);
170
+ const prepaidUsd = account.windows.some(window => window.kind === 'prepaid')
171
+ && account.windows.every(window => window.unit === 'usdMicros');
172
+ const missingReasons = [...new Set(missing.map(window => window.reason))];
173
+ const reason = account.status !== 'verified' ? 'unverified_account'
174
+ : !windows.length ? prepaidUsd ? 'not_applicable:prepaid_usd' : 'no_quota_windows'
175
+ : missing.length ? missingReasons.length === 1 ? `${missingReasons[0]}:${missing.map(window => window.windowId).join(',')}`
176
+ : missing.map(window => `${window.reason}:${window.windowId}`).join(';') : null;
177
+ const selected = reason ? null : [...windows].sort((a, b) => b.quotaMillionthsPerMTok - a.quotaMillionthsPerMTok
178
+ || a.windowId.localeCompare(b.windowId))[0];
179
+ const excluded = {};
180
+ for (const window of windows) for (const [name, count] of Object.entries(window.excluded)) excluded[name] = (excluded[name] ?? 0) + count;
181
+ const accountRows = attributed.accounts.get(account.id) ?? [];
182
+ return { accountId: account.id, provider: account.provider, minimumIntervals, windows, reason, excluded,
183
+ accountType: prepaidUsd ? 'prepaid_usd' : windows.length ? 'quota' : 'unknown',
184
+ turnsAttributed: accountRows.length, turnsWithUsage: accountRows.filter(row => row.tokens !== null).length,
185
+ intervalsUsed: windows.reduce((sum, window) => sum + window.intervalsUsed, 0),
186
+ selectedWindowId: selected?.windowId ?? null, quotaMillionthsPerMTok: selected?.quotaMillionthsPerMTok ?? null,
187
+ rateSource: selected ? `measured:${selected.intervalsUsed} intervals` : null,
188
+ rateAsOfMs: selected?.rateAsOfMs ?? null };
189
+ }).sort((a, b) => a.accountId.localeCompare(b.accountId));
190
+ const turnsAttributed = [...attributed.accounts.values()].reduce((sum, rows) => sum + rows.length, 0);
191
+ return { minimumIntervals, tokenBasis: 'non-cache input + output', turnsRead: turns.length, turnsAttributed,
192
+ turnExcluded: attributed.excluded, accounts: summaries };
193
+ }
@@ -39,7 +39,7 @@ export const ModelEvidenceSchema = object({
39
39
  provider: text, model: nullable(text), accountId: nullable(text),
40
40
  catalog: ObservationSchema(z.boolean()), entitlement: ObservationSchema(z.boolean()),
41
41
  invocation: ObservationSchema(object({ model: text, seatId: text, harness: text })),
42
- liveUse: nullable(object({ seatId: text, harness: text, attemptId: text })),
42
+ liveUse: nullable(object({ seatId: text, harness: text, attemptId: text.optional() })),
43
43
  capabilities: strings, efforts: strings, breakerId: nullable(text),
44
44
  });
45
45
  export const BreakerScopeSchema = object({
@@ -141,6 +141,7 @@ export const PolicySchema = object({
141
141
  createdAtMs: integer, createdBy: text, plannerVersion: text,
142
142
  modeByProject: record(z.enum(['off', 'shadow', 'admit'])),
143
143
  shadowIntervalMs: positive.optional(), priorMinimumSamples: positive.optional(),
144
+ quotaCalibrationMinimumIntervals: positive.optional(),
144
145
  roster: list(object({ seatId: text, harness: text, enabled: z.boolean(), host: text,
145
146
  model: nullable(text).optional(), adapterVersions: strings.optional(), agent: text.optional() })),
146
147
  placementByKind: record(text), discoveryTtlMs: positive, invocationTtlMs: positive,
@@ -154,7 +155,8 @@ export const PolicySchema = object({
154
155
  deadlineHorizonMs: positive, agingPerHourPpm: ppm, agingCapPpm: positive }),
155
156
  retry: object({ maxSwaps: integer, backoffMs: list(integer) }),
156
157
  machineLimits: object({ cpuPct: percent, memPressurePct: percent,
157
- minDiskFreeBytes: integer, minFreeMemoryBytes: integer }),
158
+ minDiskFreeBytes: integer, minFreeMemoryBytes: integer,
159
+ maxSeatsByMachine: record(integer).optional(), maxSeatsSource: text.optional() }),
158
160
  kill: object({ fleet: z.boolean(), projects: strings }),
159
161
  exclusions: list(object({ scope: BreakerScopeSchema, approvalId: text, reason: text })),
160
162
  });
@@ -127,7 +127,7 @@ export function codexSessionId(sessionsRoot, cwd, sinceMs, { nowMs = Date.now(),
127
127
  const day = new Date(nowMs - i * 86400000);
128
128
  const dir = join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));
129
129
  for (const name of directoryNames(dir)) {
130
- const match = /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.jsonl$/i.exec(name);
130
+ const match = /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.jsonl$/i.exec(name);
131
131
  if (!match) continue;
132
132
  const file = join(dir, name);
133
133
  let mtime;
@@ -347,6 +347,27 @@ export function kimiTurnModel(sessionsRoot, sid, sinceMs) {
347
347
  return model;
348
348
  }
349
349
 
350
+ // Claude's JSON result (a single envelope or the last result in stream-json) is the turn total.
351
+ // Assistant events are deliberately ignored: their per-step counts would double-count the result.
352
+ export function claudeTurnUsage(stream) {
353
+ const raw = String(stream || "").trim();
354
+ if (!raw) return null;
355
+ const events = [];
356
+ try { events.push(JSON.parse(raw)); } catch {
357
+ for (const line of raw.split("\n")) {
358
+ try { events.push(JSON.parse(line)); } catch {}
359
+ }
360
+ }
361
+ const result = events.filter(ev => ev?.type === "result").at(-1);
362
+ const u = result?.usage;
363
+ const keys = ["input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"];
364
+ if (!u || Array.isArray(u) || !keys.some(k => Object.prototype.hasOwnProperty.call(u, k))) return null;
365
+ const inp = field(u.input_tokens), out = field(u.output_tokens),
366
+ cr = field(u.cache_read_input_tokens), cw = field(u.cache_creation_input_tokens);
367
+ if ([inp, out, cr, cw].some(v => v === null)) return null;
368
+ return { input: inp, output: out, cacheRead: cr, cacheWrite: cw };
369
+ }
370
+
350
371
  // claude: ~/.claude/projects/<cwd-slug>/*.jsonl (claudeTranscriptDir names the seat's dir), the
351
372
  // newest transcript touched in the window; assistant rows carry message.usage. Subagent rows
352
373
  // (isSidechain) are skipped. A 1MB tail, since an assistant line can carry long text.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.161",
3
+ "version": "0.18.163",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"