@0perator/operator 0.1.163 → 0.1.165
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 +55 -0
- package/dist/bus/inbox.js +37 -0
- package/dist/cli.js +15 -9
- package/dist/config/settings.js +27 -7
- package/dist/engine/agent.js +19 -0
- package/dist/engine/aurora.js +5 -3
- package/dist/engine/compaction.js +17 -1
- package/dist/engine/router-adapter.js +5 -1
- package/dist/engine/token-meter.js +203 -0
- package/dist/index.js +2 -1
- package/dist/session.js +51 -15
- package/dist/ui/App.js +6 -9
- package/dist/ui/Transcript.js +30 -0
- package/dist/ui/brand.js +10 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,61 @@ 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.165 — 2026-10-01 — Robustness: deep-context swap-thrash guard + ESC-abort hardening
|
|
8
|
+
- **Swap-thrash guard (track · fix · prevent).** A long session could grow the live context past the box's RAM,
|
|
9
|
+
so model weights + KV cache spilled into swap and decode collapsed to ~0 tok/s (measured 2026-10-01: context
|
|
10
|
+
reached ~191K tokens on a 64GB box → 7.6GB swap → "88 tokens in 6 minutes"). The context *window* is a TOKEN
|
|
11
|
+
limit; the real cliff is a MEMORY limit the %-of-window compaction threshold can't see (it's the same % at any
|
|
12
|
+
RAM). Fix: `compactionCeilingTokens` now, when unset, applies a RAM-aware safe default —
|
|
13
|
+
`defaultCompactionCeiling(totalmem, window)` reserves ~28GB (≈model + OS/overhead) then ~3500 tok/GB of what's
|
|
14
|
+
left, clamped to [8000, 0.85·window] and deliberately BELOW the measured cliff — so proactive compaction fires
|
|
15
|
+
before swap on any box (64GB/300K → ~126K). An explicit `compaction.ceilingTokens` / `KODE_COMPACTION_CEILING_TOKENS`
|
|
16
|
+
still wins. The 0.1.164 token meter makes the trigger exact. `test/settings.test.mts` +8 regression tests lock
|
|
17
|
+
the ceiling below the cliff so this can't silently return.
|
|
18
|
+
- **ESC-abort hardening.** The main streaming abort path was already correct (verified by trace + a 6ms live
|
|
19
|
+
repro — no main-path bug); closed two narrower gaps: the compaction summarizer's `chat()` now carries the
|
|
20
|
+
abort signal (ESC during "compacting" tears it down), and `send()` arms the AbortController *before* first-turn
|
|
21
|
+
`maybeRecall`/MCP-discovery so ESC no longer no-ops in that window (`execute()` reuses the same controller).
|
|
22
|
+
- Full suite: 769 passed, 0 failed (104 files). `tsc --noEmit` clean.
|
|
23
|
+
|
|
24
|
+
## 0.1.164 — 2026-10-01 — Token meter (engine) + Switchboard messages inline in the transcript
|
|
25
|
+
- `src/engine/token-meter.ts` learns each endpoint's REAL chars-per-token online from the exact counts
|
|
26
|
+
the server already reports (`timings.prompt_n`, `usage.completion_tokens`): EMA (converges in ~10
|
|
27
|
+
rounds), per-`base|model` keys (two servers on one model id can tokenize differently), +4 tokens per
|
|
28
|
+
message of chat-template framing the old counter missed entirely, estimates round UP (compact a hair
|
|
29
|
+
early ≪ 400 the request). Sample guards drop zero-token reports, <500-char prompts, and out-of-range
|
|
30
|
+
(1.0–12.0) ratios — the 40-tool-call turn that used to poison the meter can no longer move it. Cold
|
|
31
|
+
start = the legacy 4.0 prior, so no behavior cliff on upgrade. Calibration persists to
|
|
32
|
+
`~/.axe/operator/token-calibration.json` (throttled cache; corrupt/missing degrades to cold, boot is
|
|
33
|
+
never blocked). NO static `node:fs` import — the shared engine graph must stay node-free for the
|
|
34
|
+
`esbuild --platform=neutral` iOS bundle — fs arrives via `process.getBuiltinModule`, degrading to an
|
|
35
|
+
in-memory meter on JSCore/browser.
|
|
36
|
+
- Wired through ONE process-wide `globalTokenMeter` so an observation from any surface calibrates all:
|
|
37
|
+
the compaction gate (`CompactionOpts.meter`/`meterKey` — gate, ceiling, clampMaxTokens and fitToWindow
|
|
38
|
+
all size to the endpoint the request will ACTUALLY hit), the size router (pooled sample-weighted
|
|
39
|
+
ratio in `router-adapter.ts`), the status-rule ctx% and `/compact` freed math (`session.ts` — one char
|
|
40
|
+
basis everywhere, enforced by construction), aurora's missing-timings output fallback (`ChatResult
|
|
41
|
+
.tokensExact` flags server-exact counts so the fallback never re-learns its own prior), and per-round
|
|
42
|
+
observation in `runTurn` (prompt side: `requestChars(built, toolSchemas)`; completion side: exact
|
|
43
|
+
samples only).
|
|
44
|
+
- `pickSummaryContent` (compaction.ts, SPEC §5 failure handling): content wins verbatim, reasoning is
|
|
45
|
+
the fallback, both dry ⇒ `""` so compact() SKIPS rather than persisting a fact-free placeholder over
|
|
46
|
+
real history; a throwing summarizer (500/drop mid-compaction) no longer kills the turn.
|
|
47
|
+
- `docs/token-meter.md` design notes (scope rules, durability, deferred ceiling);
|
|
48
|
+
`test/token-meter.test.mts` 18 tests: EMA math, all guards, endpoint isolation, persistence
|
|
49
|
+
round-trip + corrupt degradation, calibrated gate trip, picker, throw-safety, interrupted-pair validity.
|
|
50
|
+
- **Switchboard messages now render INLINE in the transcript**, superseding the 0.1.163 pinned click-to-expand
|
|
51
|
+
tray. The tray lived outside `<Static>`, so every 3s poll + re-render re-painted it and Ink orphaned the old
|
|
52
|
+
cards into scrollback (the "messages duplicate and never clear" bug). Now each bus message is a `kind:"bus"`
|
|
53
|
+
transcript entry appended at arrival time → `<Static>`-rendered (printed once), anchored to its place in the
|
|
54
|
+
conversation, scrolls with history. `src/ui/BusTray.tsx` removed. `src/ui/brand.ts` adds the Switchboard mark
|
|
55
|
+
`⦿` (a patch-jack; one const, swappable) with a direction arrow (◂ in / ▸ out) + `HH:MM`. `src/bus/inbox.ts`
|
|
56
|
+
gains `pollSent()` reading this session's own `sent/` archive so OUTBOUND traffic ("you sent X to Y") also
|
|
57
|
+
surfaces inline (consume-once via `sent-read/`, same discipline as the inbox). `src/cli.tsx` poller pushes
|
|
58
|
+
both directions; `src/ui/App.tsx` drops the tray + `busMessages` plumbing from both layouts.
|
|
59
|
+
- Full suite: 761 passed, 0 failed (104 files). `tsc --noEmit` clean; iOS `engine.bundle.js` builds under
|
|
60
|
+
`esbuild --platform=neutral` (engine graph remains node-free). Switchboard surface = Claude lane, grandmaster wave.
|
|
61
|
+
|
|
7
62
|
## 0.1.163 — 2026-09-30 — TUI: live Switchboard messages in the terminal (click-to-expand)
|
|
8
63
|
- Incoming Switchboard agent messages (the provider-agnostic on-box bus, memjar/switchboard) now surface
|
|
9
64
|
**live in the Operator terminal** as a click-to-expand tray — the end-to-end proof of the Phase-1 mouse
|
package/dist/bus/inbox.js
CHANGED
|
@@ -21,6 +21,8 @@ export function selfAgent() {
|
|
|
21
21
|
}
|
|
22
22
|
const inboxOf = (agent) => join(busDir(), "agents", encodeURIComponent(agent), "inbox");
|
|
23
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");
|
|
24
26
|
/** Read `agent`'s inbox oldest-first. Unless `peek`, each message is moved to the read/ archive so it
|
|
25
27
|
* surfaces exactly once (delivered-once, matching the CLI). Corrupt or in-flight (.tmp-) files are
|
|
26
28
|
* skipped, never thrown — a bad drop can't wedge polling. Returns [] when the bus/inbox doesn't exist. */
|
|
@@ -56,3 +58,38 @@ export function pollBus(agent = selfAgent(), opts = {}) {
|
|
|
56
58
|
}
|
|
57
59
|
return out;
|
|
58
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,7 +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, selfAgent } from "./bus/inbox.js";
|
|
14
|
+
import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
|
|
15
15
|
import { isErrorResult } from "./ui/format.js";
|
|
16
16
|
import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
|
|
17
17
|
import { Session } from "./session.js";
|
|
@@ -416,7 +416,6 @@ function Root() {
|
|
|
416
416
|
// Gates the exit-time picker below — plan mode toggled on/off with no proposal stays silent.
|
|
417
417
|
const planProposedRef = useRef(false);
|
|
418
418
|
const [planExitPicker, setPlanExitPicker] = useState(null);
|
|
419
|
-
const [busMessages, setBusMessages] = useState([]); // live Switchboard messages for the click-to-expand tray
|
|
420
419
|
const alwaysAllowRef = useRef(new Set());
|
|
421
420
|
// Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
|
|
422
421
|
// knows which address to verify against — the in-session twin of the shell's email-code login.
|
|
@@ -462,7 +461,7 @@ function Root() {
|
|
|
462
461
|
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
463
462
|
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 40) — a real build isn't cut off at 10
|
|
464
463
|
compactionThreshold: compactionThreshold(settings), // settings.compaction.threshold / KODE_COMPACTION_THRESHOLD; undefined → 0.85
|
|
465
|
-
compactionCeilingTokens: compactionCeilingTokens(settings
|
|
464
|
+
compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow), // explicit setting/env wins; else a RAM-aware safe default caps context below the box's swap cliff (the "88 tok/6min" stall)
|
|
466
465
|
temperature: settings.temperature,
|
|
467
466
|
recall: settings.memory.recall,
|
|
468
467
|
models: settings.models, // /model registry overrides (router/models.ts has the built-in defaults)
|
|
@@ -1490,15 +1489,22 @@ function Root() {
|
|
|
1490
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)
|
|
1491
1490
|
return () => clearInterval(id);
|
|
1492
1491
|
}, [status]);
|
|
1493
|
-
// Switchboard poller: pull this session's incoming agent messages every few
|
|
1494
|
-
//
|
|
1495
|
-
//
|
|
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
|
|
1496
1497
|
// Switchboard installed simply shows nothing. MUST be above the boot early-returns (stable hook order).
|
|
1497
1498
|
useEffect(() => {
|
|
1498
1499
|
if (boot !== "ready")
|
|
1499
1500
|
return;
|
|
1500
|
-
const
|
|
1501
|
-
|
|
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
|
+
};
|
|
1502
1508
|
pull();
|
|
1503
1509
|
const id = setInterval(pull, 3000);
|
|
1504
1510
|
return () => clearInterval(id);
|
|
@@ -1522,7 +1528,7 @@ function Root() {
|
|
|
1522
1528
|
? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
|
|
1523
1529
|
: `${spin} ${fmtMeta(elapsed, liveTok)}`
|
|
1524
1530
|
: metrics;
|
|
1525
|
-
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker,
|
|
1531
|
+
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, onApprovalDecide: (allow, always) => {
|
|
1526
1532
|
const cur = approval;
|
|
1527
1533
|
if (cur)
|
|
1528
1534
|
settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
|
package/dist/config/settings.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// default. Never throws — a missing or malformed file just falls back to defaults, same as an env
|
|
4
4
|
// var that was never set.
|
|
5
5
|
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
6
|
-
import { homedir } from "node:os";
|
|
6
|
+
import { homedir, totalmem } from "node:os";
|
|
7
7
|
import { join, dirname } from "node:path";
|
|
8
8
|
import { DEFAULT_MODEL_ID } from "../router/models.js";
|
|
9
9
|
// The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
|
|
@@ -161,14 +161,34 @@ export function compactionThreshold(s) {
|
|
|
161
161
|
const t = s.compaction?.threshold;
|
|
162
162
|
return typeof t === "number" && t >= 0.3 && t <= 0.95 ? t : undefined;
|
|
163
163
|
}
|
|
164
|
+
/** A RAM-aware SAFE default compaction ceiling (pure; exported for tests). The context window is a TOKEN
|
|
165
|
+
* limit, but the real failure is a MEMORY limit: model weights + KV cache must fit in RAM or macOS swaps and
|
|
166
|
+
* decode collapses to ~0 tok/s (measured 2026-10-01 on a 64GB box: context reached ~191K tok → 7.6GB swap →
|
|
167
|
+
* decode 26→2.7→0 tok/s). The %-of-window threshold can't see that cliff (it's the same % regardless of RAM),
|
|
168
|
+
* so we cap effective context by a budget derived from the box's RAM. Reserve ~28GB (≈20GB model + OS/app/KV
|
|
169
|
+
* overhead), then ~3500 tok/GB of what's left — deliberately BELOW the measured cliff (errs toward compacting
|
|
170
|
+
* a little early, which only costs some fidelity that retrieval reclaims; the alternative is the swap stall).
|
|
171
|
+
* Clamped to [8000, 0.85·window], so on a small window it never fires before the threshold path would. */
|
|
172
|
+
export function defaultCompactionCeiling(totalBytes, windowTokens) {
|
|
173
|
+
const totalGB = totalBytes / 2 ** 30;
|
|
174
|
+
const budgetGB = Math.max(0, totalGB - 28);
|
|
175
|
+
const raw = Math.floor(budgetGB * 3500);
|
|
176
|
+
const cap = Math.floor((windowTokens > 0 ? windowTokens : 0) * 0.85);
|
|
177
|
+
return Math.max(8000, Math.min(raw, cap));
|
|
178
|
+
}
|
|
164
179
|
/** The absolute-token proactive-compaction ceiling to hand runTurn: settings.compaction.ceilingTokens
|
|
165
|
-
* (env-overridden in loadSettings)
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
|
|
180
|
+
* (env-overridden in loadSettings), validated to a sane floor of 8000 tokens. When UNSET, we no longer leave
|
|
181
|
+
* it uncapped — we apply a RAM-aware safe default (defaultCompactionCeiling) so a large window can't grow the
|
|
182
|
+
* KV cache past the box's memory into swap (the "88 tokens in 6 minutes" stall). An explicit valid setting
|
|
183
|
+
* always wins. `windowTokens` is the active endpoint's context window; pass 0 if unknown (then only the floor
|
|
184
|
+
* applies). Resolved here so CLI, headless, and ACP surfaces read it identically. */
|
|
185
|
+
export function compactionCeilingTokens(s, windowTokens = 0) {
|
|
170
186
|
const t = s.compaction?.ceilingTokens;
|
|
171
|
-
|
|
187
|
+
if (typeof t === "number" && Number.isFinite(t) && t >= 8000)
|
|
188
|
+
return Math.floor(t);
|
|
189
|
+
if (windowTokens >= 8000)
|
|
190
|
+
return defaultCompactionCeiling(totalmem(), windowTokens);
|
|
191
|
+
return undefined;
|
|
172
192
|
}
|
|
173
193
|
/** Whether to auto-start a Remote Control host on session boot. An explicit setting/env wins
|
|
174
194
|
* (settings.remote.autostart / KODE_RC_AUTOSTART=1/0). Otherwise it is FEATURE-FLAGGED to the admin/VIP
|
package/dist/engine/agent.js
CHANGED
|
@@ -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
|
}
|
package/dist/engine/aurora.js
CHANGED
|
@@ -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
|
|
394
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
-
|
|
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
|
|
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,
|
|
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() {
|
|
@@ -478,13 +497,17 @@ export class Session {
|
|
|
478
497
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
479
498
|
temperature: 0,
|
|
480
499
|
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
500
|
+
signal: this.ctrl?.signal, // ESC during "compacting" must tear down THIS request too, not just the main
|
|
501
|
+
// generation stream — without it a compaction summarize (which can be a large request on a slow/deep
|
|
502
|
+
// endpoint) runs to completion after the user already hit esc. Null ctrl (background pass outside a turn)
|
|
503
|
+
// → undefined → no abort, which is correct.
|
|
481
504
|
});
|
|
482
505
|
// Return "" on a genuinely empty response so compact()'s empty-summary guard fires and PRESERVES history
|
|
483
506
|
// rather than replacing it with a useless placeholder — the old "(summary unavailable)" sentinel was
|
|
484
507
|
// non-empty, so it DEFEATED that guard and could silently destroy the evicted span. A summary is never
|
|
485
508
|
// re-derivable; a skipped compaction (caller retries, runTurn self-heals the over-budget request) is
|
|
486
509
|
// strictly safer than nuking real history.
|
|
487
|
-
const summary = (r.content
|
|
510
|
+
const summary = pickSummaryContent(r.content, r.reasoningContent);
|
|
488
511
|
if (summary)
|
|
489
512
|
this.persistHandoff(summary, span.length); // durability: compacted work survives on disk
|
|
490
513
|
return summary;
|
|
@@ -581,12 +604,23 @@ export class Session {
|
|
|
581
604
|
async send(text, h = {}) {
|
|
582
605
|
if (this.ctrl)
|
|
583
606
|
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
607
|
+
// Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
|
|
608
|
+
// called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
|
|
609
|
+
// would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
|
|
610
|
+
this.ctrl = new AbortController();
|
|
611
|
+
try {
|
|
612
|
+
await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
|
|
613
|
+
if (this.ctrl.signal.aborted)
|
|
614
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
615
|
+
this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
|
|
616
|
+
const active = findModel(this.registry, this.modelId);
|
|
617
|
+
if (active?.kind === "orchestrated")
|
|
618
|
+
return await this.sendMoa(text, h, active);
|
|
619
|
+
return await this.execute(text, h, this.router, this.sysWithThink());
|
|
620
|
+
}
|
|
621
|
+
finally {
|
|
622
|
+
this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
|
|
623
|
+
}
|
|
590
624
|
}
|
|
591
625
|
/** MOA turn (MOA-DESIGN.md): fan out to settings.moa's proposers in parallel, then run the
|
|
592
626
|
* aggregator through the SAME runTurn loop as a normal turn (execute) — pointed at the
|
|
@@ -626,7 +660,9 @@ export class Session {
|
|
|
626
660
|
async execute(text, h, router, sys, routeLabel) {
|
|
627
661
|
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
628
662
|
this.lastSys = sys; // remember the EXACT system prompt this turn sends, so cache-safe compaction reuses it verbatim
|
|
629
|
-
|
|
663
|
+
// Reuse the controller send() already armed (so esc during maybeRecall / MOA fan-out is live); create one
|
|
664
|
+
// only if execute() is somehow entered without send() arming it (defensive — every caller goes via send).
|
|
665
|
+
const controller = this.ctrl ?? new AbortController();
|
|
630
666
|
this.ctrl = controller;
|
|
631
667
|
const _t0 = performance.now();
|
|
632
668
|
try {
|
package/dist/ui/App.js
CHANGED
|
@@ -4,10 +4,9 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
4
4
|
// src/engine, src/tools, or src/router.
|
|
5
5
|
import { useEffect, useState } from "react";
|
|
6
6
|
import { Box, Text } from "ink";
|
|
7
|
-
import { termRows
|
|
7
|
+
import { termRows } from "./term.js";
|
|
8
8
|
import { caps } from "./capabilities.js";
|
|
9
9
|
import { MouseProvider, useOnWheel } from "./MouseProvider.js";
|
|
10
|
-
import { BusTray } from "./BusTray.js";
|
|
11
10
|
import { StatusRule } from "./StatusRule.js";
|
|
12
11
|
import { InputRule } from "./InputRule.js";
|
|
13
12
|
import { Transcript } from "./Transcript.js";
|
|
@@ -25,7 +24,7 @@ import { QuestionPrompt } from "./QuestionPrompt.js";
|
|
|
25
24
|
// calls at once; anything past the cap is summarized as a count instead of another row.
|
|
26
25
|
const MAX_LIVE_TOOL_ROWS = 6;
|
|
27
26
|
export function App(props) {
|
|
28
|
-
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null
|
|
27
|
+
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null } = props;
|
|
29
28
|
const thinking = status === "thinking" || status === "streaming";
|
|
30
29
|
// A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
|
|
31
30
|
// a lone call isn't worth a bordered block, the braille spinner + name already says enough.
|
|
@@ -47,11 +46,11 @@ export function App(props) {
|
|
|
47
46
|
// Enable the SGR mouse layer ONLY in fullscreen on a mouse-capable TTY — inline keeps the terminal's
|
|
48
47
|
// native scroll+copy, so it must never receive tracking. FullscreenBody (under the provider) turns
|
|
49
48
|
// wheel events into scrollback over the alt-screen transcript, which otherwise has no way to scroll.
|
|
50
|
-
return (_jsx(MouseProvider, { enabled: caps().mouse, children: _jsx(FullscreenBody, { messages: messages, live: live, activity: activity, prompts: prompts, bottom: bottom
|
|
49
|
+
return (_jsx(MouseProvider, { enabled: caps().mouse, children: _jsx(FullscreenBody, { messages: messages, live: live, activity: activity, prompts: prompts, bottom: bottom }) }));
|
|
51
50
|
}
|
|
52
51
|
// Inline (default): the dynamic frame grows below the Static transcript; unused space sits below it and
|
|
53
52
|
// fills as the conversation grows. Native scrollback preserved.
|
|
54
|
-
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(
|
|
53
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), activity, prompts, bottom] }));
|
|
55
54
|
}
|
|
56
55
|
// Entries the transcript window slides per wheel notch. A notch is one detent of the physical wheel; 3
|
|
57
56
|
// entries keeps scrollback brisk without leaping past short exchanges.
|
|
@@ -61,7 +60,7 @@ const WHEEL_STEP = 3;
|
|
|
61
60
|
// entries the bottom-anchored clip would otherwise hide), wheel-down returns toward the live bottom, and
|
|
62
61
|
// any new output snaps straight back to it — you never get stranded in history while the answer grows.
|
|
63
62
|
// Split out from App because useOnWheel must run inside the provider App itself returns.
|
|
64
|
-
function FullscreenBody({ messages, live, activity, prompts, bottom
|
|
63
|
+
function FullscreenBody({ messages, live, activity, prompts, bottom }) {
|
|
65
64
|
const rows = termRows();
|
|
66
65
|
const [scrollBack, setScrollBack] = useState(0);
|
|
67
66
|
// New settled output resets the view to the live bottom (messages.length only grows as entries settle).
|
|
@@ -71,7 +70,5 @@ function FullscreenBody({ messages, live, activity, prompts, bottom, busMessages
|
|
|
71
70
|
? Math.min(s + WHEEL_STEP, Math.max(0, messages.length - 1)) // clamp: the oldest entry stays reachable
|
|
72
71
|
: Math.max(0, s - WHEEL_STEP));
|
|
73
72
|
});
|
|
74
|
-
|
|
75
|
-
// (trayLayout topRow=1), which is what makes click hit-testing reliable. It renders nothing when empty.
|
|
76
|
-
return (_jsxs(Box, { flexDirection: "column", height: rows, children: [_jsx(BusTray, { messages: busMessages, cols: termCols() }), _jsxs(Box, { flexGrow: 1, flexDirection: "column", overflow: "hidden", justifyContent: "flex-end", children: [_jsx(Transcript, { entries: messages, live: live, bounded: true, scrollBack: scrollBack }), activity] }), prompts, bottom] }));
|
|
73
|
+
return (_jsxs(Box, { flexDirection: "column", height: rows, children: [_jsxs(Box, { flexGrow: 1, flexDirection: "column", overflow: "hidden", justifyContent: "flex-end", children: [_jsx(Transcript, { entries: messages, live: live, bounded: true, scrollBack: scrollBack }), activity] }), prompts, bottom] }));
|
|
77
74
|
}
|
package/dist/ui/Transcript.js
CHANGED
|
@@ -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") {
|
package/dist/ui/brand.js
ADDED
|
@@ -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.
|
|
3
|
+
"version": "0.1.165",
|
|
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": {
|