@0perator/operator 0.1.167 → 0.1.172

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/dist/session.js CHANGED
@@ -4,8 +4,9 @@
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, pickSummaryContent } from "./engine/compaction.js";
7
+ import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent } from "./engine/compaction.js";
8
8
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
9
+ import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
9
10
  import { engineRouter } from "./engine/router-adapter.js";
10
11
  import { appendFileSync, mkdirSync } from "node:fs";
11
12
  import { join, dirname } from "node:path";
@@ -21,6 +22,8 @@ import { McpHub, withMcp } from "./mcp/index.js";
21
22
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
22
23
  import { Telemetry } from "./observability/index.js";
23
24
  import { runSelfImprove } from "./selfimprove/index.js";
25
+ import { RollingSummarizer } from "./engine/rolling-summary.js";
26
+ import { createSleepScheduler } from "./consolidation/scheduler.js";
24
27
  // The `spawn_agent` tool — a thin pass-through to the shell's delegate handler. The handler owns the
25
28
  // policy (cap) and the reply text; the tool just guards against an empty task. safe:false so it's an
26
29
  // action (gated when permissions are on), never run speculatively in the safe-parallel batch.
@@ -228,6 +231,12 @@ export class Session {
228
231
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
229
232
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
230
233
  recalled = false;
234
+ // Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
235
+ // maintains a structured session-memory/summary.md during the session. When compact() fires,
236
+ // it loads the pre-written summary — /compact went from up to 2 minutes to instant.
237
+ rollingSummarizer = new RollingSummarizer();
238
+ // Sleep-time consolidation scheduler — triggers memory reorganization during idle (Engine doc #1).
239
+ sleepScheduler = null;
231
240
  constructor(cfg = {}) {
232
241
  // Calibration durability (SPEC §5, token-meter): learned chars/token persist beside the operator
233
242
  // state dir, so the FIRST deep session after a restart already sizes correctly instead of running
@@ -276,6 +285,8 @@ export class Session {
276
285
  this.wantRecall = cfg.recall ?? true;
277
286
  this.wantMcp = cfg.mcp === true || !!cfg.mcpHub;
278
287
  this.hub = cfg.mcpHub;
288
+ if (this.hub)
289
+ this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: offload huge MCP results too
279
290
  this.permissionCfg = cfg.permissions ?? { mode: "bypass" };
280
291
  this.policy = new PermissionPolicy(this.permissionCfg);
281
292
  this.approve = cfg.approve;
@@ -284,6 +295,17 @@ export class Session {
284
295
  this.eventActor = cfg.eventActor;
285
296
  this.sessionId = cfg.sessionId;
286
297
  this.tools = this.buildTools(); // local-only until first-turn MCP discovery rebinds it
298
+ // Initialize sleep-time consolidation if enabled (via settings or env).
299
+ const sleepEnabled = process.env.KODE_SLEEP_CONSOLIDATION === "1" || cfg.sleepConsolidation?.enabled;
300
+ if (sleepEnabled) {
301
+ const sc = cfg.sleepConsolidation ?? { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast" };
302
+ this.sleepScheduler = createSleepScheduler({
303
+ consolidation: { ...sc, enabled: true },
304
+ onComplete: (result) => {
305
+ this.telemetry.record({ type: "error", message: "consolidation completed" });
306
+ },
307
+ });
308
+ }
287
309
  }
288
310
  /** The effective system prompt: the base persona plus any memory recalled this session. Injected as
289
311
  * ONE system prompt — never a second system message, which 400s llama.cpp's chat template. */
@@ -414,7 +436,29 @@ export class Session {
414
436
  tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
415
437
  meter: globalTokenMeter,
416
438
  meterKey: this.meterKey(),
439
+ spill: spillToolOutput, // GW-10-COMPLETE: /compact's fitToWindow OFFLOADS (re-readable), never erases
417
440
  };
441
+ // Instant compaction: if a rolling summary exists, use it directly instead of calling the model.
442
+ // This is the "bridge until Pillar B ships" — the pre-written summary is loaded instantly,
443
+ // then compact() uses it as the evicted span's replacement.
444
+ const prewritten = this.rollingSummarizer.getSummary();
445
+ if (prewritten) {
446
+ const summaryMsg = {
447
+ role: "user",
448
+ content: `[Compacted summary (pre-written — instant)]:\n${prewritten}`,
449
+ };
450
+ const starts = turnStarts(this.convo.all);
451
+ const minKeep = opts.minKeepTurns ?? 4;
452
+ if (starts.length > minKeep) {
453
+ const cutIndex = starts[starts.length - minKeep];
454
+ const kept = this.convo.all.slice(cutIndex);
455
+ this.convo.replaceAll([summaryMsg, ...kept]);
456
+ const before = this.requestEstimate();
457
+ this.convo.replaceAll(fitToWindow(this.convo.all, opts));
458
+ return Math.max(0, before - this.requestEstimate());
459
+ }
460
+ }
461
+ // Fallback: normal compaction path (summarize + evict)
418
462
  const before = this.requestEstimate();
419
463
  this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
420
464
  return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
@@ -422,6 +466,26 @@ export class Session {
422
466
  /** Reset the conversation to empty (for /new). */
423
467
  reset() {
424
468
  this.convo.replaceAll([]);
469
+ this.rollingSummarizer.clear(); // clear the rolling summary on new session
470
+ }
471
+ /** Sleep-time consolidation — trigger memory reorganization. Returns the result. */
472
+ async consolidate() {
473
+ if (!this.sleepScheduler) {
474
+ // Start the scheduler if not already enabled
475
+ const sleepEnabled = process.env.KODE_SLEEP_CONSOLIDATION === "1";
476
+ if (!sleepEnabled)
477
+ return { lessonsExtracted: 0, lessonsPersisted: 0, memoryDeduped: 0, error: "consolidation disabled — set KODE_SLEEP_CONSOLIDATION=1" };
478
+ this.sleepScheduler = createSleepScheduler({
479
+ consolidation: { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast" },
480
+ });
481
+ }
482
+ const result = await this.sleepScheduler.forceConsolidate();
483
+ return {
484
+ lessonsExtracted: result.lessonsExtracted,
485
+ lessonsPersisted: result.lessonsPersisted,
486
+ memoryDeduped: result.memoryDeduped,
487
+ error: result.error,
488
+ };
425
489
  }
426
490
  turnCount() {
427
491
  return this.convo.all.filter((m) => m.role === "user").length;
@@ -541,6 +605,23 @@ export class Session {
541
605
  }
542
606
  catch { /* handoff is a durability convenience, never a hard dependency */ }
543
607
  }
608
+ /** Fire a rolling summary in the background (instant compaction bridge). Uses the SAME cache-safe
609
+ * prefix as compact() — identical system prompt, tools, and endpoint — so the llama.cpp slot hits
610
+ * f_sim=1.0 on the summarize request. Runs only when the latest round settled (no pending tool
611
+ * calls) to avoid stealing the slot from interactive turns. */
612
+ async fireRollingSummary() {
613
+ // Guard: don't fire during a tool-calling round (the model needs the slot)
614
+ // This is a best-effort background pass — never blocks the turn.
615
+ try {
616
+ // Summarize the entire current conversation (same span compact() would evict)
617
+ const summaryText = await this.summarize(this.convo.all);
618
+ if (summaryText) {
619
+ this.rollingSummarizer.setSummary(summaryText);
620
+ this.rollingSummarizer.markSummaryFired();
621
+ }
622
+ }
623
+ catch { /* best-effort — rolling summary never blocks a turn */ }
624
+ }
544
625
  /** First-turn setup, once only. (1) Recall memory relevant to what the user is asking (plus recent
545
626
  * notes) and fold it into the system prompt for the session. (2) Discover fleet MCP tools and merge
546
627
  * their schemas + dispatch. Both are best-effort — a failure degrades (local-only), never blocks. */
@@ -560,6 +641,8 @@ export class Session {
560
641
  try {
561
642
  if (!this.hub)
562
643
  this.hub = await McpHub.fromConfig();
644
+ if (this.hub)
645
+ this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: MCP offload
563
646
  await this.hub.discover();
564
647
  this.tools = this.buildTools(); // rebind so dispatch sees the discovered tools
565
648
  this.mcpSchemas = this.hub.schemas();
@@ -585,6 +668,7 @@ export class Session {
585
668
  shutdown() {
586
669
  this.hub?.shutdown();
587
670
  this.disposeShell();
671
+ this.sleepScheduler?.dispose(); // tear down the sleep consolidation scheduler
588
672
  }
589
673
  /** Kill just this session's persistent shell — call when a background sub-agent finishes so its
590
674
  * bash doesn't linger for the whole parent session. Safe to call more than once; a no-op if the
@@ -677,6 +761,7 @@ export class Session {
677
761
  router,
678
762
  tools: this.tools,
679
763
  toolSchemas: this.allSchemas(),
764
+ spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
680
765
  systemPrompt: sys,
681
766
  summarize: this.summarize,
682
767
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
@@ -697,6 +782,7 @@ export class Session {
697
782
  onToolResult: h.onToolResult,
698
783
  onToolBatch: h.onToolBatch,
699
784
  onAutoContinue: h.onAutoContinue,
785
+ onCacheStats: h.onCacheStats,
700
786
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
701
787
  // Verify-before-done: enabled unless KODE_VERIFY_GATE=0 (projected from settings.verifyGate). One
702
788
  // reminder round when a turn changed files but ran no passing check. Every surface routes through
@@ -705,6 +791,16 @@ export class Session {
705
791
  });
706
792
  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 });
707
793
  this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
794
+ // Instant compaction: feed token counts to the rolling summarizer. When a round ends without
795
+ // tool calls and we've crossed the threshold, the summarizer triggers a background summary.
796
+ const shouldSummarize = this.rollingSummarizer.feedRound(res.tokens ?? 0, res.toolCalls);
797
+ // Feed the sleep scheduler's step counter (triggers consolidation after N steps)
798
+ this.sleepScheduler?.recordStep();
799
+ if (shouldSummarize) {
800
+ // Fire the rolling summary in the background — the session's summarizer reuses the same
801
+ // cache-safe prefix as compact() so it hits KV cache. Runs only when the round settled.
802
+ this.fireRollingSummary();
803
+ }
708
804
  // Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
709
805
  // (best-effort, never blocks). Gated by KODE_SELFIMPROVE (projected from settings.selfImprove).
710
806
  void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY === "1" }, {
@@ -3,20 +3,79 @@
3
3
  // (the saved path) in place of the discarded middle and re-reads it on demand with file_read(offset/limit).
4
4
  // Injected into capToolResult so that module stays node-free for kode-web. Best-effort: a failed write returns
5
5
  // null and capToolResult falls back to the plain head+tail truncation — a spill must never fail a tool call.
6
- import { mkdirSync, writeFileSync } from "node:fs";
6
+ //
7
+ // GW-10-COMPLETE (Hermes): retention (spilled bytes otherwise accumulate forever), content-hash names
8
+ // (a re-run of the same command re-spills identical bytes — a hash makes that a cheap overwrite and keeps
9
+ // the dir greppable), and an env override so tests/CI/second-user boxes isolate the dir instead of writing
10
+ // the shared box dir. All best-effort: a sweep/name failure never blocks a spill.
11
+ import { createHash } from "node:crypto";
12
+ import { mkdirSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
7
13
  import { join } from "node:path";
8
14
  import { homedir } from "node:os";
9
- /** Where spilled tool outputs live. A flat dir under the operator home; the model is handed absolute paths. */
15
+ const RETENTION_MS = 14 * 24 * 3600_000; // spill files older than 14 days are pruned
16
+ const MAX_DIR_BYTES = 500 * 1024 * 1024; // hard ceiling on the spill dir (500MB)
17
+ const SWEEP_INTERVAL_MS = 3600_000; // at most once per hour, from spillToolOutput
18
+ /** Where spilled tool outputs live. A flat dir under the operator home; the model is handed absolute paths.
19
+ * KODE_TOOL_OUTPUT_DIR overrides it (tests/CI/second-user isolation). */
10
20
  export function toolOutputDir() {
11
- return join(homedir(), ".axe", "operator", "tool-outputs");
21
+ return process.env.KODE_TOOL_OUTPUT_DIR || join(homedir(), ".axe", "operator", "tool-outputs");
22
+ }
23
+ let _lastSweep = 0;
24
+ /** Best-effort retention sweep: age out >RETENTION_MS files, then cap the dir at MAX_DIR_BYTES oldest-first.
25
+ * force:true bypasses the hourly throttle (tests / ops). Never throws — the spill dir is a cache, not a ledger. */
26
+ export function sweepToolOutputs(dir = toolOutputDir(), opts = {}) {
27
+ const now = Date.now();
28
+ if (!opts.force && now - _lastSweep < SWEEP_INTERVAL_MS)
29
+ return;
30
+ _lastSweep = now;
31
+ let entries;
32
+ try {
33
+ entries = readdirSync(dir)
34
+ .filter((f) => f.endsWith(".txt"))
35
+ .map((f) => {
36
+ try {
37
+ const st = statSync(join(dir, f));
38
+ return { f, mtime: st.mtimeMs, size: st.size };
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ })
44
+ .filter((x) => !!x);
45
+ }
46
+ catch {
47
+ return;
48
+ } // dir missing = nothing to sweep
49
+ for (const e of entries) {
50
+ if (now - e.mtime > RETENTION_MS) {
51
+ try {
52
+ rmSync(join(dir, e.f));
53
+ }
54
+ catch { /* raced; fine */ }
55
+ }
56
+ }
57
+ const alive = entries.filter((e) => now - e.mtime <= RETENTION_MS);
58
+ let total = alive.reduce((n, e) => n + e.size, 0);
59
+ if (total > MAX_DIR_BYTES) {
60
+ for (const e of [...alive].sort((a, b) => a.mtime - b.mtime)) {
61
+ if (total <= MAX_DIR_BYTES)
62
+ break;
63
+ try {
64
+ rmSync(join(dir, e.f));
65
+ total -= e.size;
66
+ }
67
+ catch { /* skip */ }
68
+ }
69
+ }
12
70
  }
13
- let _seq = 0; // process-local tiebreaker so two spills in the same ms don't collide
14
71
  /** Persist `full` and return its absolute path, or null on any failure (caller degrades to head+tail). */
15
72
  export function spillToolOutput(full) {
16
73
  try {
17
74
  const dir = toolOutputDir();
18
75
  mkdirSync(dir, { recursive: true });
19
- const path = join(dir, `${Date.now().toString(36)}-${(_seq++).toString(36)}.txt`);
76
+ sweepToolOutputs(dir);
77
+ const hash = createHash("sha1").update(full).digest("hex").slice(0, 12);
78
+ const path = join(dir, `${Date.now().toString(36)}-${hash}.txt`);
20
79
  writeFileSync(path, full);
21
80
  return path;
22
81
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.167",
3
+ "version": "0.1.172",
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": {
@@ -1,70 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- // BusTray — live Switchboard messages surfaced in the Operator TUI as click-to-expand cards. Top-anchored
3
- // in the fullscreen layout so each card's absolute terminal row is deterministic (topRow + Σ heights above),
4
- // which is what makes mouse hit-testing reliable without Ink absolute-position measurement. Clicking a card
5
- // toggles its body (the Phase-1 mouse layer in action). In inline mode (no mouse) the cards still render,
6
- // just not clickable. Messages are DATA from other agents — shown, never executed.
7
- import { useEffect, useState } from "react";
8
- import { Box, Text } from "ink";
9
- import { useMouse } from "./MouseProvider.js";
10
- const MAX_BODY_LINES = 8; // cap an expanded card's body so one big message can't dominate the screen
11
- function wrap(line, width) {
12
- const w = Math.max(1, width);
13
- if (line.length <= w)
14
- return [line];
15
- const out = [];
16
- for (let i = 0; i < line.length; i += w)
17
- out.push(line.slice(i, i + w));
18
- return out;
19
- }
20
- /** Pure layout: assign each message a card with an absolute row (y) and height, given which ids are
21
- * expanded and the terminal width. Deterministic top-to-bottom stacking from `topRow` — the basis for both
22
- * render order and click hit-testing. Exported for unit tests. */
23
- export function trayLayout(messages, expanded, cols, topRow = 1) {
24
- const width = cols > 0 ? cols : 80;
25
- const cards = [];
26
- let y = topRow;
27
- for (const msg of messages) {
28
- const isExp = expanded.has(msg.id);
29
- const bodyLines = isExp
30
- ? msg.body.split("\n").flatMap((l) => wrap(l, width - 2)).slice(0, MAX_BODY_LINES)
31
- : [];
32
- const height = 1 + bodyLines.length;
33
- cards.push({ msg, y, height, expanded: isExp, bodyLines });
34
- y += height;
35
- }
36
- return cards;
37
- }
38
- function preview(body, cols) {
39
- const one = body.replace(/\s+/g, " ").trim();
40
- const budget = Math.max(10, (cols > 0 ? cols : 80) - 28);
41
- return one.length > budget ? one.slice(0, budget - 1) + "…" : one;
42
- }
43
- /** The tray. `cols` is the terminal width (for wrapping + region width). Renders nothing when empty. */
44
- export function BusTray({ messages, cols }) {
45
- const { registerRegion, enabled } = useMouse();
46
- const [expanded, setExpanded] = useState(() => new Set());
47
- const cards = trayLayout(messages, expanded, cols);
48
- // Register every card's clickable region imperatively (one effect, not a hook-per-card — the message
49
- // count varies, which would violate rules-of-hooks). A left-press anywhere on a card toggles its body.
50
- const sig = cards.map((c) => `${c.msg.id}:${c.y}:${c.height}`).join("|");
51
- useEffect(() => {
52
- if (!enabled || !cards.length)
53
- return;
54
- const disposers = cards.map((c) => registerRegion({ id: `bus:${c.msg.id}`, x: 1, y: c.y, width: Math.max(1, cols), height: c.height }, () => {
55
- setExpanded((prev) => {
56
- const next = new Set(prev);
57
- if (next.has(c.msg.id))
58
- next.delete(c.msg.id);
59
- else
60
- next.add(c.msg.id);
61
- return next;
62
- });
63
- }));
64
- return () => disposers.forEach((d) => d());
65
- // eslint-disable-next-line react-hooks/exhaustive-deps
66
- }, [enabled, registerRegion, cols, sig]);
67
- if (!messages.length)
68
- return null;
69
- return (_jsx(Box, { flexDirection: "column", children: cards.map((c) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { color: "cyan", children: [c.expanded ? "▾" : "▸", " ", "📨 ", c.msg.from, c.msg.subject ? ` [${c.msg.subject}]` : "", c.expanded ? "" : `: ${preview(c.msg.body, cols)}`, enabled && !c.expanded ? _jsx(Text, { dimColor: true, children: " \u00B7 click to expand" }) : null] }), c.expanded ? c.bodyLines.map((l, i) => _jsx(Text, { dimColor: true, children: " " + l }, i)) : null] }, c.msg.id))) }));
70
- }