@0perator/operator 0.1.44 → 0.1.46

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 ADDED
@@ -0,0 +1,104 @@
1
+ # Operator (kode-tsi) — Changelog
2
+
3
+ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on the local Aurora model.
4
+ Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
5
+ npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
6
+
7
+ ## 0.1.46 — 2026-09-21
8
+ - Added: `scratchpad` tool — a private per-session notes file OUTSIDE the workspace (read with no args;
9
+ append, or mode:"overwrite"), so the model can think/track progress without cluttering the repo.
10
+ - Added: `session_handoff` tool — write a note for your FUTURE self in this directory (what you did, state,
11
+ next steps); it is auto-loaded into the system prompt at the start of the next session here, so Operator
12
+ resumes seamlessly. Files live under ~/.axe/operator/{scratch,handoff}.
13
+ - Tests: +4 scratchpad/handoff (append/read/overwrite, save/read-back, fail-safe). Suite 277/277.
14
+
15
+ ## 0.1.45 — 2026-09-21
16
+ - Fixed: chauffeur computer-use looped ("session has ended", stale window ids, fell back to hand-written
17
+ osascript). Root cause: the MCP client discarded each tool result's `structuredContent`, where chauffeur
18
+ returns the real data (window list with ids, accessibility tree) while the text is only a summary
19
+ ("Found 76 windows."). `flattenResult` now includes structuredContent. Verified live end-to-end.
20
+ - Added: chauffeur session-lifecycle tools (start_session/get_session/list_sessions) so the model recovers
21
+ instead of looping; rewrote embodiment guidance (no `session` arg, fresh window_id per read, never
22
+ osascript a GUI).
23
+ - Added: honest token/prefill telemetry — live line shows "reading your prompt..." during prefill (not a
24
+ frozen "0 tokens"); settled metric shows output tok @ decode tok/s + prefill size; a cumulative session
25
+ token total (ΣNk) on the status rule.
26
+ - Tests: +5 MCP (flattenResult surfaces structuredContent). Suite 273/273.
27
+
28
+ ## 0.1.44 — 2026-09-21
29
+ - Fixed: tool-step lines truncated the whole args blob, hiding the file path behind `content`. Now
30
+ identifying args (path/command/url/...) show first and in full; bulky payloads (content/text) show as a
31
+ size. file_write/edit/read/shell_exec always show the exact file + path.
32
+ - Tests: +5 tool-step. Suite 268/268.
33
+
34
+ ## 0.1.43 — 2026-09-21
35
+ - Fixed: the render "everything scrolls to the top" collapse. The streaming answer rendered in Ink's
36
+ dynamic (non-Static) frame; once taller than the window Ink cleared to the top and scrolled the
37
+ transcript away at the live->settle transition. `Transcript.liveTail` bounds the live view to a small
38
+ wrap-counted tail; the full answer still renders via <Static>. Reproduced + verified with a pty+pyte
39
+ harness at 315x65.
40
+ - Tests: +4 transcript (height bound). Suite 263/263.
41
+
42
+ ## 0.1.42 — 2026-09-21
43
+ - Added: ask_user always offers a final free-text "Chat about it - type your own reply" option beyond the
44
+ model's choices; typed text returns to the model verbatim. Keystroke logic is a pure, tested reducer.
45
+ - Changed: computer tasks run end-to-end from one instruction - chauffeur READS run unprompted, only
46
+ ACTIONS ask; system prompt tells the model to read/decide/act itself, not walk the owner through steps.
47
+ - Tests: +7 ask_user reducer. Suite 259/259.
48
+
49
+ ## 0.1.41 — 2026-09-21
50
+ - Added: chauffeur computer-use driver wired into embodiment as a curated 19-tool MCP hub (scoped, not the
51
+ whole fleet), plus a general `tools` allowlist on MCP server config. System prompt steers Aurora to read
52
+ UIs via chauffeur's textual accessibility tree instead of hand-rolling osascript. Enable with
53
+ KODE_COMPUTER=1. Suite 252/252.
54
+
55
+ ## 0.1.40 — 2026-09-21
56
+ - Fixed: status-rule wrap-creep — the rule mixed box-drawing with dingbat glyphs and could render at
57
+ exactly the terminal width, wrapping and creeping the frame. Now measured with a conservative cellWidth
58
+ and truncated so it is always cols-1.
59
+ - Fixed: file tools ignored a leading `~` (file_write "~/Downloads/x.md" wrote to a literal "~" folder and
60
+ claimed success). A shared expandPath now runs before the sandbox check on every path tool.
61
+ - Tests: +43 status-rule width, +2 path. Suite 252/252.
62
+
63
+ ## 0.1.39 — refactor: dedup the exec helper; close a destructive-rm signature-line gap.
64
+ ## 0.1.38 — /remotecontrol prints a shareable 0perator.co follower link.
65
+ ## 0.1.37 — /think and /ultrathink extended-reasoning modes.
66
+ ## 0.1.36 — ask_user interactive clarification tool.
67
+ ## 0.1.35 — @file mentions: inline a file by typing @path.
68
+ ## 0.1.34 — Plan Mode: read-only research + propose, then approve to execute.
69
+ ## 0.1.33 — grep_search survives special files (sockets/FIFOs); AXE identity.
70
+ ## 0.1.32 — warm a cold-started Aurora so the first turn is fast.
71
+ ## 0.1.31 — swarm dashboard live-tails events.jsonl; /dashboard command.
72
+ ## 0.1.30 — control-plane visibility: permission tier seat badge + /audit.
73
+ ## 0.1.29 — human-signature lines: money/prod/destructive always require a human.
74
+ ## 0.1.28 — control plane: tool tiering (admin/enterprise/readonly) + frozen OperatorEvent stream.
75
+ ## 0.1.27 — service lever: ensure Aurora/autopilot are up on start; /services.
76
+ ## 0.1.26 — /remotecontrol host + WebSocket relay broker (remote-drive a session), live E2E.
77
+ ## 0.1.25 — pin SearXNG to independent non-Microsoft engines by default.
78
+ ## 0.1.24 — publish the web_search fixes (SearXNG lifecycle + default engine).
79
+ ## 0.1.23 — Operator auto-manages a local SearXNG container; autopilot fallback.
80
+ ## 0.1.22 — web_search backend is a first-class setting.
81
+ ## 0.1.21 — Gradient Constellation masthead as the boot banner.
82
+ ## 0.1.20 — fix CI-red sandbox symlink tests (component-wise readlink resolution).
83
+ ## 0.1.19 — enterprise header polish (✷ mark + bright wordmark + info), reflow-safe.
84
+ ## 0.1.18 — fix input area creeping to the top on keystroke (exact-width status-rule wrap).
85
+ ## 0.1.17 — fix empty-turn recovery 400 (no second system message), caught by a live test.
86
+ ## 0.1.16 — background/detached shell + task-management tools.
87
+ ## 0.1.15 — grandmaster sub-agents: 4 engine mechanisms.
88
+ ## 0.1.14 — fix launch crash (Rules of Hooks) + turn metrics readout.
89
+ ## 0.1.13 — web_search backed by AXE autopilot (drop DDG/Playwright scrape).
90
+ ## 0.1.12 — web_search tool + auto-load project context (AGENTS.md/CLAUDE.md).
91
+ ## 0.1.11 — finish_reason handling + fix the empty-turn user-directive leak.
92
+ ## 0.1.10 — render markdown in the transcript (was showing raw ** / backticks).
93
+ ## 0.1.9 — sandbox read-containment for credentials (security P1).
94
+ ## 0.1.8 — close the sandbox symlink-write bypass (security P1).
95
+ ## 0.1.7 — stream the model's thinking, dimmed above the answer.
96
+ ## 0.1.6 — computer control (macOS embodiment) with per-action approval.
97
+ ## 0.1.5 — smooth email-code sign-in as the default `operator auth login`.
98
+ ## 0.1.4 — input bounded between two rules (status rule above, plain rule below).
99
+ ## 0.1.3 — live turn timer: token count, tok/s, and elapsed all tick during a turn.
100
+ ## 0.1.2 — minimal masthead: drop divider rules, status text in the corner.
101
+ ## 0.1.1 — device-login opens the browser with the code embedded (one-click connect).
102
+ ## 0.1.0 — reliable local-file search + clearer `operator update`.
103
+ ## 0.0.3–0.0.9 — Operator persona default; 1M-context awareness; status-rule metrics; media-attachment
104
+ chips; context self-poisoning fix (session file out of cwd + grep line cap); platform:neutral bundle fix.
package/dist/cli.js CHANGED
@@ -16,10 +16,12 @@ import { loadSettings } from "./config/settings.js";
16
16
  import { EventSink } from "./telemetry/events.js";
