@0perator/operator 0.1.162 → 0.1.164

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,58 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on A
4
4
  Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
5
5
  npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
6
6
 
7
+ ## 0.1.164 — 2026-10-01 — Token meter (engine) + Switchboard messages inline in the transcript
8
+ - `src/engine/token-meter.ts` learns each endpoint's REAL chars-per-token online from the exact counts
9
+ the server already reports (`timings.prompt_n`, `usage.completion_tokens`): EMA (converges in ~10
10
+ rounds), per-`base|model` keys (two servers on one model id can tokenize differently), +4 tokens per
11
+ message of chat-template framing the old counter missed entirely, estimates round UP (compact a hair
12
+ early ≪ 400 the request). Sample guards drop zero-token reports, <500-char prompts, and out-of-range
13
+ (1.0–12.0) ratios — the 40-tool-call turn that used to poison the meter can no longer move it. Cold
14
+ start = the legacy 4.0 prior, so no behavior cliff on upgrade. Calibration persists to
15
+ `~/.axe/operator/token-calibration.json` (throttled cache; corrupt/missing degrades to cold, boot is
16
+ never blocked). NO static `node:fs` import — the shared engine graph must stay node-free for the
17
+ `esbuild --platform=neutral` iOS bundle — fs arrives via `process.getBuiltinModule`, degrading to an
18
+ in-memory meter on JSCore/browser.
19
+ - Wired through ONE process-wide `globalTokenMeter` so an observation from any surface calibrates all:
20
+ the compaction gate (`CompactionOpts.meter`/`meterKey` — gate, ceiling, clampMaxTokens and fitToWindow
21
+ all size to the endpoint the request will ACTUALLY hit), the size router (pooled sample-weighted
22
+ ratio in `router-adapter.ts`), the status-rule ctx% and `/compact` freed math (`session.ts` — one char
23
+ basis everywhere, enforced by construction), aurora's missing-timings output fallback (`ChatResult
24
+ .tokensExact` flags server-exact counts so the fallback never re-learns its own prior), and per-round
25
+ observation in `runTurn` (prompt side: `requestChars(built, toolSchemas)`; completion side: exact
26
+ samples only).
27
+ - `pickSummaryContent` (compaction.ts, SPEC §5 failure handling): content wins verbatim, reasoning is
28
+ the fallback, both dry ⇒ `""` so compact() SKIPS rather than persisting a fact-free placeholder over
29
+ real history; a throwing summarizer (500/drop mid-compaction) no longer kills the turn.
30
+ - `docs/token-meter.md` design notes (scope rules, durability, deferred ceiling);
31
+ `test/token-meter.test.mts` 18 tests: EMA math, all guards, endpoint isolation, persistence
32
+ round-trip + corrupt degradation, calibrated gate trip, picker, throw-safety, interrupted-pair validity.
33
+ - **Switchboard messages now render INLINE in the transcript**, superseding the 0.1.163 pinned click-to-expand
34
+ tray. The tray lived outside `<Static>`, so every 3s poll + re-render re-painted it and Ink orphaned the old
35
+ cards into scrollback (the "messages duplicate and never clear" bug). Now each bus message is a `kind:"bus"`
36
+ transcript entry appended at arrival time → `<Static>`-rendered (printed once), anchored to its place in the
37
+ conversation, scrolls with history. `src/ui/BusTray.tsx` removed. `src/ui/brand.ts` adds the Switchboard mark
38
+ `⦿` (a patch-jack; one const, swappable) with a direction arrow (◂ in / ▸ out) + `HH:MM`. `src/bus/inbox.ts`
39
+ gains `pollSent()` reading this session's own `sent/` archive so OUTBOUND traffic ("you sent X to Y") also
40
+ surfaces inline (consume-once via `sent-read/`, same discipline as the inbox). `src/cli.tsx` poller pushes
41
+ both directions; `src/ui/App.tsx` drops the tray + `busMessages` plumbing from both layouts.
42
+ - Full suite: 761 passed, 0 failed (104 files). `tsc --noEmit` clean; iOS `engine.bundle.js` builds under
43
+ `esbuild --platform=neutral` (engine graph remains node-free). Switchboard surface = Claude lane, grandmaster wave.
44
+
45
+ ## 0.1.163 — 2026-09-30 — TUI: live Switchboard messages in the terminal (click-to-expand)
46
+ - Incoming Switchboard agent messages (the provider-agnostic on-box bus, memjar/switchboard) now surface
47
+ **live in the Operator terminal** as a click-to-expand tray — the end-to-end proof of the Phase-1 mouse
48
+ layer. `src/bus/inbox.ts` reads this session's inbox directly (same mailbox format, no cross-repo dep;
49
+ neutral defaults `SWITCHBOARD_DIR`→`~/.switchboard`, `SWITCHBOARD_AGENT`→`AXE_AGENT`→`role@host`); a 3s
50
+ poller in `cli.tsx` feeds a bounded tail to `<App>`.
51
+ - `src/ui/BusTray.tsx` renders each message as a collapsible card, **top-anchored** so each card's absolute
52
+ terminal row is deterministic (`trayLayout()`, pure + tested) — which is what makes left-click hit-testing
53
+ reliable without Ink absolute-position measurement. Click toggles the body; inline mode shows cards
54
+ read-only (no mouse there). A box without Switchboard installed shows nothing (empty-safe).
55
+ - Enterprise/AI-agnostic: no vendor lock, neutral env-overridable paths, works on any surface. Received
56
+ messages are DATA, never executed. Decision log: `_ai-docs/decisions/2026-09-30-switchboard-tui-bustray.md`.
57
+ Suite 748 green (+10).
58
+
7
59
  ## 0.1.162 — 2026-09-30 — TUI: wheel-scrollback in fullscreen (mouse layer wired into App)
8
60
  - The Phase 1 mouse mechanism is now live in the app. `App.tsx`'s fullscreen branch mounts `MouseProvider`
9
61
  (enabled only on a mouse-capable TTY — inline stays a native-scroll no-op) and a new `FullscreenBody`
@@ -0,0 +1,95 @@
1
+ // Switchboard inbox reader (Operator side of the provider-agnostic agent bus, memjar/switchboard).
2
+ // The bus is a file mailbox: one JSON file per message under <SWITCHBOARD_DIR>/agents/<agent>/inbox.
3
+ // This module reads THIS session's inbox so incoming messages can surface live in the TUI (BusTray) — the
4
+ // counterpart to the `switch`/`sb-msg` CLI other agents send with. We read the format directly rather than
5
+ // depend on the switchboard package, so kode-tsi stays self-contained.
6
+ //
7
+ // SECURITY: a bus message is DATA written by another agent — untrusted input. The UI surfaces it to the
8
+ // operator; nothing here executes message contents.
9
+ import { readdirSync, readFileSync, renameSync, mkdirSync, existsSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { homedir, hostname } from "node:os";
12
+ /** The bus state root — mirrors the switchboard CLI's SWITCHBOARD_DIR. Neutral default (~/.switchboard) so
13
+ * this works on any box/surface, not just the AXE fleet; the env var repoints it wherever the bus lives. */
14
+ export function busDir() {
15
+ return process.env.SWITCHBOARD_DIR || join(homedir(), ".switchboard");
16
+ }
17
+ /** This session's bus identity. Convention is role@node. SWITCHBOARD_AGENT is the neutral primary; AXE_AGENT
18
+ * is honored as a fleet fallback; else <role>@<host>. Vendor-neutral by default (no AI/product baked in). */
19
+ export function selfAgent() {
20
+ return process.env.SWITCHBOARD_AGENT || process.env.AXE_AGENT || `operator@${hostname().split(".")[0]}`;
21
+ }
22
+ const inboxOf = (agent) => join(busDir(), "agents", encodeURIComponent(agent), "inbox");
23
+ const readOf = (agent) => join(busDir(), "agents", encodeURIComponent(agent), "read");
24
+ const sentOf = (agent) => join(busDir(), "agents", encodeURIComponent(agent), "sent");
25
+ const sentReadOf = (agent) => join(busDir(), "agents", encodeURIComponent(agent), "sent-read");
26
+ /** Read `agent`'s inbox oldest-first. Unless `peek`, each message is moved to the read/ archive so it
27
+ * surfaces exactly once (delivered-once, matching the CLI). Corrupt or in-flight (.tmp-) files are
28
+ * skipped, never thrown — a bad drop can't wedge polling. Returns [] when the bus/inbox doesn't exist. */
29
+ export function pollBus(agent = selfAgent(), opts = {}) {
30
+ const dir = inboxOf(agent);
31
+ if (!existsSync(dir))
32
+ return [];
33
+ let files;
34
+ try {
35
+ files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.startsWith(".tmp-")).sort();
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ const out = [];
41
+ for (const f of files) {
42
+ const full = join(dir, f);
43
+ let msg = null;
44
+ try {
45
+ msg = JSON.parse(readFileSync(full, "utf8"));
46
+ }
47
+ catch { /* skip corrupt */ }
48
+ if (!msg || typeof msg.body !== "string")
49
+ continue;
50
+ out.push(msg);
51
+ if (!opts.peek) {
52
+ try {
53
+ mkdirSync(readOf(agent), { recursive: true });
54
+ renameSync(full, join(readOf(agent), f));
55
+ }
56
+ catch { /* already consumed by a concurrent read */ }
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ /** Read the archive of messages `agent` SENT — the switchboard CLI/lib mirrors a copy into sent/ on every
62
+ * send so this session can surface its OWN outbound traffic ("you sent X to Y") inline, the counterpart to
63
+ * pollBus. Same oldest-first, consume-once (move to sent-read/), corrupt-skip discipline. [] when no bus. */
64
+ export function pollSent(agent = selfAgent(), opts = {}) {
65
+ const dir = sentOf(agent);
66
+ if (!existsSync(dir))
67
+ return [];
68
+ let files;
69
+ try {
70
+ files = readdirSync(dir).filter((f) => f.endsWith(".json") && !f.startsWith(".tmp-")).sort();
71
+ }
72
+ catch {
73
+ return [];
74
+ }
75
+ const out = [];
76
+ for (const f of files) {
77
+ const full = join(dir, f);
78
+ let msg = null;
79
+ try {
80
+ msg = JSON.parse(readFileSync(full, "utf8"));
81
+ }
82
+ catch { /* skip corrupt */ }
83
+ if (!msg || typeof msg.body !== "string")
84
+ continue;
85
+ out.push(msg);
86
+ if (!opts.peek) {
87
+ try {
88
+ mkdirSync(sentReadOf(agent), { recursive: true });
89
+ renameSync(full, join(sentReadOf(agent), f));
90
+ }
91
+ catch { /* already consumed by a concurrent read */ }
92
+ }
93
+ }
94
+ return out;
95
+ }
package/dist/cli.js CHANGED
@@ -11,6 +11,7 @@ import { mastheadLines } from "./ui/Masthead.js";
11
11
  import { hyperlinkHint } from "./ui/capabilities.js";
12
12
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
13
13
  import { RemoteHost } from "./remote/host.js";
14
+ import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
14
15
  import { isErrorResult } from "./ui/format.js";
15
16
  import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
16
17
  import { Session } from "./session.js";
@@ -1488,6 +1489,26 @@ function Root() {
1488
1489
  const id = setInterval(() => setElapsed((Date.now() - turnStartRef.current) / 1000), 500); // 500ms: the elapsed readout shows whole/half seconds; 250ms doubled the whole-frame re-render rate (flashing)
1489
1490
  return () => clearInterval(id);
1490
1491
  }, [status]);
1492
+ // Switchboard poller: pull this session's incoming (inbox) and outgoing (sent/) agent messages every few
1493
+ // seconds and append each as an INLINE transcript entry at the moment it arrived/was sent — Static-rendered
1494
+ // so it's printed once, anchored to its place in the conversation, and scrolls with history (no pinned,
1495
+ // re-painted tray that duplicated into scrollback). pollBus/pollSent each consume-once (move to read/ and
1496
+ // sent-read/), so every message shows exactly once. No-op when the bus dir doesn't exist — a box without
1497
+ // Switchboard installed simply shows nothing. MUST be above the boot early-returns (stable hook order).
1498
+ useEffect(() => {
1499
+ if (boot !== "ready")
1500
+ return;
1501
+ const self = selfAgent();
1502
+ const pull = () => {
1503
+ for (const msg of pollBus(self))
1504
+ push({ kind: "bus", id: nextId(), msg, direction: "in", at: Date.now() });
1505
+ for (const msg of pollSent(self))
1506
+ push({ kind: "bus", id: nextId(), msg, direction: "out", at: Date.now() });
1507
+ };
1508
+ pull();
1509
+ const id = setInterval(pull, 3000);
1510
+ return () => clearInterval(id);
1511
+ }, [boot]);
1491
1512
  if (boot === "checking")
1492
1513
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
1493
1514
  if (boot === "down") {
@@ -6,6 +6,7 @@ import { chat } from "./aurora.js";
6
6
  import { buildMessages } from "./messages.js";
7
7
  import { recoverToolCalls } from "./toolcalls.js";
8
8
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens } from "./compaction.js";
9
+ import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
9
10
  import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
10
11
  import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
11
12
  const MAX_SELF_HEAL_PER_TURN = 3;
@@ -387,6 +388,8 @@ export async function runTurn(userInput, conversation, opts) {
387
388
  threshold: opts.compactionThreshold,
388
389
  ceilingTokens: opts.compactionCeilingTokens,
389
390
  minKeepTurns: opts.minKeepTurns,
391
+ meter: globalTokenMeter, // SPEC §5: size to THIS endpoint's learned ratio, not chars/4
392
+ meterKey: endpointKey(ep.base, ep.model),
390
393
  });
391
394
  let response;
392
395
  for (;;) {
@@ -446,6 +449,22 @@ export async function runTurn(userInput, conversation, opts) {
446
449
  genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
447
450
  promptTokensTotal += response.promptTokens ?? 0;
448
451
  promptMsTotal += response.promptMs ?? 0; // and prefill (the invisible wall-time cost)
452
+ // Token meter (SPEC §5): teach the endpoint its real chars/token from the server's EXACT
453
+ // counts. Prompt side: the built request through requestChars — the same basis every estimate
454
+ // uses (one basis, enforced by construction). Completion side: only when the server actually
455
+ // reported (tokensExact) — observing aurora's own chars/4 fallback would just re-assert the
456
+ // prior and dilute real signal. Guards inside observe*() drop zero/tiny/absurd samples.
457
+ {
458
+ const mKey = endpointKey(endpoint.base, endpoint.model);
459
+ if (response.promptTokens && response.promptTokens > 0) {
460
+ globalTokenMeter.observePrompt(mKey, requestChars(messages, opts.toolSchemas), response.promptTokens);
461
+ }
462
+ if (response.tokensExact && response.tokens && response.tokens > 0) {
463
+ const outChars = (response.content?.length ?? 0) + (response.reasoningContent?.length ?? 0)
464
+ + (response.toolCalls ?? []).reduce((n, t) => n + t.function.name.length + t.function.arguments.length, 0);
465
+ globalTokenMeter.observeCompletion(mKey, outChars, response.tokens);
466
+ }
467
+ }
449
468
  opts.onTokens?.(tokensTotal); // authoritative live count — includes tool-call-arg + reasoning tokens the delta stream misses
450
469
  break;
451
470
  }
@@ -1,6 +1,7 @@
1
1
  // selfheal.js only type-imports from here (erased at runtime), so importing its values back is not a
2
2
  // runtime cycle. Reused to retry a transient transport drop at the fetch layer (see fetchChat).
3
3
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
+ import { globalTokenMeter } from "./token-meter.js";
4
5
  const _endpointGates = new Map();
5
6
  function endpointSlots(_base) {
6
7
  // One knob for now (the fleet runs one single-slot Aurora); keyed by base so a future per-endpoint override
@@ -390,10 +391,11 @@ export async function chat(messages, o) {
390
391
  // never ~0 for a round that plainly did work.
391
392
  const generatedChars = content.length + reasoning.length +
392
393
  [...acc.values()].reduce((n, e) => n + e.name.length + e.args.length, 0);
393
- const tokens = meta.tokens && meta.tokens > 0 ? meta.tokens
394
- : generatedChars > 0 ? Math.max(1, Math.ceil(generatedChars / 4)) // SPEC §5 heuristic (chars/4)
394
+ const tokensExact = !!meta.tokens && meta.tokens > 0;
395
+ const tokens = tokensExact ? meta.tokens
396
+ : generatedChars > 0 ? globalTokenMeter.estimateCompletion(generatedChars) // SPEC §5: calibrated output ratio (cold = chars/4 prior)
395
397
  : meta.tokens;
396
- return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
398
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, tokensExact, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
397
399
  }
398
400
  /** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
399
401
  export async function health(base) {
@@ -81,8 +81,13 @@ export function estimateTokensHeuristic(messages) {
81
81
  return Math.ceil(chars / 4);
82
82
  }
83
83
  function fullRequestEstimate(conversation, opts) {
84
- const estimate = opts.estimateTokens ?? estimateTokensHeuristic;
85
84
  const system = opts.systemPrompt ? [{ role: "system", content: opts.systemPrompt }] : [];
85
+ // Calibrated path: the meter's ONE char basis (requestChars — content + tool_calls JSON + schemas,
86
+ // plus chat-template overhead) measured at the endpoint's learned ratio. Replaces both the chars/4
87
+ // heuristic AND the separate toolsTokens add-on below; the legacy path stays for un-metered callers.
88
+ if (opts.meter && opts.meterKey)
89
+ return opts.meter.estimateRequestFor(opts.meterKey, [...system, ...conversation], opts.tools);
90
+ const estimate = opts.estimateTokens ?? estimateTokensHeuristic;
86
91
  const toolsTokens = opts.tools?.length ? Math.ceil(JSON.stringify(opts.tools).length / 4) : 0;
87
92
  return estimate([...system, ...conversation]) + toolsTokens;
88
93
  }
@@ -142,6 +147,17 @@ export function clampMaxTokens(built, opts, want, min = 1024) {
142
147
  const room = opts.ctxWindow - promptEst - 256; // margin for chat-template/role tokens the estimate omits
143
148
  return Math.max(min, Math.min(want, room));
144
149
  }
150
+ /** The summary content picker (SPEC §5 failure handling). Aurora's always-on thinking frequently
151
+ * spends the whole budget on reasoning_content and returns EMPTY content — the facts still live in
152
+ * reasoning, so it is the fallback, never equal. Both dry ⇒ "" (NOT a placeholder): callers persist
153
+ * or splice only a non-empty result, so compact()'s empty guard can PRESERVE history instead of
154
+ * replacing real spans with a fact-free stub. */
155
+ export function pickSummaryContent(content, reasoning) {
156
+ const c = (content ?? "").trim();
157
+ if (c)
158
+ return c;
159
+ return (reasoning ?? "").trim();
160
+ }
145
161
  /** A "turn" starts at a user message. Returns the index of each turn start, in order. */
146
162
  function turnStarts(conversation) {
147
163
  const idxs = [];
@@ -3,6 +3,7 @@
3
3
  // engine lead during the tsi merge — the two lanes chose different Router shapes; this is the
4
4
  // single adapter that binds them, and the surface kode-web imports rather than reimplementing.
5
5
  import { AuroraRouter } from "../router/router.js";
6
+ import { globalTokenMeter } from "./token-meter.js";
6
7
  const toRE = (e) => ({
7
8
  base: e.base,
8
9
  model: e.model,
@@ -11,7 +12,10 @@ const toRE = (e) => ({
11
12
  });
12
13
  function estimateTokens(messages, tools) {
13
14
  const chars = JSON.stringify(messages).length + (tools ? JSON.stringify(tools).length : 0);
14
- return Math.ceil(chars / 4); // SPEC §5 heuristic (chars/4), same as compaction.ts
15
+ // SPEC §5: the pooled sample-weighted ratio across ALL endpoints. The router is what PICKS the
16
+ // endpoint, so per-endpoint calibration isn't known yet here — pooled is the honest aggregate,
17
+ // and it cold-starts at the legacy 4.0 prior (identical behavior to the old chars/4).
18
+ return Math.ceil(chars / globalTokenMeter.pooledPromptRatio());
15
19
  }
16
20
  /** Wrap an AuroraRouter so the agentic loop can call select()/recover(). */
17
21
  export function engineRouter(inner = new AuroraRouter()) {
@@ -0,0 +1,203 @@
1
+ function nodeFs() {
2
+ const proc = globalThis.process;
3
+ const fs = proc?.getBuiltinModule?.("node:fs");
4
+ return fs && typeof fs.readFileSync === "function" ? fs : undefined;
5
+ }
6
+ /** Parent dir of a path — all of node:path this cache needs. */
7
+ function parentDir(p) {
8
+ const i = Math.max(p.lastIndexOf("/"), p.lastIndexOf("\\"));
9
+ return i > 0 ? p.slice(0, i) : ".";
10
+ }
11
+ export const COLD_CHARS_PER_TOKEN = 4.0; // SPEC §5 legacy prior — kept until the first observation lands
12
+ const MIN_RATIO = 1.0; // absurd-guard: no real chat tokenizer packs denser than ~1 char/token…
13
+ const MAX_RATIO = 12.0; // …or sparser than ~12 (would mean the sample was template-dominated noise)
14
+ const MIN_SAMPLE_CHARS = 500; // ignore tiny prompts — one short greeting would yank the EMA around
15
+ const EMA_ALPHA = 0.25; // new samples move the ratio 25% of the way; ~10 rounds to mostly converge
16
+ const TEMPLATE_OVERHEAD_PER_MESSAGE = 4; // llama.cpp chat template tokens per message (role/BOS/EOS framing)
17
+ const SAVE_EVERY_MS = 60_000; // throttle disk writes — calibration is a cache, not a ledger
18
+ const SAVE_EVERY_OBS = 20; // …but never hold more than this many un-persisted observations
19
+ const freshCalibration = () => ({
20
+ promptRatio: COLD_CHARS_PER_TOKEN,
21
+ promptSamples: 0,
22
+ completionRatio: COLD_CHARS_PER_TOKEN,
23
+ completionSamples: 0,
24
+ });
25
+ /** Stable per-endpoint key. Two bases serving the same model id can tokenize differently
26
+ * (different templates/quant configs), so key on both, never on model alone. */
27
+ export function endpointKey(base, model) {
28
+ return `${base}|${model}`;
29
+ }
30
+ /** Exact char basis for ONE estimate/observe cycle. `messages` is the full built request
31
+ * (system message already prepended by buildMessages); `tools` are the schemas sent alongside. */
32
+ export function requestChars(messages, tools) {
33
+ let chars = 0;
34
+ for (const m of messages) {
35
+ chars += m.content.length;
36
+ if (m.tool_calls?.length)
37
+ chars += JSON.stringify(m.tool_calls).length;
38
+ }
39
+ if (tools)
40
+ chars += JSON.stringify(tools).length;
41
+ return chars;
42
+ }
43
+ export class TokenMeter {
44
+ cal = new Map();
45
+ persistPath;
46
+ lastSave = 0;
47
+ obsSinceSave = 0;
48
+ /** Samples only count when they carry signal: real server tokens, a big-enough prompt, and a
49
+ * sane ratio. A 0-token report (server omitted timings) or a 40-char greeting teaches nothing
50
+ * and would corrupt the average — drop it rather than learn noise. */
51
+ observePrompt(key, chars, promptTokens) {
52
+ if (!(promptTokens > 0) || chars < MIN_SAMPLE_CHARS)
53
+ return;
54
+ const ratio = chars / promptTokens;
55
+ if (!(ratio >= MIN_RATIO && ratio <= MAX_RATIO))
56
+ return;
57
+ const c = this.for(key);
58
+ c.promptRatio = c.promptSamples === 0 ? ratio : c.promptRatio + EMA_ALPHA * (ratio - c.promptRatio);
59
+ c.promptSamples += 1;
60
+ this.afterObserve();
61
+ }
62
+ /** Completion side: basis is streamed output chars (content + reasoning + tool-call args),
63
+ * truth is server completion tokens. Same guards — a 0-token tool_call round is the exact
64
+ * case that used to poison the old meter. */
65
+ observeCompletion(key, generatedChars, completionTokens) {
66
+ if (!(completionTokens > 0) || generatedChars < MIN_SAMPLE_CHARS)
67
+ return;
68
+ const ratio = generatedChars / completionTokens;
69
+ if (!(ratio >= MIN_RATIO && ratio <= MAX_RATIO))
70
+ return;
71
+ const c = this.for(key);
72
+ c.completionRatio = c.completionSamples === 0 ? ratio : c.completionRatio + EMA_ALPHA * (ratio - c.completionRatio);
73
+ c.completionSamples += 1;
74
+ this.afterObserve();
75
+ }
76
+ /** Full-request prompt estimate: measured ratio over the real char basis, plus template
77
+ * overhead. Rounds UP — for the compaction gate, overestimating by a fraction compacts a
78
+ * hair early (cheap); underestimating 400s the request (expensive). The 0.85 gate threshold
79
+ * remains the margin; the estimator itself stays unbiased. */
80
+ estimateRequest(messages, tools) {
81
+ return this.estimateWithRatio(requestChars(messages, tools), messages.length, this.promptRatioFor());
82
+ }
83
+ /** Same, for a KNOWN endpoint — the compaction gate sizes to the endpoint the request will
84
+ * actually hit, never to a fleet average. */
85
+ estimateRequestFor(key, messages, tools) {
86
+ const c = this.cal.get(key);
87
+ return this.estimateWithRatio(requestChars(messages, tools), messages.length, c?.promptRatio ?? this.pooledPromptRatio());
88
+ }
89
+ /** Conversation-only estimate (CompactionOpts.estimateTokens shape): content + tool_calls
90
+ * JSON over the pooled ratio, plus template overhead. With zero observations this is
91
+ * ceil(chars/4) + 4/message — the legacy heuristic plus the overhead it always missed. */
92
+ estimateMessages(messages) {
93
+ let chars = 0;
94
+ for (const m of messages) {
95
+ chars += m.content.length;
96
+ if (m.tool_calls?.length)
97
+ chars += JSON.stringify(m.tool_calls).length;
98
+ }
99
+ return this.estimateWithRatio(chars, messages.length, this.pooledPromptRatio());
100
+ }
101
+ /** Output-side estimate for the timings-missing fallback in aurora.ts. */
102
+ estimateCompletion(generatedChars) {
103
+ return Math.max(1, Math.ceil(generatedChars / this.pooledCompletionRatio()));
104
+ }
105
+ /** Sample-weighted mean across endpoints — what the size router (which picks the endpoint)
106
+ * and fresh sessions use before any per-endpoint data exists. */
107
+ pooledPromptRatio() {
108
+ let w = 0;
109
+ let sum = 0;
110
+ for (const c of this.cal.values()) {
111
+ if (c.promptSamples > 0) {
112
+ w += c.promptSamples;
113
+ sum += c.promptRatio * c.promptSamples;
114
+ }
115
+ }
116
+ return w > 0 ? sum / w : COLD_CHARS_PER_TOKEN;
117
+ }
118
+ pooledCompletionRatio() {
119
+ let w = 0;
120
+ let sum = 0;
121
+ for (const c of this.cal.values()) {
122
+ if (c.completionSamples > 0) {
123
+ w += c.completionSamples;
124
+ sum += c.completionRatio * c.completionSamples;
125
+ }
126
+ }
127
+ return w > 0 ? sum / w : COLD_CHARS_PER_TOKEN;
128
+ }
129
+ promptSamplesFor(key) {
130
+ return this.cal.get(key)?.promptSamples ?? 0;
131
+ }
132
+ /** Durability: learned ratios survive restarts. A fresh process re-learns in ~10 rounds
133
+ * anyway, but persistence means the FIRST deep session after a restart already sizes
134
+ * correctly. Best-effort — a cache that fails to load is just a cold start. */
135
+ setPersistence(path) {
136
+ this.persistPath = path;
137
+ const fs = nodeFs();
138
+ if (!fs)
139
+ return; // non-node surface (web/JSCore): the meter still works, just learns fresh each boot
140
+ try {
141
+ const raw = fs.readFileSync(path, "utf8");
142
+ const parsed = JSON.parse(raw);
143
+ if (parsed && typeof parsed === "object" && parsed.endpoints && typeof parsed.endpoints === "object") {
144
+ for (const [k, v] of Object.entries(parsed.endpoints)) {
145
+ if (typeof k === "string" && v && typeof v.promptRatio === "number" && typeof v.completionRatio === "number") {
146
+ this.cal.set(k, {
147
+ promptRatio: this.clamp(v.promptRatio),
148
+ promptSamples: Math.max(0, Math.floor(v.promptSamples ?? 0)),
149
+ completionRatio: this.clamp(v.completionRatio),
150
+ completionSamples: Math.max(0, Math.floor(v.completionSamples ?? 0)),
151
+ });
152
+ }
153
+ }
154
+ }
155
+ }
156
+ catch { /* missing/corrupt file → cold start; never block boot on a cache */ }
157
+ }
158
+ flush() {
159
+ if (!this.persistPath)
160
+ return;
161
+ const fs = nodeFs();
162
+ if (!fs)
163
+ return;
164
+ try {
165
+ fs.mkdirSync(parentDir(this.persistPath), { recursive: true });
166
+ const endpoints = {};
167
+ for (const [k, v] of this.cal)
168
+ endpoints[k] = { ...v };
169
+ fs.writeFileSync(this.persistPath, JSON.stringify({ version: 1, endpoints }));
170
+ this.lastSave = Date.now();
171
+ this.obsSinceSave = 0;
172
+ }
173
+ catch { /* best-effort; the in-memory calibration keeps working */ }
174
+ }
175
+ for(key) {
176
+ let c = this.cal.get(key);
177
+ if (!c) {
178
+ c = freshCalibration();
179
+ this.cal.set(key, c);
180
+ }
181
+ return c;
182
+ }
183
+ promptRatioFor() {
184
+ return this.pooledPromptRatio();
185
+ }
186
+ estimateWithRatio(chars, messageCount, ratio) {
187
+ return Math.ceil(chars / ratio) + TEMPLATE_OVERHEAD_PER_MESSAGE * messageCount;
188
+ }
189
+ clamp(ratio) {
190
+ if (!(ratio >= MIN_RATIO && ratio <= MAX_RATIO))
191
+ return COLD_CHARS_PER_TOKEN;
192
+ return ratio;
193
+ }
194
+ afterObserve() {
195
+ this.obsSinceSave += 1;
196
+ if (this.persistPath && (Date.now() - this.lastSave > SAVE_EVERY_MS || this.obsSinceSave >= SAVE_EVERY_OBS)) {
197
+ this.flush();
198
+ }
199
+ }
200
+ }
201
+ /** Process-wide meter. agent.ts, router-adapter.ts, aurora.ts and session.ts share it so an
202
+ * observation from ANY surface (CLI, headless, web) calibrates EVERY surface. */
203
+ export const globalTokenMeter = new TokenMeter();
package/dist/index.js CHANGED
@@ -8,7 +8,8 @@ export { runTurn, TurnAbortedError } from "./engine/agent.js";
8
8
  export { Conversation, buildMessages, assertValidMessages } from "./engine/messages.js";
9
9
  export { streamChat, chat, health } from "./engine/aurora.js";
10
10
  export { recoverToolCalls } from "./engine/toolcalls.js";
11
- export { needsCompaction, compact, summaryPrompt, clampMaxTokens } from "./engine/compaction.js";
11
+ export { needsCompaction, compact, summaryPrompt, clampMaxTokens, usageRatio, pickSummaryContent } from "./engine/compaction.js";
12
+ export { TokenMeter, globalTokenMeter, endpointKey, requestChars, COLD_CHARS_PER_TOKEN } from "./engine/token-meter.js";
12
13
  export { classifyFailure } from "./engine/selfheal.js";
13
14
  export { engineRouter } from "./engine/router-adapter.js";
14
15
  export { AuroraRouter } from "./router/router.js";
package/dist/session.js CHANGED
@@ -4,7 +4,8 @@
4
4
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
5
  import { Conversation } from "./engine/messages.js";
6
6
  import { chat, health } from "./engine/aurora.js";
7
- import { SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, compact, fitToWindow } from "./engine/compaction.js";
7
+ import { SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, compact, fitToWindow, pickSummaryContent } from "./engine/compaction.js";
8
+ import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
8
9
  import { engineRouter } from "./engine/router-adapter.js";
9
10
  import { appendFileSync, mkdirSync } from "node:fs";
10
11
  import { join, dirname } from "node:path";
@@ -221,6 +222,10 @@ export class Session {
221
222
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
222
223
  recalled = false;
223
224
  constructor(cfg = {}) {
225
+ // Calibration durability (SPEC §5, token-meter): learned chars/token persist beside the operator
226
+ // state dir, so the FIRST deep session after a restart already sizes correctly instead of running
227
+ // on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
228
+ globalTokenMeter.setPersistence(join(homedir(), ".axe", "operator", "token-calibration.json"));
224
229
  // Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
225
230
  // handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
226
231
  // are built from the same map, so the tool is advertised iff it's runnable.
@@ -347,10 +352,22 @@ export class Session {
347
352
  health() {
348
353
  return health(this.inner.base);
349
354
  }
350
- /** Estimated context usage of the live conversation against the current endpoint's window, 0-99. */
355
+ /** The calibration key for the endpoint this session's requests ACTUALLY reach (failover/MOA-aware
356
+ * — the same base/model the live turn and the summarizer go to, via onRoute capture). */
357
+ meterKey() {
358
+ return endpointKey(this.lastBase ?? this.inner.base, this.lastModel ?? this.inner.model);
359
+ }
360
+ /** Full-request estimate (system + conversation + tool schemas) at the live endpoint's LEARNED
361
+ * chars/token — the one basis shared by the ctx% bar and the /compact freed math (SPEC §5). */
362
+ requestEstimate() {
363
+ const sys = this.sys();
364
+ const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
365
+ return globalTokenMeter.estimateRequestFor(this.meterKey(), built, this.allSchemas());
366
+ }
367
+ /** Estimated context usage of the live conversation against the current endpoint's window, 0-99.
368
+ * Calibrated: the meter's real ratio once observations land; exactly the old chars/4 prior cold. */
351
369
  ctxPct() {
352
- const chars = JSON.stringify(this.convo.all).length + (this.sys()?.length ?? 0);
353
- return Math.min(99, Math.round((Math.ceil(chars / 4) / this.inner.ctxLimit()) * 100));
370
+ return Math.min(99, Math.round((this.requestEstimate() / this.inner.ctxLimit()) * 100));
354
371
  }
355
372
  /** Cumulative tokens (prefill + output) across every turn this session — the Claude-Code-style running
356
373
  * session total for the status rule, so the real spend is visible (not just the current completion). */
@@ -387,11 +404,13 @@ export class Session {
387
404
  systemPrompt: this.sys(),
388
405
  summarize: this.summarize,
389
406
  minKeepTurns: 2,
407
+ tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
408
+ meter: globalTokenMeter,
409
+ meterKey: this.meterKey(),
390
410
  };
391
- const chars = () => this.convo.all.reduce((n, m) => n + m.content.length, 0);
392
- const before = chars();
411
+ const before = this.requestEstimate();
393
412
  this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
394
- return Math.max(0, Math.ceil((before - chars()) / 4)); // approx tokens freed (chars/4)
413
+ return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
395
414
  }
396
415
  /** Reset the conversation to empty (for /new). */
397
416
  reset() {
@@ -484,7 +503,7 @@ export class Session {
484
503
  // non-empty, so it DEFEATED that guard and could silently destroy the evicted span. A summary is never
485
504
  // re-derivable; a skipped compaction (caller retries, runTurn self-heals the over-budget request) is
486
505
  // strictly safer than nuking real history.
487
- const summary = (r.content?.trim()) || (r.reasoningContent?.trim()) || "";
506
+ const summary = pickSummaryContent(r.content, r.reasoningContent);
488
507
  if (summary)
489
508
  this.persistHandoff(summary, span.length); // durability: compacted work survives on disk
490
509
  return summary;
@@ -0,0 +1,70 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // BusTray — live Switchboard messages surfaced in the Operator TUI as click-to-expand cards. Top-anchored
3
+ // in the fullscreen layout so each card's absolute terminal row is deterministic (topRow + Σ heights above),
4
+ // which is what makes mouse hit-testing reliable without Ink absolute-position measurement. Clicking a card
5
+ // toggles its body (the Phase-1 mouse layer in action). In inline mode (no mouse) the cards still render,
6
+ // just not clickable. Messages are DATA from other agents — shown, never executed.
7
+ import { useEffect, useState } from "react";
8
+ import { Box, Text } from "ink";
9
+ import { useMouse } from "./MouseProvider.js";
10
+ const MAX_BODY_LINES = 8; // cap an expanded card's body so one big message can't dominate the screen
11
+ function wrap(line, width) {
12
+ const w = Math.max(1, width);
13
+ if (line.length <= w)
14
+ return [line];
15
+ const out = [];
16
+ for (let i = 0; i < line.length; i += w)
17
+ out.push(line.slice(i, i + w));
18
+ return out;
19
+ }
20
+ /** Pure layout: assign each message a card with an absolute row (y) and height, given which ids are
21
+ * expanded and the terminal width. Deterministic top-to-bottom stacking from `topRow` — the basis for both
22
+ * render order and click hit-testing. Exported for unit tests. */
23
+ export function trayLayout(messages, expanded, cols, topRow = 1) {
24
+ const width = cols > 0 ? cols : 80;
25
+ const cards = [];
26
+ let y = topRow;
27
+ for (const msg of messages) {
28
+ const isExp = expanded.has(msg.id);
29
+ const bodyLines = isExp
30
+ ? msg.body.split("\n").flatMap((l) => wrap(l, width - 2)).slice(0, MAX_BODY_LINES)
31
+ : [];
32
+ const height = 1 + bodyLines.length;
33
+ cards.push({ msg, y, height, expanded: isExp, bodyLines });
34
+ y += height;
35
+ }
36
+ return cards;
37
+ }
38
+ function preview(body, cols) {
39
+ const one = body.replace(/\s+/g, " ").trim();
40
+ const budget = Math.max(10, (cols > 0 ? cols : 80) - 28);
41
+ return one.length > budget ? one.slice(0, budget - 1) + "…" : one;
42
+ }
43
+ /** The tray. `cols` is the terminal width (for wrapping + region width). Renders nothing when empty. */
44
+ export function BusTray({ messages, cols }) {
45
+ const { registerRegion, enabled } = useMouse();
46
+ const [expanded, setExpanded] = useState(() => new Set());
47
+ const cards = trayLayout(messages, expanded, cols);
48
+ // Register every card's clickable region imperatively (one effect, not a hook-per-card — the message
49
+ // count varies, which would violate rules-of-hooks). A left-press anywhere on a card toggles its body.
50
+ const sig = cards.map((c) => `${c.msg.id}:${c.y}:${c.height}`).join("|");
51
+ useEffect(() => {
52
+ if (!enabled || !cards.length)
53
+ return;
54
+ const disposers = cards.map((c) => registerRegion({ id: `bus:${c.msg.id}`, x: 1, y: c.y, width: Math.max(1, cols), height: c.height }, () => {
55
+ setExpanded((prev) => {
56
+ const next = new Set(prev);
57
+ if (next.has(c.msg.id))
58
+ next.delete(c.msg.id);
59
+ else
60
+ next.add(c.msg.id);
61
+ return next;
62
+ });
63
+ }));
64
+ return () => disposers.forEach((d) => d());
65
+ // eslint-disable-next-line react-hooks/exhaustive-deps
66
+ }, [enabled, registerRegion, cols, sig]);
67
+ if (!messages.length)
68
+ return null;
69
+ return (_jsx(Box, { flexDirection: "column", children: cards.map((c) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "cyan", children: [c.expanded ? "▾" : "▸", " ", "📨 ", c.msg.from, c.msg.subject ? ` [${c.msg.subject}]` : "", c.expanded ? "" : `: ${preview(c.msg.body, cols)}`, enabled && !c.expanded ? _jsx(Text, { dimColor: true, children: " \u00B7 click to expand" }) : null] }), c.expanded ? c.bodyLines.map((l, i) => _jsx(Text, { dimColor: true, children: " " + l }, i)) : null] }, c.msg.id))) }));
70
+ }
@@ -5,6 +5,7 @@ import { Markdown } from "./Markdown.js";
5
5
  import { SummaryCard } from "./SummaryCard.js";
6
6
  import { StatsCard } from "./StatsCard.js";
7
7
  import { ToolBatch } from "./ToolBatch.js";
8
+ import { SB_MARK, SB_IN, SB_OUT } from "./brand.js";
8
9
  import { termCols, termRows } from "./term.js";
9
10
  // In fullscreen we can't use <Static> (it targets the scrollback the alt-screen buffer hides), so render
10
11
  // the last N entries as a plain column the parent region clips to the visible height. N is generous — the
@@ -61,11 +62,40 @@ export function liveTail(s, rows, cols) {
61
62
  return { text: s, clipped: 0 };
62
63
  return { text: lines.slice(start).join("\n"), clipped: start };
63
64
  }
65
+ // A Switchboard bus message rendered inline (SPEC §6, Switchboard surface). Static-rendered like any
66
+ // settled entry, so it's printed once and scrolls with history — anchored to when it arrived/was sent,
67
+ // never a re-painted pinned tray. The mark + direction arrow carry the whole affordance at a glance.
68
+ const BUS_BODY_MAX = 12; // cap the inline body; the full message stays in the bus archive (read/ or sent/)
69
+ function wrapLine(line, width) {
70
+ const w = Math.max(10, width);
71
+ if (line.length <= w)
72
+ return [line];
73
+ const out = [];
74
+ for (let i = 0; i < line.length; i += w)
75
+ out.push(line.slice(i, i + w));
76
+ return out;
77
+ }
78
+ function hhmm(at) {
79
+ const d = new Date(at);
80
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
81
+ }
82
+ function BusCard({ entry }) {
83
+ const { msg, direction, at } = entry;
84
+ const who = direction === "in" ? msg.from : msg.to;
85
+ const arrow = direction === "in" ? SB_IN : SB_OUT;
86
+ const lead = direction === "in" ? "" : "sent · ";
87
+ const all = msg.body.split("\n").flatMap((l) => wrapLine(l, termCols() - 2));
88
+ const shown = all.slice(0, BUS_BODY_MAX);
89
+ const clipped = all.length - shown.length;
90
+ return (_jsxs(Box, { flexDirection: "column", marginBottom: 1, children: [_jsxs(Text, { color: "cyan", children: [SB_MARK, " ", arrow, " ", _jsx(Text, { bold: true, children: who }), msg.subject ? ` [${msg.subject}]` : "", _jsx(Text, { dimColor: true, children: ` ${lead}${hhmm(at)}` })] }), shown.map((l, i) => _jsx(Text, { dimColor: true, children: " " + l }, i)), clipped > 0 ? _jsx(Text, { dimColor: true, children: ` ⋯ +${clipped} more line${clipped === 1 ? "" : "s"}` }) : null] }));
91
+ }
64
92
  function renderEntry(entry, live = false) {
65
93
  if (entry.kind === "summary")
66
94
  return _jsx(SummaryCard, { summary: entry.summary });
67
95
  if (entry.kind === "stats")
68
96
  return _jsx(StatsCard, { stats: entry.stats });
97
+ if (entry.kind === "bus")
98
+ return _jsx(BusCard, { entry: entry });
69
99
  if (entry.kind === "toolBatch")
70
100
  return _jsx(ToolBatch, { steps: entry.steps, durationMs: entry.durationMs });
71
101
  if (entry.kind === "message") {
@@ -0,0 +1,10 @@
1
+ // Switchboard brand mark — the one glyph that stands for the on-box agent bus wherever it appears in the
2
+ // TUI (inline message cards, future unread badge). Chosen to be a single geometric mark that renders on
3
+ // every terminal in our matrix (Apple_Terminal included — no emoji VS16 width ambiguity) and is distinct
4
+ // from Operator's own marks (◆/◈/◉). ⦿ = a patch-jack: a port in a ring, the switchboard's physical
5
+ // primitive (an operator patched cords into jacks to connect two parties). Swap SB_MARK to restyle
6
+ // everywhere — the alternates below each stand for the same idea if a different taste is wanted.
7
+ // ⦿ patch-jack (default) ⇌ bidirectional relay ⊗ cross-connect ❖ node/hub
8
+ export const SB_MARK = "⦿";
9
+ export const SB_IN = "◂"; // inbound: a message arriving toward you
10
+ export const SB_OUT = "▸"; // outbound: a message you sent out
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.162",
3
+ "version": "0.1.164",
4
4
  "description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
5
5
  "type": "module",
6
6
  "bin": {