@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.
@@ -82,8 +82,8 @@ const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets,
82
82
  const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
83
83
  const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
84
84
  const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
85
- const RUNAWAY_CHARS = 120_000; // a round is capped at max_tokens (~8k => ~33k chars); far past that is a
86
- // decode loop or a stream/render duplication, never a real answer — hard stop.
85
+ const RUNAWAY_CHARS = 260_000; // with 32K output tokens the model can legitimately produce ~130K chars;
86
+ // 260K gives 2x headroom before cutting a decode loop or stream duplication.
87
87
  function hasAlpha(s) {
88
88
  return /[a-zA-Z]/.test(s);
89
89
  }
@@ -178,7 +178,15 @@ function requestBody(messages, o, stream) {
178
178
  // prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
179
179
  // the server prefix-matches and prefills only the new tail. Harmless on servers that ignore the field.
180
180
  cache_prompt: true,
181
- max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
181
+ // GW-26 — ngram speculation is DEFAULT-ON in modern llama.cpp and a NET LOSS on the DeltaNet-hybrid
182
+ // Aurora at untuned draft params: measured live on :8097 (b11146, ctx 307K), acceptance 3-17% and
183
+ // 4-6 tok/s decode WITH it vs 20-25 tok/s WITHOUT — every rejected draft forces a multi-token
184
+ // re-verify + recache on the hybrid. Shape verified live: {"speculative":{"ngram":{"enabled":false}}}
185
+ // -> timings.draft_n drops to 0 and decode jumps 4x; a `{"type":"none"}` variant is silently IGNORED,
186
+ // so keep this exact shape. Servers without llama.cpp speculation ignore the field (same contract
187
+ // as cache_prompt). Escape hatch when a retuned/high-acceptance bless lands: enableSpeculation: true.
188
+ ...(o.enableSpeculation ? {} : { speculative: { ngram: { enabled: false } } }),
189
+ max_tokens: o.maxTokens ?? 32768, temperature: o.temperature ?? 0.7,
182
190
  ...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
183
191
  // /think: re-enable the model's native reasoning for THIS request, overriding the server's
184
192
  // enable_thinking:false default (set for speed). Verified this per-request override works on the
@@ -269,8 +277,10 @@ async function* streamDeltas(messages, o) {
269
277
  try {
270
278
  const j = JSON.parse(d);
271
279
  // llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
280
+ // cache_n / prompt_tokens_details.cached_tokens = how much of the prompt the server SERVED FROM
281
+ // ITS PREFIX CACHE this round (vs re-prefilled) — GW-05: parse it, don't throw away the truth.
272
282
  if (j.timings || j.usage)
273
- 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 });
283
+ 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, cacheN: j.timings?.cache_n ?? j.usage?.prompt_tokens_details?.cached_tokens });
274
284
  const choice = j.choices?.[0];
275
285
  // finish_reason is a sibling of delta (often on a final chunk whose delta is {} or absent).
276
286
  // Attach it to the yielded delta, and still yield a bare {finish_reason} when there's no delta,