17
17
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
18
18
  import { expandFileMentions } from "./util/mentions.js";
19
- import { join } from "node:path";
19
+ import { join, dirname } from "node:path";
20
20
  import { homedir, hostname } from "node:os";
21
21
  import { createHash } from "node:crypto";
22
- const VERSION = "0.1.44";
22
+ // RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
23
+ // (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
24
+ const VERSION = "0.1.46";
23
25
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
24
26
  const settings = loadSettings();
25
27
  // Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
@@ -101,6 +103,17 @@ const RESUME = process.argv.includes("--resume") || process.argv.includes("-r")
101
103
  // The sink always exists so the audit trail works even with telemetry off; turn/service events are gated
102
104
  // on telemetry.enabled so the metrics stream honors the off switch.
103
105
  const SESSION_ID = createHash("sha1").update(`${process.cwd()}:${Date.now()}`).digest("hex").slice(0, 12);
106
+ // Scratchpad (per session) + handoff (per working directory). Projected to env for the scratchpad /
107
+ // session_handoff tools; the handoff is auto-loaded into the system prompt below so the next session in
108
+ // this directory resumes from it. Kept under ~/.axe/operator, never in the workspace.
109
+ const WORKSPACE_HASH = createHash("sha1").update(process.cwd()).digest("hex").slice(0, 16);
110
+ process.env.KODE_SCRATCH_FILE = join(homedir(), ".axe", "operator", "scratch", `${SESSION_ID}.md`);
111
+ process.env.KODE_HANDOFF_FILE = join(homedir(), ".axe", "operator", "handoff", `${WORKSPACE_HASH}.md`);
112
+ try {
113
+ mkdirSync(dirname(process.env.KODE_SCRATCH_FILE), { recursive: true });
114
+ mkdirSync(dirname(process.env.KODE_HANDOFF_FILE), { recursive: true });
115
+ }
116
+ catch { /* best-effort; the tools guard too */ }
104
117
  const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: "cli" };
