import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync } from "node:fs"; import type { TaskAttribution } from "./attribution.ts"; import { segmentsOf, streamEnd } from "./log-rotation.ts"; import type { PeerId } from "./envelope.ts"; import type { StageSwitchTrace as SwitchTrace } from "../models/route/stage-fallback.ts"; import type { ScreenRecord } from "./inference.ts"; import { safeModelLabel } from "../omniroute/usage.ts"; export interface RoleIdentity { id: string; layer: "shipped" | "project"; hash: string } /** * #1402: how a turn's model was learned, strongest first. `served`: the provider or the native transcript named it for this turn's responses. `session`: the native session's current model id. * `configured`: only the hub's own override or launch flag is known. An alias is recorded as the native surface reported it, never expanded. */ export const MODEL_EVIDENCE = ["served", "session", "configured"] as const; export type ModelEvidence = (typeof MODEL_EVIDENCE)[number]; export const isModelEvidence = (value: unknown): value is ModelEvidence => typeof value === "string" && (MODEL_EVIDENCE as readonly string[]).includes(value); /** What a peer adapter observed for the turn that just ended. */ export interface ModelObservation { model: string; evidence: ModelEvidence } /** The `turn_end` fields for an observation: both or neither. A label that fails `safeModelLabel` is dropped whole (never truncated into another valid-looking id) and nothing but the id is kept. */ export function turnModelFields(observed: unknown): { model: string; modelEvidence: ModelEvidence } | Record { if (!observed || typeof observed !== "object") return {}; const { model, evidence } = observed as { model?: unknown; evidence?: unknown }; const label = safeModelLabel(model); return label !== undefined && isModelEvidence(evidence) ? { model: label, modelEvidence: evidence } : {}; } /** #1556 T2: the closed, text-free edit counts a turn may add to `turn_end` (only when it modified files). `e` is the edit tool [total, verifiedFull, partialOnly, blindOrStale, occRejected], `s` the shell route [total, verifiedFull, partialOnly, blindOrStale, blockedByGuard], `u` tree writes no stream attributed. Counts only: never a path, a command or text. */ export const EDIT_OBS = ["hook", "stream", "tree"] as const; export const EDIT_ARMS = ["baseline", "soft_guidance", "route_guard", "occ_guard", "combined_guard", "shadow"] as const; export type EditCounts = [number, number, number, number, number]; export interface TurnEdits { obs: (typeof EDIT_OBS)[number]; arm?: (typeof EDIT_ARMS)[number]; e?: EditCounts; s?: EditCounts; u?: number; fe?: number; rev?: number } const EDIT_MAX = 1_000_000; const editCount = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= EDIT_MAX; const editCounts = (v: unknown): EditCounts | undefined => Array.isArray(v) && v.length === 5 && v.every(editCount) ? (v as EditCounts).slice() as EditCounts : undefined; /** Rebuilds `turn_end.edits` from an untrusted value, field by field: a field that is not exactly the closed shape is dropped whole, and a value with no valid `obs` is dropped altogether. */ export function turnEdits(raw: unknown): TurnEdits | undefined { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined; const r = raw as Record; if (!(EDIT_OBS as readonly unknown[]).includes(r.obs)) return undefined; const e = editCounts(r.e), s = editCounts(r.s); return { obs: r.obs as TurnEdits["obs"], ...((EDIT_ARMS as readonly unknown[]).includes(r.arm) ? { arm: r.arm as TurnEdits["arm"] } : {}), ...(e ? { e } : {}), ...(s ? { s } : {}), ...(editCount(r.u) ? { u: r.u } : {}), ...(editCount(r.fe) ? { fe: r.fe } : {}), ...(editCount(r.rev) ? { rev: r.rev } : {}) }; } /** Bumped whenever a field changes meaning or goes away; new fields and new types do not bump it. */ export const EVENTS_SCHEMA = 1; /** * One line of `events.jsonl`, the machine-readable twin of hub.log (issue #40). Never a message body: envelopes carry * ids, routing and sizes, tasks carry ids and states, so the file can be exported without leaking what agents wrote. */ export type HubEvent = /** Owned reviewer accounting, never a native session/home or model text. Unmatched starts remain unknown after restart. */ | { type: "reviewer_accounting"; peer: string; attempt: string; outcome: "started" | "complete" | "unknown" } | { type: "model_change"; peer: string; previousModel: string | null; model: string | null; by: "person"; source: "cli" | "dashboard"; appliesFrom: "next_turn"; afterTurn?: string } | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docsDigest: string; documents: number } | { type: "release_authorization"; by: PeerId; authorization: string; commit: string; version: string; docs: "none" } | { type: "permission_mode"; peer: string; from: import("./permission-mode.ts").PermissionMode; to: import("./permission-mode.ts").PermissionMode } | { type: "role"; peer?: string; task?: number; actor: string; stage: "prepared" | "assigned"; roles: { id: string; layer: "shipped" | "project"; hash: string }[] } /** A settings change (#269): the registry key, the bounded registry values before/after and their source; an optional person reason is sanitized and capped at 400 UTF-8 bytes. */ | { type: "settings"; key: string; from: import("./settings.ts").SettingValue; to: import("./settings.ts").SettingValue; source: "dashboard" | "terminal" | "conductor"; peer?: string; undo?: boolean; reason?: string } /** A structural config edit (#689): the file, key paths with short hashes of their values before and after (never a value), the file revisions and the person who made it. */ | { type: "config_edit"; file: "config.local.json" | "sdlc.toml"; paths: { path: string; before: string | null; after: string | null }[]; fileBefore: string; fileAfter: string; tier: 2 | 3; by: string; source: "dashboard" | "terminal" | "conductor"; backup?: string; reason?: string; instructionClaim?: "person_direct_instruction" } | { type: "sdlc_config_instruction"; by: string; paths: string[]; instructionClaim: "person_direct_instruction" } /** #445 C2: an invocation's ids, class and outcome. Never an argument, a result or a description. */ | { type: "invocation"; id: string; caller: string; target: string; capability: string; class: string; outcome: string; task?: number; bytes?: number } /** `origin` (#604 PR B): the sending connection's role, peer and launch or instance id. Never a path or text; absent for an envelope the hub itself wrote. */ | { type: "envelope"; id: string; from: string; to?: string[]; priority: string; hop: number; kind?: string; task?: string; bytes?: number; private?: boolean; dropped?: string; origin?: import("./provenance.ts").Origin } /** #604 PR B: one per peer-role or tools-role hello, with the same fields an envelope's `origin` carries. No cwd, root or token. */ | ({ type: "attach" } & import("./provenance.ts").Origin) /** Visual payloads and paths stay local; observer events carry counts only. */ | { type: "visual"; id: string; kind: "mermaid" | "comparison" | "table" | "beforeAfter"; bytes: number; files: number; task?: number } | { type: "overflow" | "undeliverable"; id: string; from: string; peer: string } | { type: "stale"; id: string; from: string; peer: string; task?: string } | { type: "quiet"; id: string; from: string; peers: string[] } | { type: "fact"; peer: string; id: string; files: number; plans: number; unknown: number; named: number; bytes: number; via: "hook" | "steer" | "done"; ms?: number; hookMs?: number; rttMs?: number; accepted?: boolean; unanswered?: boolean; probe?: boolean; coverage?: boolean } | { type: "fact_ack"; peer: string; id: string; via: string; ms: number } | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionTarget?: "judge"; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial) | { type: "cooldown"; peer: string; alias: string; event: "start" | "end"; failures: number; ms?: number } | { type: "route_outcome"; peer: string; decision: string; turnId: string; turn: "completed" | "failed"; task?: number; pii: boolean; latched: boolean; next?: { severity: number; tests: "pass" | "fail" | "none"; repeat: boolean }; advisor?: "approve" | "redo" | "failed" } | { type: "advisor"; peer: string; route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number } | { type: "progress"; peer: string; task: number; severity: number; spinning: number; exploring: number; production: number } | { type: "stuck"; peer: string; task: number; category: "repetition" | "false_progress" | "drift" | "desperation" | "capability_gap"; streak: number; latched: boolean } | { type: "capability"; peer: string; state: "verified" | "lost"; via?: string } /** A hub run began: every peer is detached until its next state event (#248: attachments never span a crash). */ /** `personAttribution`: this run writes `task` and `attribution` on permission, question, completion and agent_cli events (#1278). A log with no such start says nothing about which task a person interaction belonged to. */ | { type: "hub_start"; instance: string; personAttribution?: true } /** #248: the add-ons a peer works with, names and versions from a closed list, at each attach. */ | { type: "tooling"; peer: string; addons: import("./tooling.ts").Addon[] } /** #258: a task brief handed to its owner: how many hub-memory items (and fails among them) and supplemental items (legacy claudeMem field), never their text. New local-library records identify source amem. */ | { type: "memory_brief"; source?: "amem"; peer: string; task: number; native: number; fails: number; claudeMem: number } /** #1330: the session preface a peer was given: its size in bytes, the number of memory lines in it, and whether observed use reordered the long-term section. Numbers and a boolean only, never a line. */ | { type: "preface"; peer: string; bytes: number; lines: number; ordered: boolean } | { type: "split"; task: number; where?: "routing" | "cohort"; verdict: "split" | "single" | "unknown"; single?: string; splitS?: number; singleS?: number; reason?: string; trace?: string[] } | { type: "state"; peer: string; state: string } | { type: "turn_start"; peer: string; turn: string } | { type: "native_thread"; peer: string; thread: string; fresh: boolean } | ({ type: "turn_end"; peer: string; turn: string; ms: number; tokens?: number; files?: number; snapshotMs?: number; preparedRoles?: RoleIdentity[] | null; model?: string; modelEvidence?: ModelEvidence; edits?: TurnEdits } & Partial) | { type: "native_turn_end"; peer: string; id?: string; reason?: "user_canceled" | "error" | "max_invocations" | "max_forced_invocations" | "max_token_budget_exceeded" | "terminal_step_type" | "terminal_custom_hook" } | { type: "conduct"; peer: string; action: string; task?: number; target?: string } | ({ type: "agent_cli"; peer: string; command: string; refused: boolean; delegated?: true; instructed?: true; instructionReceipt?: string } & Partial) | ({ type: "permission"; id: string; peer: string; event: "requested" | "answered" | "expired" | "cancelled"; latencyMs?: number; surface?: "console" | "dashboard" | "terminal"; option?: "allow_once" | "allow_always" | "reject_once" | "reject_always" } & Partial) /** #1053: one question a peer asked the person, and how it ended. Counts, ids and a closed reason only: never a prompt, an option, an answer or other text. */ | ({ type: "question"; set: string; peer: string; event: "asked" | "answered" | "pending" | "superseded" | "cancelled" | "expired" | "unavailable"; latencyMs?: number; surface?: "terminal" | "console" | "dashboard" | "acon" | "conductor"; person?: string; reason?: "superseded" | "stopped" | "turn_aborted" | "session_changed" | "expired" | "unattended"; questions?: number; private?: boolean } & Partial) /** Completed native turns that received supervision, not feed enqueues or inferred costs. */ | { type: "supervision_turn"; peer: string; turn: string; tokens?: number; ms?: number } /** #1054: a run a person started settled (or a restart cut it short). Ids, a closed outcome and a duration only: never the prompt or the reply. */ /** #1054: a person (or the hub on a person's command) marked a result read. A receipt only: never read from a snapshot. */ | { type: "completion_seen"; id: string; surface: "terminal" | "console" | "dashboard" | "acon" } | ({ type: "completion"; id: string; peer: string; outcome: "done" | "failed" | "limit" | "interrupted"; ms: number } & Partial) | { type: "hook_stats"; peer: string; n: number; startupMs: number; hubMs: number; maxStartupMs: number } | { type: "cohort"; id: number; event: "formed" | "joined" | "lifted"; silent: boolean; tasks: number[]; owners: string[] } | ({ type: "tokens"; peer: string; n: number; source?: "kimi_wire"; id?: string } & Partial) | ({ type: "usage"; peer: string; source: "omniroute" | "claude_transcript" | "claude_result" | "codex_appserver" | "kimi_wire" | "jcode_acp" | "agy_transcript"; id: string; reasoningTokens?: number; measuredAt?: string; requestedModel?: string; servedModel?: string; provider?: string; inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; totalTokens?: number } & Partial) | { type: "planning"; by: string; task?: number; release?: number; fields: string[]; revision: number } | { type: "task"; id: number; event: string; by: string; state: string; owner: string | null; reviewer: string | null; class: string; profile?: string; profileClass?: string; role?: string; roleIdentity?: { id: string; layer: "shipped" | "project"; hash: string }; pii: boolean; reason?: string; release?: number | null; priority?: number | null; plannedStart?: number | null; due?: number | null } | { type: "overlap"; task: number; owner: string; others: { task: number; owner: string; paths: string[]; symbols?: string[] }[] } /** A PII screen verdict (issue #198): what was screened and the closed label, source and category, never the text. */ | ({ type: "pii_screen" } & ScreenRecord) | { type: "conflict"; peer: string; task?: number; other: number; owner: string; paths: string[]; concurrent: boolean; turns?: [string, string] } | { type: "context_pressure"; peer: string; source: string; measuredAt: number; used: number; window: number | null } /** #1331: a saved checkpoint and which structured fields it carried (names from a closed list, never text), so field use is countable. */ | { type: "checkpoint"; peer: string; reason: "quota" | "context"; fields: string[] } | { type: "quota"; peer: string; windows: { id: string; used: number; resetsAt?: number }[]; hard: boolean; measuredAt?: string } /** * The limit ledger (#683 U1): additive, ids and numbers only, no PROTOCOL bump (a reader that does not know a type ignores it). * `by` is who ended or began the pause: the coordinator (`hub`) or the console user (`person`, an override). */ | { type: "budget_pause"; peer: string; reason: string; window: string; resetsAt: number; by: "hub" | "person" } | { type: "budget_resume"; peer: string; reason: string; window: string; resetsAt: number; by: "hub" | "person" } /** A window's reset, derived from two readings of one window id: `resetsAt` moved forward, or `used` fell by 0.5 or more. */ | { type: "quota_reset"; peer: string; window: string; cause: "resets_at_moved" | "used_dropped"; resetsAt?: number; previousResetsAt?: number; used: number; previousUsed: number; measuredAt?: string }; export type StampedEvent = HubEvent & { v: number; at: string }; /** Whether the file's last byte is something other than a newline: a crash cut its last line short. */ function cutShort(file: string): boolean { if (!existsSync(file)) return false; const fd = openSync(file, "r"); try { const { size } = fstatSync(fd); if (!size) return false; const last = Buffer.alloc(1); readSync(fd, last, 0, 1, size - 1); return last[0] !== 0x0a; } finally { closeSync(fd); } } /** An appender that never throws: the state dir can vanish under a running hub, and telemetry must not take it down. */ export function eventLog(file: string, onFailure?: (e: HubEvent) => void): (e: HubEvent) => boolean { let first = true; return (e) => { try { // After a crash the first line goes on a line of its own, so only the cut event is lost. const lead = first && cutShort(file) ? "\n" : ""; first = false; appendFileSync(file, `${lead}${JSON.stringify({ v: EVENTS_SCHEMA, at: new Date().toISOString(), ...e })}\n`); return true; } catch { first = true; // A failed append may have left a partial row; recheck its newline before the next event. try { onFailure?.(e); } catch { /* telemetry failure reporting is optional too */ } // the state dir is gone; the watchdog is stopping the hub return false; } }; } /** * Kimi's running session totals to increments: only what was added since the last update counts; a new session * starts from zero whatever its first total, and a smaller total in the same session means it was reset. (Codex * differences its thread totals in the adapter, which knows whether a thread was started or resumed.) */ export function tokenDeltas(): (peer: string, total: number, session: string) => number { const last = new Map(); return (peer, total, session) => { const prev = last.get(peer); last.set(peer, { session, total }); return prev?.session === session && total >= prev.total ? total - prev.total : total; }; } /** * Events at or after `since` (ms), skipping lines a crash cut short. Reads every rotated segment (`log-rotation.ts`, #1546) oldest first and then the live file, so rotation never hides history from a reader; * the segment list is read again afterwards and the read repeated if a rotation moved the live file meanwhile. */ export function readEvents(file: string, since = 0): StampedEvent[] { for (let attempt = 0; ; attempt++) { const segments = segmentsOf(file), out: StampedEvent[] = []; for (const segment of segments) { let text: string; try { text = readFileSync(segment.path, "utf8"); } catch { continue; } // moved by a rotation since the listing: the check below repeats the read for (const line of text.split("\n")) { const event = parseEventLine(line, since); if (event !== undefined) out.push(event); } } const again = segmentsOf(file); if (attempt >= 3 || (again.length === segments.length && again.every((segment, i) => segment.path === segments[i]!.path && segment.start === segments[i]!.start))) return out; } } /** * #1555 AC5, #1546: the whole lines of the event log (its rotated segments and the live file make one byte stream: an offset is a position in that stream, so it keeps its meaning across a rotation) from byte `from` up to byte `to` (default: the end), each with the byte offset it starts at, read in bounded chunks, never the file from byte 0 unless `from` is 0. * A trailing piece with no newline yet is not a line: it is left for the pass that sees its end. Returns the offset after the last whole line, which is where the next pass starts. * A line is the bytes between two `\n`, so a multi-byte character never splits one. * Bytes below the oldest kept segment are gone: a `from` below it starts at the oldest segment. A trailing piece with no newline can only be the live file's last bytes. */ export function scanEventLines(file: string, from: number, each: (line: string, offset: number) => void, to = Infinity): number { const segments = segmentsOf(file); if (!segments.length) return from; let position = Math.max(from, segments[0]!.start); const end = Math.min(streamEnd(segments), to); for (const segment of segments) { const segmentEnd = Math.min(segment.start + segment.size, end); if (segmentEnd <= position) continue; if (segment.start >= end) break; position = segment.start + scanFileLines(segment.path, position - segment.start, (line, offset) => each(line, segment.start + offset), segmentEnd - segment.start); if (position < segmentEnd) break; // a trailing piece with no newline yet: the next pass sees its end } return position; } function scanFileLines(file: string, from: number, each: (line: string, offset: number) => void, to: number): number { if (!existsSync(file)) return from; const fd = openSync(file, "r"); try { const end = Math.min(fstatSync(fd).size, to); const chunk = Buffer.alloc(1 << 20); let pending = Buffer.alloc(0), base = from, at = from; while (at < end) { const n = readSync(fd, chunk, 0, Math.min(chunk.length, end - at), at); if (n <= 0) break; at += n; const data = pending.length ? Buffer.concat([pending, chunk.subarray(0, n)]) : Buffer.from(chunk.subarray(0, n)); let lineStart = 0; for (let nl = data.indexOf(0x0a, lineStart); nl >= 0; nl = data.indexOf(0x0a, lineStart)) { each(data.toString("utf8", lineStart, nl), base + lineStart); lineStart = nl + 1; } base += lineStart; pending = data.subarray(lineStart); } return base; } finally { closeSync(fd); } } /** The historical event-reader predicate, shared without adding shape or line-size restrictions. */ export function parseEventLine(line: string, since = 0): StampedEvent | undefined { if (!line.trim()) return undefined; try { const e = JSON.parse(line) as StampedEvent; const measuredAt = e.type === "usage" && typeof e.measuredAt === "string" ? e.measuredAt : e.at; return Date.parse(measuredAt) >= since ? e : undefined; } catch { return undefined; } } /** `7d`, `24h`, `90m` or an ISO date, as epoch ms; undefined when it is neither. */ export function parseSince(text: string, now = Date.now()): number | undefined { const m = /^(\d+)([dhm])$/.exec(text); if (m) return now - Number(m[1]) * { d: 86_400_000, h: 3_600_000, m: 60_000 }[m[2] as "d" | "h" | "m"]; // ISO dates only: Date.parse also takes "7" (a year in 2001), which would silently mean everything. const t = /^\d{4}-\d\d-\d\d/.test(text) ? Date.parse(text) : NaN; return Number.isNaN(t) ? undefined : t; }