@@ -328,7 +338,8 @@ export async function chat(messages, o) {
328
338
  meta.tokens = m.tokens; if (m.genMs != null)
329
339
  meta.genMs = m.genMs; if (m.promptTokens != null)
330
340
  meta.promptTokens = m.promptTokens; if (m.promptMs != null)
331
- meta.promptMs = m.promptMs; o.onMeta?.(m); } };
341
+ meta.promptMs = m.promptMs; if (m.cacheN != null)
342
+ meta.cacheN = m.cacheN; o.onMeta?.(m); } };
332
343
  for await (const delta of streamDeltas(messages, oo)) {
333
344
  if (delta.content) {
334
345
  content += delta.content;
@@ -395,7 +406,18 @@ export async function chat(messages, o) {
395
406
  const tokens = tokensExact ? meta.tokens
396
407
  : generatedChars > 0 ? globalTokenMeter.estimateCompletion(generatedChars) // SPEC §5: calibrated output ratio (cold = chars/4 prior)
397
408
  : meta.tokens;
398
- return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, tokensExact, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs };
409
+ return { content, toolCalls, reasoningContent: reasoning || undefined, stopReason, tokens, tokensExact, genMs: meta.genMs, promptTokens: meta.promptTokens, promptMs: meta.promptMs, cacheN: meta.cacheN };
410
+ }
411
+ /** GW-05 cache-bust notice: a PURE shape-checker — the CALLER decides what counts as a continuation
412
+ * (the very first request of a process legitimately misses everything). Returns a human line when a
413
+ * continuation request re-prefilled >= minTokens with ZERO server cache reuse, else null. promptMs
414
+ * (when present) prices the bust in wall-seconds — the number that makes "why is it crawling" answerable. */
415
+ export function cacheBustNotice(o) {
416
+ const min = o.minTokens ?? 8000;
417
+ if (o.requestIndex <= 1 || o.cached > 0 || o.promptTokens < min)
418
+ return null;
419
+ const secs = o.promptMs ? ` (~${(o.promptMs / 1000).toFixed(1)}s prefill)` : "";
420
+ return `prefix cache missed on a continuation — ${o.promptTokens.toLocaleString()} tokens re-prefilled${secs}`;
399
421
  }
400
422
  /** GET {base}/health → true iff {"status":"ok"}. Used by Router (SPEC §4) for self-heal failover. */
401
423
  export async function health(base) {
@@ -0,0 +1,74 @@
1
+ // GW-06 oracle seed: cold-start calibration from the endpoint's OWN tokenizer.
2
+ //
3
+ // The token meter (token-meter.ts, SPEC §5) cold-starts at the legacy chars/4 prior. Measured truth
4
+ // (docs/reviews/aurora-tier0/calibrate-token-meter.py, 2026-10-01): agent-shaped traffic on Aurora packs
5
+ // at ~2.15 chars/token — the 4.0 prior UNDER-counts by 41-50%, so a fresh install's compaction gate
6
+ // fires LATE (the dangerous side) for its first ~10 rounds. llama.cpp exposes the exact oracle offline
7
+ // (`POST /apply-template` → server-side render, `POST /tokenize {special:true}` → exact ids). We seed
8
+ // ONE weight-1 observation per zero-sample endpoint at startup — fire-and-forget, superseded instantly
9
+ // by real server-reported observations. The oracle stays OFF the hot path (inherited ruling: one
10
+ // round-trip per sizing check is not worth it).
11
+ //
12
+ // Browser-safety: no node builtins — plain `fetch` via an injectable transport (tests fake it).
13
+ import { endpointKey, requestChars, globalTokenMeter } from "./token-meter.js";
14
+ export const fetchTransport = {
15
+ async postJSON(url, body) {
16
+ const r = await fetch(url, {
17
+ method: "POST",
18
+ headers: { "Content-Type": "application/json" },
19
+ body: JSON.stringify(body),
20
+ });
21
+ if (!r.ok)
22
+ throw new Error("http " + r.status);
23
+ return await r.json();
24
+ },
25
+ };
26
+ /** Representative agent request shape: a system block with code, a realistic tool-schema set, and a
27
+ * user ask — the traffic class the meter sizes. >=500-char basis so observePrompt's signal guard
28
+ * accepts the sample. Deliberately generic (not harness-faithful): the seed only needs to be CLOSER
29
+ * than 4.0; real observations take over within a round or two. */
30
+ export function seedProbe() {
31
+ const messages = [
32
+ { role: "system", content: "You are a terminal coding agent. Tools operate on the working tree.\n" +
33
+ Array.from({ length: 24 }, (_, i) => `def validate_${i}(shard: dict) -> bool: # checksum 0x${((i * 2654435761) >>> 0).toString(16)}`).join("\n") },
34
+ { role: "user", content: "Read src/engine/token-meter.ts, run the test suite, and summarize any failing assertion in plain language, quoting the exact expected and actual values." },
35
+ ];
36
+ const schema = (name, desc, props, required) => ({
37
+ type: "function",
38
+ function: { name, description: desc, parameters: { type: "object", properties: props, required } },
39
+ });
40
+ const tools = [
41
+ schema("file_read", "Read a file from the working tree with optional pagination.", { path: { type: "string" }, offset: { type: "integer" }, limit: { type: "integer" } }, ["path"]),
42
+ schema("shell", "Run a shell command in the session sandbox.", { command: { type: "string" }, cwd: { type: "string" }, timeout: { type: "integer" } }, ["command"]),
43
+ schema("edit", "Patch a file by exact string replacement.", { path: { type: "string" }, old_string: { type: "string" }, new_string: { type: "string" }, replace_all: { type: "boolean" } }, ["path", "old_string", "new_string"]),
44
+ schema("grep", "Regex-search file contents.", { pattern: { type: "string" }, path: { type: "string" }, file_glob: { type: "string" } }, ["pattern"]),
45
+ schema("web_fetch", "Fetch a URL and return readable text.", { url: { type: "string" } }, ["url"]),
46
+ ];
47
+ return { messages, tools };
48
+ }
49
+ /** Seed `base|model` once if the meter has zero observations for it. Never throws; never blocks. */
50
+ export async function seedCalibration(base, model, meter = globalTokenMeter, t = fetchTransport, probe = seedProbe()) {
51
+ const key = endpointKey(base, model);
52
+ if (meter.promptSamplesFor(key) > 0)
53
+ return "already-calibrated";
54
+ try {
55
+ const at = await t.postJSON(`${base}/apply-template`, {
56
+ messages: probe.messages, tools: probe.tools, add_generation_prompt: true,
57
+ });
58
+ const rendered = typeof at === "string" ? at : (at?.prompt ?? "");
59
+ if (!rendered)
60
+ return "no-template";
61
+ const tk = await t.postJSON(`${base}/tokenize`, { content: rendered, special: true });
62
+ const exact = Array.isArray(tk?.tokens) ? tk.tokens.length : 0;
63
+ // The meter charges +4/message template overhead on top of its ratio; strip the framing from the
64
+ // server-exact count so the seeded ratio measures CONTENT density only.
65
+ const adjusted = exact - 4 * probe.messages.length;
66
+ if (adjusted <= 0)
67
+ return "weak-sample";
68
+ meter.observePrompt(key, requestChars(probe.messages, probe.tools), adjusted);
69
+ return meter.promptSamplesFor(key) > 0 ? "seeded" : "rejected"; // rejected = tripped a signal guard
70
+ }
71
+ catch {
72
+ return "unreachable";
73
+ }
74
+ }
@@ -122,16 +122,21 @@ export function fitToWindow(conversation, opts) {
122
122
  if (usageRatio(conversation, opts) < (opts.threshold ?? 0.7))
123
123
  return [...conversation];
124
124
  const out = conversation.map((m) => ({ ...m }));
125
- // Tool messages, largest content first — elide the worst offenders until it fits.
125
+ // Tool messages, largest content first — shed the worst offenders until it fits. GW-10-COMPLETE:
126
+ // error-ish results go LAST (Manus doctrine — a failed tool trace in context suppresses repeat
127
+ // mistakes; a success's bytes are re-fetchable from the spill file, the failure's lesson is not).
126
128
  const byLargest = out
127
- .map((m, i) => ({ i, len: m.role === "tool" ? m.content.length : 0 }))
129
+ .map((m, i) => ({ i, len: m.role === "tool" ? m.content.length : 0, err: /^(error[:\s]|\(no output; exit)/i.test(m.content) }))
128
130
  .filter((x) => x.len > 0)
129
- .sort((a, b) => b.len - a.len);
131
+ .sort((a, b) => (a.err === b.err ? b.len - a.len : a.err ? 1 : -1));
130
132
  for (const { i } of byLargest) {
131
133
  if (usageRatio(out, opts) < (opts.threshold ?? 0.7))
132
134
  break;
133
135
  const was = out[i].content.length;
134
- out[i] = { ...out[i], content: `[large tool output elided to fit the ${opts.ctxWindow.toLocaleString()}-token context — was ${was.toLocaleString()} chars]` };
136
+ const p = opts.spill ? opts.spill(out[i].content) : null;
137
+ out[i] = p
138
+ ? { ...out[i], content: `[large tool output offloaded to fit the ${opts.ctxWindow.toLocaleString()}-token context — FULL ${was.toLocaleString()} chars at ${p}; re-read exact sections with file_read(path, offset, limit)]` }
139
+ : { ...out[i], content: `[large tool output elided to fit the ${opts.ctxWindow.toLocaleString()}-token context — was ${was.toLocaleString()} chars]` };
135
140
  }
136
141
  return out;
137
142
  }
@@ -159,7 +164,7 @@ export function pickSummaryContent(content, reasoning) {
159
164
  return (reasoning ?? "").trim();
160
165
  }
161
166
  /** A "turn" starts at a user message. Returns the index of each turn start, in order. */
162
- function turnStarts(conversation) {
167
+ export function turnStarts(conversation) {
163
168
  const idxs = [];
164
169
  conversation.forEach((m, i) => {
165
170
  if (m.role === "user")
@@ -12,6 +12,7 @@
12
12
  // Pure + framework-agnostic; node builtins (fs/child_process for verify) load lazily so the neutral bundle
13
13
  // is unaffected. The verify predicate (isVerifyCmd/ranButFailed) is shared with the main-loop verify gate.
14
14
  import { isVerifyCmd, ranButFailed } from "./verify-gate.js";
15
+ import { applySRFTMask, runMutationCheck } from "../flywheel/processor.js";
15
16
  const nodeImport = (m) => import(m);
16
17
  // Infer the task type from a free-form objective when the caller didn't declare one — keeps the tool
17
18
  // usable with just a task string while still selecting the right schema + verify + lane.
@@ -217,6 +218,18 @@ export async function verifyFinalAnswer(value, type, cwd) {
217
218
  return { verified: false, detail: `verify error: ${e instanceof Error ? e.message : String(e)}` };
218
219
  }
219
220
  }
221
+ /** Mutation check — catches vacuous passes. After verify_command passes, re-run it against a mutation:
222
+ * git stash / revert the turn's diff in a temp worktree. If the suite still passes, the tests don't
223
+ * test the change (the "37/37 file-exists" class caught by behavior, not regex). */
224
+ export async function verifyMutation(cwd, verifyCommand, diffSha) {
225
+ return runMutationCheck(cwd, verifyCommand, diffSha);
226
+ }
227
+ /** Apply SRFT step masking to a graded trajectory. Marks each step as productive (keep in loss) or
228
+ * harmful (mask from loss). A step is harmful if it's a tool call that returned an error, part of
229
+ * a repetition loop, or triggered a forced redirect. */
230
+ export function applySRFT(traj) {
231
+ return applySRFTMask(traj);
232
+ }
220
233
  // --- 4. size-routed spawn -----------------------------------------------------------
221
234
  /** Pick the lane by task size/complexity (mechanism 4). reasoning = full 1M; fast = small/bounded model
222
235
  * for mechanical children. A caller `heavy` hint forces reasoning; plan/review are always reasoning. */
@@ -0,0 +1,101 @@
1
+ // Rolling session summary — the "instant compaction" mechanism.
2
+ // A background summarizer runs during lulls (when a round ends without tool calls)
3
+ // and maintains a structured session-memory/summary.md. When compact() fires,
4
+ // it loads this pre-computed summary instead of making a live summarize call,
5
+ // turning a 48s–5min stall into zero user-visible latency.
6
+ //
7
+ // Also pre-builds the living-memory block for Pillar B's journal index.
8
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { homedir } from "node:os";
11
+ const SESSION_MEMORY_DIR = `${homedir()}/.axe/operator/session-memory`;
12
+ const SUMMARY_FILE = join(SESSION_MEMORY_DIR, "summary.md");
13
+ const DEFAULTS = {
14
+ minTokensSinceUpdate: 5000,
15
+ minToolBatches: 3,
16
+ maxSummaryChars: 4000,
17
+ enabled: true,
18
+ };
19
+ export class RollingSummarizer {
20
+ opts;
21
+ lastUpdateTokens = 0;
22
+ lastUpdateBatches = 0;
23
+ lastUpdateTime = 0;
24
+ summaryCache = "";
25
+ dirty = false;
26
+ constructor(opts = {}) {
27
+ this.opts = { ...DEFAULTS, ...opts };
28
+ // Load existing summary if present
29
+ if (existsSync(SUMMARY_FILE)) {
30
+ this.summaryCache = readFileSync(SUMMARY_FILE, "utf8");
31
+ }
32
+ }
33
+ /** Feed token/batch counts from a completed round. Returns true if a summary should be triggered. */
34
+ feedRound(outputTokens, toolBatches) {
35
+ if (!this.opts.enabled)
36
+ return false;
37
+ this.lastUpdateTokens += outputTokens;
38
+ this.lastUpdateBatches += toolBatches;
39
+ // Check if we should trigger a summary
40
+ const minTokens = this.opts.minTokensSinceUpdate ?? DEFAULTS.minTokensSinceUpdate ?? 5000;
41
+ const minBatches = this.opts.minToolBatches ?? DEFAULTS.minToolBatches ?? 3;
42
+ const tokensOk = this.lastUpdateTokens >= minTokens;
43
+ const batchesOk = this.lastUpdateBatches >= minBatches;
44
+ if (tokensOk && batchesOk) {
45
+ this.dirty = true;
46
+ // Reset counters — the caller fires the actual summarize
47
+ this.lastUpdateTokens = 0;
48
+ this.lastUpdateBatches = 0;
49
+ return true;
50
+ }
51
+ return false;
52
+ }
53
+ /** Mark that a summary was fired (called by the session after summarizing). */
54
+ markSummaryFired() {
55
+ this.lastUpdateTime = Date.now();
56
+ this.dirty = false;
57
+ }
58
+ /** Get the current cached summary (for /compact to use). Empty string if none. */
59
+ getSummary() {
60
+ return this.summaryCache;
61
+ }
62
+ /** Set the summary content (called by the session after a summary is generated). */
63
+ setSummary(content) {
64
+ this.summaryCache = content;
65
+ this.writeSummary();
66
+ this.dirty = false;
67
+ }
68
+ /** Whether a summary is stale and should be refreshed. */
69
+ isStale() {
70
+ return this.dirty;
71
+ }
72
+ /** Whether to persist the summary to disk. */
73
+ writeSummary() {
74
+ try {
75
+ mkdirSync(SESSION_MEMORY_DIR, { recursive: true });
76
+ writeFileSync(SUMMARY_FILE, this.summaryCache, "utf8");
77
+ }
78
+ catch { /* best-effort — summary persistence never blocks a turn */ }
79
+ }
80
+ /** Truncate summary to max chars, keeping the most recent content. */
81
+ truncate(maxChars) {
82
+ const cap = maxChars || (this.opts?.maxSummaryChars ?? DEFAULTS.maxSummaryChars) || 4000;
83
+ if (this.summaryCache.length <= cap)
84
+ return this.summaryCache;
85
+ // Keep the tail — newer info is more relevant
86
+ return this.summaryCache.slice(-(cap - 50)) + "\n\n[summary truncated — older context in live conversation]";
87
+ }
88
+ /** Clear the rolling summary (for /new session). */
89
+ clear() {
90
+ this.summaryCache = "";
91
+ this.dirty = false;
92
+ this.lastUpdateTokens = 0;
93
+ this.lastUpdateBatches = 0;
94
+ try {
95
+ if (existsSync(SUMMARY_FILE)) {
96
+ writeFileSync(SUMMARY_FILE, "", "utf8");
97
+ }
98
+ }
99
+ catch { /* best-effort */ }
100
+ }
101
+ }
@@ -0,0 +1,251 @@
1
+ // Training flywheel upgrades — SRFT step masking, mutation verify, and eval harness.
2
+ // This turns the existing graded trajectory recorder into a self-improving loop.
3
+ import { mkdirSync, appendFileSync } from "node:fs";
4
+ import { join, dirname } from "node:path";
5
+ /** Apply SRFT-style step masking to a trajectory.
6
+ * Marks each step as productive (keep in loss) or harmful (mask from loss).
7
+ * A step is harmful if:
8
+ * - It's a tool call that returned an error
9
+ * - It's marked as a repetition loop guard
10
+ * - It's a parse_fallback lint
11
+ * - It triggered a forced redirect
12
+ */
13
+ export function applySRFTMask(trajectory) {
14
+ const mask = [];
15
+ let hasErrors = trajectory.stopReason === "repetition" || trajectory.unverified === true;
16
+ let isHarmful = hasErrors;
17
+ for (let i = 0; i < (trajectory.steps?.length ?? 0); i++) {
18
+ const step = trajectory.steps[i];
19
+ if (!step) {
20
+ mask.push(true); // default: include unknown steps
21
+ continue;
22
+ }
23
+ // Mask tool errors — the model shouldn't learn from failed tool calls
24
+ if (step.role === "tool" && step.content?.includes("error") && step.content?.includes("exit")) {
25
+ isHarmful = true;
26
+ }
27
+ // Mask steps that are part of a repetition loop
28
+ if (trajectory.stopReason === "repetition" && isHarmful) {
29
+ mask.push(false); // mask this step
30
+ }
31
+ else {
32
+ mask.push(true);
33
+ }
34
+ }
35
+ // If the trajectory is graded but has no explicit steps, mask the last few rounds
36
+ // (likely the failure tail)
37
+ if ((trajectory.steps?.length ?? 0) === 0 && trajectory.rounds > 3) {
38
+ const tailRounds = Math.min(trajectory.rounds - 3, 5);
39
+ for (let i = 0; i < tailRounds; i++) {
40
+ mask.push(false);
41
+ }
42
+ for (let i = tailRounds; i < trajectory.rounds; i++) {
43
+ mask.push(true);
44
+ }
45
+ }
46
+ return mask.length > 0 ? mask : new Array(trajectory.rounds).fill(true);
47
+ }
48
+ /** Run a mutation check on a verified turn.
49
+ * Stashes the worktree, reverts the diff, runs verify_command.
50
+ * If the suite still passes, the tests are vacuous (they don't test the change). */
51
+ export async function runMutationCheck(cwd, verifyCommand, diffSha) {
52
+ try {
53
+ // Create a temporary worktree for the revert test
54
+ const worktreeDir = join(cwd, ".worktrees", `mutation-check-${Date.now()}`);
55
+ mkdirSync(dirname(worktreeDir), { recursive: true });
56
+ // Run: git stash && git checkout <sha> -- . && git stash pop (revert the change)
57
+ // If verify_command still passes → vacuous test
58
+ const { execSync } = await import("node:child_process");
59
+ // Stash current changes
60
+ execSync("git stash push -m 'mutation-check-stash' -- .", { cwd, stdio: "pipe" });
61
+ // Revert to the pre-change state
62
+ execSync(`git checkout ${diffSha} -- .`, { cwd, stdio: "pipe" });
63
+ // Run verification
64
+ let verifyResult;
65
+ try {
66
+ verifyResult = execSync(verifyCommand, { cwd, encoding: "utf8", stdio: "pipe" });
67
+ }
68
+ catch (e) {
69
+ // Verify failed — good! The tests actually test something.
70
+ // Restore the stash
71
+ try {
72
+ execSync("git stash pop", { cwd, stdio: "pipe" });
73
+ }
74
+ catch { /* best-effort */ }
75
+ return {
76
+ passed: false,
77
+ detail: "verify_command FAILED after reverting the change — tests are valid (not vacuous)",
78
+ verifyCommand,
79
+ worktree: worktreeDir,
80
+ };
81
+ }
82
+ // Restore the stash
83
+ try {
84
+ execSync("git stash pop", { cwd, stdio: "pipe" });
85
+ }
86
+ catch { /* best-effort */ }
87
+ return {
88
+ passed: true,
89
+ detail: "verify_command passed even after reverting — tests may be vacuous (existence checks only)",
90
+ verifyCommand,
91
+ worktree: worktreeDir,
92
+ };
93
+ }
94
+ catch (e) {
95
+ return {
96
+ passed: false,
97
+ detail: `mutation check error: ${e instanceof Error ? e.message : String(e)}`,
98
+ verifyCommand,
99
+ error: e instanceof Error ? e.message : String(e),
100
+ };
101
+ }
102
+ }
103
+ /** Run a single eval task. Returns the result. */
104
+ export async function runEvalTask(task, modelFn) {
105
+ const startTime = Date.now();
106
+ try {
107
+ // Apply the "after" state
108
+ const { execSync } = await import("node:child_process");
109
+ // Restore to before state
110
+ execSync(`git checkout ${task.beforeState} -- .`, { cwd: task.cwd, stdio: "pipe" });
111
+ // Apply the model's output (diff, file writes, etc.)
112
+ // This is where the harness would apply the model's generated changes
113
+ // For now, we assume the changes are already applied and we verify them
114
+ const verifyOutput = execSync(task.verifyCommand, {
115
+ cwd: task.cwd,
116
+ encoding: "utf8",
117
+ timeout: task.timeoutMs ?? 120000,
118
+ stdio: "pipe",
119
+ });
120
+ const passed = verifyOutput.includes("pass") || verifyOutput.includes("PASSED") || verifyOutput.includes("0 failing");
121
+ return {
122
+ taskId: task.id,
123
+ passed,
124
+ detail: verifyOutput.slice(0, 500),
125
+ durationMs: Date.now() - startTime,
126
+ timestamp: Date.now(),
127
+ };
128
+ }
129
+ catch (e) {
130
+ return {
131
+ taskId: task.id,
132
+ passed: false,
133
+ detail: e instanceof Error ? e.message : String(e),
134
+ durationMs: Date.now() - startTime,
135
+ timestamp: Date.now(),
136
+ };
137
+ }
138
+ }
139
+ /** Run a suite of eval tasks. Returns aggregate results. */
140
+ export function aggregateEvalResults(results) {
141
+ const total = results.length;
142
+ const passed = results.filter(r => r.passed).length;
143
+ const failed = results.filter(r => !r.passed).length;
144
+ return {
145
+ total,
146
+ passed,
147
+ failed,
148
+ passRate: total > 0 ? passed / total : 0,
149
+ results,
150
+ timestamp: Date.now(),
151
+ };
152
+ }
153
+ let loraState = { active: {}, loaded: {} };
154
+ /** Apply a LoRA adapter to an endpoint. */
155
+ export async function applyLoRAAdapter(endpoint, adapter) {
156
+ try {
157
+ const { execSync } = await import("node:child_process");
158
+ // POST to the llama.cpp server's /lora-adapters endpoint
159
+ const body = JSON.stringify({ lora: [{ id: adapter.id, scale: adapter.scale ?? 1.0 }] });
160
+ execSync(`curl -s -X POST "${endpoint}/lora-adapters" -H "Content-Type: application/json" -d '${body}'`, {
161
+ stdio: "pipe",
162
+ });
163
+ loraState.active[endpoint] = loraState.active[endpoint] ?? [];
164
+ loraState.active[endpoint].push(adapter);
165
+ return true;
166
+ }
167
+ catch {
168
+ return false;
169
+ }
170
+ }
171
+ /** Remove a LoRA adapter from an endpoint. */
172
+ export async function removeLoRAAdapter(endpoint, adapterId) {
173
+ try {
174
+ const { execSync } = await import("node:child_process");
175
+ execSync(`curl -s -X POST "${endpoint}/lora-adapters" -H "Content-Type: application/json" -d '{"lora":[]}'`, {
176
+ stdio: "pipe",
177
+ });
178
+ loraState.active[endpoint] = (loraState.active[endpoint] ?? []).filter(a => a.id !== adapterId);
179
+ return true;
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ }
185
+ /** Get the current LoRA state. */
186
+ export function getLoRAState() {
187
+ return { ...loraState };
188
+ }
189
+ export class FlywheelProcessor {
190
+ opts;
191
+ constructor(opts) {
192
+ this.opts = opts;
193
+ }
194
+ /** Process all trajectories in the flywheel directory.
195
+ * Applies SRFT masking, runs mutation checks, and outputs cleaned trajectories. */
196
+ async processAll() {
197
+ const { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync } = await import("node:fs");
198
+ const { join } = await import("node:path");
199
+ const flywheelDir = this.opts.flywheelDir;
200
+ if (!existsSync(flywheelDir)) {
201
+ return { total: 0, processed: 0, masked: 0, results: [] };
202
+ }
203
+ const files = readdirSync(flywheelDir).filter(f => f.endsWith(".jsonl"));
204
+ const allRows = [];
205
+ for (const file of files) {
206
+ const filepath = join(flywheelDir, file);
207
+ const raw = readFileSync(filepath, "utf8");
208
+ const lines = raw.split("\n").filter(Boolean);
209
+ for (const line of lines) {
210
+ try {
211
+ const row = JSON.parse(line);
212
+ if (row.graded) {
213
+ allRows.push(row);
214
+ }
215
+ }
216
+ catch { /* skip malformed rows */ }
217
+ }
218
+ }
219
+ // Process each trajectory
220
+ const processed = [];
221
+ let maskedCount = 0;
222
+ for (const traj of allRows) {
223
+ let processedTraj = { ...traj };
224
+ // Apply SRFT masking
225
+ if (this.opts.applySRFT) {
226
+ const mask = applySRFTMask(traj);
227
+ processedTraj.stepLossMask = mask;
228
+ maskedCount += mask.filter(m => !m).length;
229
+ }
230
+ // Run mutation check if enabled
231
+ if (this.opts.runMutationCheck && traj.cwd && traj.toolCalls && traj.toolCalls > 0) {
232
+ // This would need the verify command and diff sha from the turn
233
+ // For now, we note it needs to be wired to the actual turn data
234
+ }
235
+ processed.push(processedTraj);
236
+ }
237
+ // Write processed trajectories
238
+ const outputDir = this.opts.outputDir ?? join(flywheelDir, "processed");
239
+ mkdirSync(outputDir, { recursive: true });
240
+ const outputFile = join(outputDir, `${new Date().toISOString().slice(0, 10)}-processed.jsonl`);
241
+ for (const p of processed) {
242
+ appendFileSync(outputFile, JSON.stringify(p) + "\n", "utf8");
243
+ }
244
+ return {
245
+ total: allRows.length,
246
+ processed: processed.length,
247
+ masked: maskedCount,
248
+ results: processed,
249
+ };
250
+ }
251
+ }
package/dist/index.js CHANGED
@@ -7,6 +7,8 @@ export { withPermissions, PermissionPolicy } from "./permissions/index.js";
7
7
  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
+ export { cacheBustNotice } from "./engine/aurora.js";
11
+ export { seedCalibration, seedProbe } from "./engine/calibration-seed.js";
10
12
  export { recoverToolCalls } from "./engine/toolcalls.js";
11
13
  export { needsCompaction, compact, summaryPrompt, clampMaxTokens, usageRatio, pickSummaryContent } from "./engine/compaction.js";
12
14
  export { TokenMeter, globalTokenMeter, endpointKey, requestChars, COLD_CHARS_PER_TOKEN } from "./engine/token-meter.js";
package/dist/mcp/index.js CHANGED
@@ -21,6 +21,10 @@ export class McpHub {
21
21
  constructor(servers) {
22
22
  this.servers = servers;
23
23
  }
24
+ /** GW-10-COMPLETE: node hosts may inject a spill sink so huge REMOTE (MCP) results are offloaded
25
+ * losslessly like local ones (capToolResult's optional sink). Kept as an assignable field (not a
26
+ * constructor arg) so McpHub's browser-barrel re-export stays node-free and kode-web is unaffected. */
27
+ spillSink;
24
28
  /** Build a hub from the on-disk config (mcp_servers.json). Empty/absent config → an inert hub. */
25
29
  static async fromConfig() {
26
30
  return new McpHub(await loadMcpConfig());
@@ -95,7 +99,7 @@ export class McpHub {
95
99
  if (!t)
96
100
  return `error: unknown MCP tool ${name}`;
97
101
  try {
98
- return capToolResult(await t.client.callTool(t.def.name, args));
102
+ return capToolResult(await t.client.callTool(t.def.name, args), this.spillSink);
99
103
  }
100
104
  catch (e) {
101
105
  return `error calling ${name}: ${e instanceof Error ? e.message : String(e)}`;