105
118
  const eventSink = new EventSink();
106
119
  const emitTelemetry = settings.telemetry.enabled !== false;
@@ -132,6 +145,18 @@ function loadProjectContext() {
132
145
  }
133
146
  return "";
134
147
  }
148
+ // Session handoff: the note the previous session in THIS directory wrote for its future self (via the
149
+ // session_handoff tool). Auto-loaded here so the agent resumes seamlessly. Capped so a runaway handoff
150
+ // can't dominate the prompt.
151
+ function loadHandoff() {
152
+ try {
153
+ const t = readFileSync(process.env.KODE_HANDOFF_FILE ?? "", "utf8").trim();
154
+ if (t)
155
+ return `\n\n## Handoff from your previous session here (you wrote this for yourself)\n${t.slice(0, 6000)}\n\nContinue from where it leaves off, and update it with session_handoff before you finish.`;
156
+ }
157
+ catch { /* none yet */ }
158
+ return "";
159
+ }
135
160
  // Embodiment guidance, appended only when computer control is on. It steers Aurora to READ the screen
136
161
  // with chauffeur's textual accessibility tree instead of hand-rolling osascript — the exact loop that
137
162
  // failed on Slack (AppleScript can't read Electron UIs). chauffeur is reachable either via the scoped
@@ -141,16 +166,22 @@ const EMBODIMENT_GUIDE = settings.computer.enabled
141
166
  ? `\n## Controlling this computer\nComputer control is ON (every action asks the owner first). Drive apps with ` +
142
167
  `computer_app_open / computer_app_activate, computer_type, computer_key, computer_click, computer_screenshot.` +
143
168
  (chauffeurReady
144
- ? ` To SEE the screen, use chauffeur: call chauffeur:list_windows to enumerate windows (each with pid + ` +
145
- `window_id + title), then chauffeur:get_window_state {pid, window_id} to read a window's UI as a TEXT ` +
146
- `accessibility tree — labels, values, and clickable elements with coordinates. Act via chauffeur:click / ` +
147
- `chauffeur:type_text / chauffeur:press_key using that element info. Do NOT hand-write osascript or System ` +
148
- `Events to scrape a GUI: AppleScript cannot reliably read Electron apps (Slack, VS Code, Discord) and will ` +
149
- `error — always read them with chauffeur:get_window_state instead. Work the task END-TO-END from the ` +
150
- `owner's one natural-language instruction: read the screen, decide, and act by chaining these tools ` +
151
- `yourself, then report the result — do NOT narrate or stop to make the owner walk through each step. ` +
152
- `Reads (list_windows/get_window_state) run without a prompt; only actions ask for approval. Use ask_user ` +
153
- `ONLY for a genuine decision that is the owner's to make — never to step through a task you can just do.`
169
+ ? ` To SEE the screen use the chauffeur tools — NEVER shell_exec/osascript/System Events to read or drive ` +
170
+ `a GUI (AppleScript cannot read Electron apps like Slack/VS Code/Discord and just errors). Correct usage, ` +
171
+ `follow it exactly:\n` +
172
+ `- Do NOT pass a "session" argument to any chauffeur tool. Omit it — the implicit session is used ` +
173
+ `automatically. (Inventing a session label causes "session has ended" errors.)\n` +
174
+ `- To read a window: call chauffeur:list_windows, take a window_id + pid FROM THAT RESULT, then ` +
175
+ `immediately chauffeur:get_window_state {pid, window_id} → a TEXT accessibility tree (roles, labels, ` +
176
+ `values, clickable elements + coordinates). window_ids go stale, so always list_windows again right ` +
177
+ `before get_window_state; never reuse an old id.\n` +
178
+ `- To act: chauffeur:click / chauffeur:type_text / chauffeur:press_key, addressing elements by the info ` +
179
+ `from the latest get_window_state.\n` +
180
+ `- If ANY chauffeur tool returns "session has ended", call chauffeur:start_session ONCE (no arguments), ` +
181
+ `then retry the read — do not loop the failing call.\n` +
182
+ `Work END-TO-END from the owner's one instruction: read → decide → act by chaining these tools yourself, ` +
183
+ `then report the result. Reads run without a prompt; only actions ask. Use ask_user only for a genuine ` +
184
+ `owner decision — never to walk through a task you can just do.`
154
185
  : ` NOTE: reliably READING on-screen UI (especially Electron apps like Slack) needs the chauffeur driver, ` +
155
186
  `which is not installed here; computer_screenshot only saves a PNG you cannot read back yet. Do not ` +
156
187
  `hand-write osascript to scrape a GUI — it will error on Electron apps.`)
@@ -176,8 +207,12 @@ const SYSTEM_PROMPT = (settings.systemPrompt ??
176
207
  `never killed mid-search — shell_exec {"command":"find ~ -maxdepth 4 -iname \\"*name*\\" 2>/dev/null | ` +
177
208
  `head -80","timeout_ms":60000}. Do NOT use an unbounded find / (too slow, it times out). Also check ` +
178
209
  `~/.axe/repos and any folder ls ~ revealed, and widen the pattern (a repo may be named slightly ` +
179
- `differently). Only report not-found after this real search, and say exactly where you looked.`) +
180
- loadProjectContext() + EMBODIMENT_GUIDE;
210
+ `differently). Only report not-found after this real search, and say exactly where you looked.` +
211
+ `\n## Scratchpad & handoff\nUse the scratchpad tool for private working notes, plans, and intermediate ` +
212
+ `results — think there, not in the workspace or your reply. Before you finish a substantial task, or ` +
213
+ `when you're running low on context, call session_handoff to record what you did, the state, and the ` +
214
+ `next steps: your next session in this directory loads it automatically, so write it for your future self.`) +
215
+ loadProjectContext() + loadHandoff() + EMBODIMENT_GUIDE;
181
216
  const MAX_BG = 4; // concurrent background sub-agents — all share the single Aurora 1M endpoint, so cap fan-out
182
217
  const HELP = [
183
218
  "commands:",
@@ -480,12 +515,19 @@ function Root() {
480
515
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: outcome.content, reasoning } });
481
516
  remoteRef.current?.finalAssistant(outcome.content, reasoning);
482
517
  }
483
- // Surface the turn's real generation metrics in the status rule: tokens · gen tok/s · wall time.
484
- if (!outcome.interrupted && (outcome.tokens || outcome.durationMs)) {
518
+ // Surface the turn's real metrics: wall time · output tokens @ decode tok/s · prefill size. The
519
+ // prefill number is the key one on a local model — it's where "0 tokens for N seconds" goes (the
520
+ // model reading the prompt), otherwise invisible.
521
+ if (!outcome.interrupted && (outcome.tokens || outcome.durationMs || outcome.promptTokens)) {
485
522
  const tok = outcome.tokens ?? 0;
486
523
  const durationMs = outcome.durationMs ?? 0;
487
524
  const secs = durationMs / 1000;
488
- setMetrics(fmtMeta(secs, tok));
525
+ const tps = outcome.genMs && outcome.genMs > 0 ? Math.round(tok / (outcome.genMs / 1000)) : 0;
526
+ const prefill = outcome.promptTokens ?? 0;
527
+ const parts = [fmtDuration(secs), `${fmtTokens(tok).replace(/ tokens?$/, " tok")}${tps ? ` @ ${tps} tok/s` : ""}`];
528
+ if (prefill)
529
+ parts.push(`${fmtTokens(prefill).replace(/ tokens?$/, "")} prefill`);
530
+ setMetrics(`(${parts.join(" · ")})`);
489
531
  // Feed the same numbers to the frozen event stream (dashboard + mobile). Gated on telemetry.enabled.
490
532
  if (emitTelemetry) {
491
533
  eventSink.emit({ kind: "turn", session: SESSION_ID, actor: EVENT_ACTOR,
@@ -802,10 +844,16 @@ function Root() {
802
844
  // turn's numbers mid-turn — the clock always moves.
803
845
  const SPIN = "⣾⣽⣻⢿⡿⣟⣯⣷";
804
846
  const active = status === "streaming" || status === "thinking" || status === "executing" || status === "recovering";
847
+ const spin = SPIN[Math.floor(elapsed * 4) % SPIN.length];
848
+ // Before the first token streams, the model is PREFILLING (reading the prompt) — that's the "0 tokens
849
+ // for N seconds" the user sees. Label it honestly instead of showing a frozen "0 tokens", so a slow
850
+ // local prefill reads as work in progress, not a hang. Once tokens flow, show the live count + elapsed.
805
851
  const liveMetrics = active
806
- ? `${SPIN[Math.floor(elapsed * 4) % SPIN.length]} ${fmtMeta(elapsed, liveTok)}`
852
+ ? liveTok === 0
853
+ ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
854
+ : `${spin} ${fmtMeta(elapsed, liveTok)}`
807
855
  : metrics;
808
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, onApprovalDecide: (allow, always) => {
856
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, onApprovalDecide: (allow, always) => {
809
857
  const cur = approval;
810
858
  if (cur)
811
859
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
@@ -112,6 +112,8 @@ export async function runTurn(userInput, conversation, opts) {
112
112
  let toolCallTotal = 0;
113
113
  let tokensTotal = 0; // output tokens summed across rounds (from llama.cpp timings)
114
114
  let genMsTotal = 0; // server-side generation ms summed across rounds
115
+ let promptTokensTotal = 0; // prompt tokens PREFILLED, summed across rounds
116
+ let promptMsTotal = 0; // prefill ms summed across rounds
115
117
  let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
116
118
  for (; rounds < hardCap; rounds++) {
117
119
  throwIfAborted(opts.signal); // stop before spending another round (covers compaction below too)
@@ -152,6 +154,8 @@ export async function runTurn(userInput, conversation, opts) {
152
154
  });
153
155
  tokensTotal += response.tokens ?? 0;
154
156
  genMsTotal += response.genMs ?? 0; // accumulate real gen metrics across rounds
157
+ promptTokensTotal += response.promptTokens ?? 0;
158
+ promptMsTotal += response.promptMs ?? 0; // and prefill (the invisible wall-time cost)
155
159
  break;
156
160
  }
157
161
  catch (err) {
@@ -243,9 +247,9 @@ export async function runTurn(userInput, conversation, opts) {
243
247
  ? "(hit the output limit before an answer landed — ask me to continue and I'll pick up where I left off.)"
244
248
  : "(the model returned an empty response — try rephrasing.)");
245
249
  conversation.assistant(answer);
246
- return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal };
250
+ return { content: answer, rounds: rounds + 1, toolCalls: toolCallTotal, stopReason: response.stopReason, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
247
251
  }
248
252
  const timeoutMsg = `[stopped after ${hardCap} tool rounds — the task may be unfinished; ask me to continue and I'll pick up where I left off]`;
249
253
  conversation.assistant(timeoutMsg);
250
- return { content: timeoutMsg, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal };
254
+ return { content: timeoutMsg, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
251
255
  }
@@ -111,7 +111,7 @@ async function* streamDeltas(messages, o) {
111
111
  const j = JSON.parse(d);
112
112
  // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
113
113
  if (j.timings || j.usage)
114
- o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms });
114
+ o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms, promptTokens: j.timings?.prompt_n ?? j.usage?.prompt_tokens, promptMs: j.timings?.prompt_ms });
115
115
  const choice = j.choices?.[0];
116
116
  // finish_reason is a sibling of delta (often on a final chunk whose delta is {} or absent).
117
117
  // Attach it to the yielded delta, and still yield a bare {finish_reason} when there's no delta,
@@ -163,7 +163,9 @@ export async function chat(messages, o) {
163
163
  const meta = {};
164
164
  const oo = { ...o, onMeta: (m) => { if (m.tokens != null)
165
165
  meta.tokens = m.tokens; if (m.genMs != null)
166
- meta.genMs = m.genMs; o.onMeta?.(m); } };
166
+ meta.genMs = m.genMs; if (m.promptTokens != null)
167
+ meta.promptTokens = m.promptTokens; if (m.promptMs != null)
168
+ meta.promptMs = m.promptMs; o.onMeta?.(m); } };
167
169
  for await (const delta of streamDeltas(messages, oo)) {
168
170
  if (delta.content) {
169
171
  content += delta.content;
@@ -216,7 +218,7 @@ export async function chat(messages, o) {
216
218
  // "length" isn't a truncated ANSWER, so only flag length/content_filter when NO tool calls were made.
217
219
  const apiStop = finishReason === "length" ? "length" : finishReason === "content_filter" ? "content_filter" : undefined;
218
220
  const stopReason = degenerate ? "repetition" : (acc.size === 0 ? apiStop : undefined);
219
- return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens: meta.tokens, genMs: meta.genMs };
221
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens: meta.tokens, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
220
222
  }
221
223
  /** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
222
224
  export async function health(base) {
@@ -1,11 +1,22 @@
1
- /** Flatten an MCP tools/call result's content array to a single string (shared by both transports). */
1
+ /** Flatten an MCP tools/call result to a single string (shared by both transports). Includes the machine-
2
+ * readable `structuredContent` when present: for many tools the text content is only a human summary
3
+ * ("Found 76 windows.") and the data the model must act on (ids, elements, coordinates) lives in
4
+ * structuredContent — dropping it left the model blind and looping. */
2
5
  export function flattenResult(result) {
3
6
  const text = (result?.content ?? [])
4
7
  .map((c) => (c.type === "text" ? c.text ?? "" : `[${c.type}]`))
5
8
  .join("\n")
6
9
  .trim();
7
- const out = text || "(no content)";
8
- return result?.isError ? `error: ${out}` : out;
10
+ let structured = "";
11
+ if (result?.structuredContent !== undefined && result.structuredContent !== null) {
12
+ try {
13
+ structured = JSON.stringify(result.structuredContent);
14
+ }
15
+ catch { /* non-serializable → skip */ }
16
+ }
17
+ // Prefer both: the human line as a header, then the JSON payload the model parses. Either alone is valid.
18
+ const body = structured ? (text ? `${text}\n${structured}` : structured) : (text || "(no content)");
19
+ return result?.isError ? `error: ${body}` : body;
9
20
  }
10
21
  let RPC_ID = 0;
11
22
  export class McpHttpClient {
package/dist/session.js CHANGED
@@ -95,6 +95,7 @@ export class Session {
95
95
  memory;
96
96
  wantRecall;
97
97
  recallBlock = ""; // memory recalled on the first turn, folded into the system prompt thereafter
98
+ sessionTokensTotal = 0; // cumulative prefill+output tokens across all turns (Claude-Code-style session total)
98
99
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
99
100
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
100
101
  recalled = false;
@@ -195,6 +196,9 @@ export class Session {
195
196
  const chars = JSON.stringify(this.convo.all).length + (this.sys()?.length ?? 0);
196
197
  return Math.min(99, Math.round((Math.ceil(chars / 4) / this.inner.ctxLimit()) * 100));
197
198
  }
199
+ /** Cumulative tokens (prefill + output) across every turn this session — the Claude-Code-style running
200
+ * session total for the status rule, so the real spend is visible (not just the current completion). */
201
+ sessionTokens() { return this.sessionTokensTotal; }
198
202
  /** Abort the in-flight turn (ESC / Stop). No-op when idle. */
199
203
  interrupt() {
200
204
  this.ctrl?.abort();
@@ -342,6 +346,7 @@ export class Session {
342
346
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
343
347
  });
344
348
  this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
349
+ this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
345
350
  return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
346
351
  }
347
352
  catch (e) {
@@ -13,6 +13,9 @@ import { McpHub } from "../mcp/index.js";
13
13
  // through each step) and ACTIONS (input/mutation — always gated "ask" in the foreground, "deny" in bg).
14
14
  export const CHAUFFEUR_READ_TOOLS = [
15
15
  "list_windows", "get_window_state", "get_desktop_state", "list_apps", "clipboard_read",
16
+ // Session lifecycle (control, non-mutating → unprompted). Chauffeur is session-based: without these the
17
+ // model can't recover from a "session has ended" error and every stateful read fails in a loop.
18
+ "start_session", "get_session", "list_sessions",
16
19
  ];
17
20
  export const CHAUFFEUR_ACTION_TOOLS = [
18
21
  "launch_app", "bring_to_front", // window/app management
@@ -124,6 +124,62 @@ async function fileEdit(args) {
124
124
  return `error: ${e.message}`;
125
125
  }
126
126
  }
127
+ // Scratchpad — a private, per-session notes file OUTSIDE the workspace (so working notes never litter the
128
+ // repo or get grepped back into context). No `content` = read it; `content` = append (or mode:"overwrite").
129
+ // Path is injected by cli.tsx as KODE_SCRATCH_FILE.
130
+ async function scratchpad(args) {
131
+ const file = process.env.KODE_SCRATCH_FILE;
132
+ if (!file)
133
+ return "error: scratchpad is not configured in this session";
134
+ const { readFile, writeFile, appendFile, mkdir } = await nodeImport("node:fs/promises");
135
+ const { dirname } = await nodeImport("node:path");
136
+ if (args.content == null) {
137
+ try {
138
+ return (await readFile(file, "utf8")) || "(scratchpad is empty)";
139
+ }
140
+ catch {
141
+ return "(scratchpad is empty)";
142
+ }
143
+ }
144
+ const content = str(args.content);
145
+ try {
146
+ await mkdir(dirname(file), { recursive: true });
147
+ if (str(args.mode) === "overwrite")
148
+ await writeFile(file, content, "utf8");
149
+ else
150
+ await appendFile(file, content.endsWith("\n") ? content : content + "\n", "utf8");
151
+ return `scratchpad ${str(args.mode) === "overwrite" ? "written" : "appended"} → ${file}`;
152
+ }
153
+ catch (e) {
154
+ return `error: ${e.message}`;
155
+ }
156
+ }
157
+ // Session handoff — a note the agent writes for its FUTURE self working in this same directory. It is
158
+ // auto-loaded into the system prompt at the start of the next session here (cli.tsx). No `content` = read
159
+ // the current handoff; `content` = save one (overwrites, timestamped). Path is KODE_HANDOFF_FILE.
160
+ async function sessionHandoff(args) {
161
+ const file = process.env.KODE_HANDOFF_FILE;
162
+ if (!file)
163
+ return "error: session handoff is not configured in this session";
164
+ const { readFile, writeFile, mkdir } = await nodeImport("node:fs/promises");
165
+ const { dirname } = await nodeImport("node:path");
166
+ if (args.content == null) {
167
+ try {
168
+ return (await readFile(file, "utf8")) || "(no handoff saved yet)";
169
+ }
170
+ catch {
171
+ return "(no handoff saved yet)";
172
+ }
173
+ }
174
+ try {
175
+ await mkdir(dirname(file), { recursive: true });
176
+ await writeFile(file, `# Operator session handoff\n_updated ${new Date().toISOString()}_\n\n${str(args.content)}\n`, "utf8");
177
+ return `handoff saved → ${file} — your next session in this directory loads it automatically`;
178
+ }
179
+ catch (e) {
180
+ return `error: ${e.message}`;
181
+ }
182
+ }
127
183
  async function grepSearch(args) {
128
184
  const pattern = str(args.pattern);
129
185
  const path = expandPath(str(args.path, "."));
@@ -501,6 +557,23 @@ const TOOLS = [
501
557
  }, required: ["path", "old_string", "new_string"] },
502
558
  run: fileEdit,
503
559
  },
560
+ {
561
+ name: "scratchpad", safe: true,
562
+ description: "Your PRIVATE scratchpad for working notes, plans, and intermediate results that must NOT go in the workspace. Call with no args to read it; with `content` to append (or mode:\"overwrite\" to replace). Persists for this session — use it to think, track progress, and stash findings instead of cluttering the repo or your reply.",
563
+ parameters: { type: "object", properties: {
564
+ content: { type: "string", description: "text to add; omit to READ the scratchpad" },
565
+ mode: { type: "string", enum: ["append", "overwrite"], description: "default append" },
566
+ } },
567
+ run: scratchpad,
568
+ },
569
+ {
570
+ name: "session_handoff", safe: true,
571
+ description: "Write a handoff for your FUTURE self working in THIS directory: what you did, the current state, decisions, and the next steps. It is auto-loaded into your context at the start of the next session here, so you resume seamlessly. Call with no args to read the current handoff; with `content` to save one (overwrites). Update it before you finish or when you're running low on context.",
572
+ parameters: { type: "object", properties: {
573
+ content: { type: "string", description: "the handoff (markdown); omit to READ the current handoff" },
574
+ } },
575
+ run: sessionHandoff,
576
+ },
504
577
  {
505
578
  name: "grep_search", safe: true,
506
579
  description: "Recursively grep for a regex pattern under a path.",
package/dist/ui/App.js CHANGED
@@ -10,10 +10,10 @@ import { BgPanel } from "./BgPanel.js";
10
10
  import { ApprovalPrompt } from "./ApprovalPrompt.js";
11
11
  import { QuestionPrompt } from "./QuestionPrompt.js";
12
12
  export function App(props) {
13
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null } = props;
13
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null } = props;
14
14
  const thinking = status === "thinking" || status === "streaming";
15
15
  const showSpinner = status === "recovering" || status === "executing" || thinking;
16
16
  return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
17
17
  : status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
18
- : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question }), _jsx(InputRule, {})] }));
18
+ : _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question }), _jsx(InputRule, {})] }));
19
19
  }
@@ -1,5 +1,12 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
+ // Compact token count for the status rule: 1234 -> "1.2k", 45231 -> "45k", 800 -> "800".
4
+ function fmtK(n) {
5
+ if (n < 1000)
6
+ return String(n);
7
+ const k = n / 1000;
8
+ return `${k >= 10 ? Math.round(k) : k.toFixed(1)}k`;
9
+ }
3
10
  // Conservative terminal cell width: ASCII, Latin punctuation (·), and the box-drawing block (─, ≤ U+257F)
4
11
  // are one cell; anything above the box-drawing block is a symbol/dingbat/geometric glyph the terminal
5
12
  // font is free to render two cells wide, so we count it as 2. Over-estimating is safe (a shorter rule);
@@ -39,7 +46,8 @@ export function statusRight(p, cols) {
39
46
  const seat = p.tier && p.tier !== "admin" ? `⛨ ${p.tier} · ` : ""; // a narrowed seat shows; owner's admin doesn't
40
47
  const plan = p.planMode ? `◔ plan · ` : ""; // read-only research mode is visible while active
41
48
  const think = p.thinkMode === "ultrathink" ? `✲✲ ultrathink · ` : p.thinkMode === "think" ? `✲ think · ` : "";
42
- let info = `${think}${plan}${seat}${who}${p.route} · ${Math.round(p.ctxPct)}% · v${p.version}${p.build ? ` ·${p.build}` : ""}`;
49
+ const tok = p.sessionTokens && p.sessionTokens > 0 ? `Σ${fmtK(p.sessionTokens)} · ` : ""; // session token total
50
+ let info = `${think}${plan}${seat}${who}${p.route} · ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
43
51
  let right = `✷ OPERATOR · ${info} ─`;
44
52
  const maxRight = cols - 3; // leaves fill ≥ 1 and total = cols-1
45
53
  if (cellWidth(right) > maxRight) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.44",
3
+ "version": "0.1.46",
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": {
@@ -10,7 +10,8 @@
10
10
  "files": [
11
11
  "dist",
12
12
  "dashboard",
13
- "README.md"
13
+ "README.md",
14
+ "CHANGELOG.md"
14
15
  ],
15
16
  "engines": {
16
17
  "node": ">=20"