@0perator/operator 0.1.282 → 0.1.284

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.
@@ -49,12 +49,14 @@ export async function runHeadless(settings, prompt, opts = {}) {
49
49
  reporter.event("done", { reason: res.reason, turns: res.turns, toolCalls: res.toolCalls });
50
50
  if (res.lastContent)
51
51
  reporter.line(res.lastContent);
52
+ await session.flushRouteShadow(); // MOA phase-0: the last turn's shadow record must not die with the process
52
53
  return res.reason === "error" ? 1 : res.reason === "interrupted" ? 130 : 0;
53
54
  }
54
55
  const outcome = await session.send(prompt, handlers);
55
56
  reporter.event("done", { rounds: outcome.rounds, toolCalls: outcome.toolCalls, interrupted: outcome.interrupted, durationMs: Math.round(outcome.durationMs ?? 0) });
56
57
  if (outcome.content)
57
58
  reporter.line(outcome.content);
59
+ await session.flushRouteShadow(); // MOA phase-0: headless one-shot exits before fire-and-forget would land
58
60
  return outcome.interrupted ? 130 : 0;
59
61
  }
60
62
  catch (e) {
@@ -12,7 +12,8 @@
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
+ import { applySRFTMask } from "../flywheel/srft.js"; // PURE half — node-free, neutral-graph safe
16
+ // runMutationCheck needs node:fs/child_process — resolved lazily via nodeImport() inside verifyMutation.
16
17
  const nodeImport = (m) => import(m);
17
18
  // Infer the task type from a free-form objective when the caller didn't declare one — keeps the tool
18
19
  // usable with just a task string while still selecting the right schema + verify + lane.
@@ -257,6 +258,7 @@ export async function verifyFinalAnswer(value, type, cwd, opts) {
257
258
  * git stash / revert the turn's diff in a temp worktree. If the suite still passes, the tests don't
258
259
  * test the change (the "37/37 file-exists" class caught by behavior, not regex). */
259
260
  export async function verifyMutation(cwd, verifyCommand, diffSha) {
261
+ const { runMutationCheck } = await nodeImport("../flywheel/processor.js"); // node-only module: never statically bundled (iOS neutral graph)
260
262
  return runMutationCheck(cwd, verifyCommand, diffSha);
261
263
  }
262
264
  /** Apply SRFT step masking to a graded trajectory. Marks each step as productive (keep in loss) or
@@ -3,49 +3,11 @@
3
3
  import { mkdirSync, appendFileSync } from "node:fs";
4
4
  import { screenRecord } from "./secret-gate.js"; // HV3-N1: the training stream must never carry secrets
5
5
  import { join, dirname } from "node:path";
6
- /** Apply SRFT-style step masking to a trajectory.
7
- * Marks each step as productive (keep in loss) or harmful (mask from loss).
8
- * A step is harmful if:
9
- * - It's a tool call that returned an error
10
- * - It's marked as a repetition loop guard
11
- * - It's a parse_fallback lint
12
- * - It triggered a forced redirect
13
- */
14
- export function applySRFTMask(trajectory) {
15
- const mask = [];
16
- let hasErrors = trajectory.stopReason === "repetition" || trajectory.unverified === true;
17
- let isHarmful = hasErrors;
18
- for (let i = 0; i < (trajectory.steps?.length ?? 0); i++) {
19
- const step = trajectory.steps[i];
20
- if (!step) {
21
- mask.push(true); // default: include unknown steps
22
- continue;
23
- }
24
- // Mask tool errors — the model shouldn't learn from failed tool calls
25
- if (step.role === "tool" && step.content?.includes("error") && step.content?.includes("exit")) {
26
- isHarmful = true;
27
- }
28
- // Mask steps that are part of a repetition loop
29
- if (trajectory.stopReason === "repetition" && isHarmful) {
30
- mask.push(false); // mask this step
31
- }
32
- else {
33
- mask.push(true);
34
- }
35
- }
36
- // If the trajectory is graded but has no explicit steps, mask the last few rounds
37
- // (likely the failure tail)
38
- if ((trajectory.steps?.length ?? 0) === 0 && trajectory.rounds > 3) {
39
- const tailRounds = Math.min(trajectory.rounds - 3, 5);
40
- for (let i = 0; i < tailRounds; i++) {
41
- mask.push(false);
42
- }
43
- for (let i = tailRounds; i < trajectory.rounds; i++) {
44
- mask.push(true);
45
- }
46
- }
47
- return mask.length > 0 ? mask : new Array(trajectory.rounds).fill(true);
48
- }
6
+ // ---------------------------------------------------------------------------
7
+ // SRFT (Step Rejection Fine-Tuning) — per-step masking for trajectories
8
+ // ---------------------------------------------------------------------------
9
+ import { applySRFTMask } from "./srft.js";
10
+ export { applySRFTMask } from "./srft.js"; // one import surface for existing consumers
49
11
  /** Run a mutation check on a verified turn.
50
12
  * Stashes the worktree, reverts the diff, runs verify_command.
51
13
  * If the suite still passes, the tests are vacuous (they don't test the change). */
@@ -0,0 +1,43 @@
1
+ /** Apply SRFT-style step masking to a trajectory.
2
+ * Marks each step as productive (keep in loss) or harmful (mask from loss).
3
+ * A step is harmful if:
4
+ * - It's a tool call that returned an error
5
+ * - It's marked as a repetition loop guard
6
+ * - It's a parse_fallback lint
7
+ * - It triggered a forced redirect
8
+ */
9
+ export function applySRFTMask(trajectory) {
10
+ const mask = [];
11
+ let hasErrors = trajectory.stopReason === "repetition" || trajectory.unverified === true;
12
+ let isHarmful = hasErrors;
13
+ for (let i = 0; i < (trajectory.steps?.length ?? 0); i++) {
14
+ const step = trajectory.steps[i];
15
+ if (!step) {
16
+ mask.push(true); // default: include unknown steps
17
+ continue;
18
+ }
19
+ // Mask tool errors — the model shouldn't learn from failed tool calls
20
+ if (step.role === "tool" && step.content?.includes("error") && step.content?.includes("exit")) {
21
+ isHarmful = true;
22
+ }
23
+ // Mask steps that are part of a repetition loop
24
+ if (trajectory.stopReason === "repetition" && isHarmful) {
25
+ mask.push(false); // mask this step
26
+ }
27
+ else {
28
+ mask.push(true);
29
+ }
30
+ }
31
+ // If the trajectory is graded but has no explicit steps, mask the last few rounds
32
+ // (likely the failure tail)
33
+ if ((trajectory.steps?.length ?? 0) === 0 && trajectory.rounds > 3) {
34
+ const tailRounds = Math.min(trajectory.rounds - 3, 5);
35
+ for (let i = 0; i < tailRounds; i++) {
36
+ mask.push(false);
37
+ }
38
+ for (let i = tailRounds; i < trajectory.rounds; i++) {
39
+ mask.push(true);
40
+ }
41
+ }
42
+ return mask.length > 0 ? mask : new Array(trajectory.rounds).fill(true);
43
+ }
@@ -0,0 +1,61 @@
1
+ // MOA phase-0 route shadow — pure observability for the mixture-of-agents dispatch plan.
2
+ // A gate-not-voice classifier labels the turn's opening request into one of 9 route labels;
3
+ // we log (label, model-that-actually-ran, cost) so a week of real traffic answers the ONLY
4
+ // question that decides lane placement: what share of turns is actually CHAT/SUMMARIZE/WRITE
5
+ // (fast lane) vs CODE/SECURITY (heavy/top). NOTHING here changes routing, blocks a turn, or
6
+ // leaves the machine: env-gated (KODE_MOA_SHADOW), fire-and-forget, every failure swallowed.
7
+ //
8
+ // The classifier is deliberately strict — parseRouteLabel accepts ONE word and nothing else;
9
+ // prose answers ("This is a coding request") are null, not a guess. That is the same contract
10
+ // the Alfred-class 186M gate will ship under: a gate that rambles is a gate that lies.
11
+ // Node-free by construction (plain fetch + caller-supplied file path) — safe for any graph.
12
+ export const ROUTE_LABELS = ["CHAT", "OPERATE", "VISION", "CODE", "DATA", "SECURITY", "WRITE", "SUMMARIZE", "MATH"];
13
+ /** Planned lane per label (MOA design, 2026-10-12): fast=small resident model, operate=tool-format
14
+ * model, heavy=aurora-class, top=true-MoA fanout (SECURITY only for now), vision=media surface. */
15
+ export const TIER_BY_LABEL = {
16
+ CHAT: "fast", SUMMARIZE: "fast", WRITE: "fast",
17
+ OPERATE: "operate",
18
+ CODE: "heavy", DATA: "heavy", MATH: "heavy",
19
+ SECURITY: "top",
20
+ VISION: "vision",
21
+ };
22
+ /** Teacher prompt: 9 labels, one word, nothing else. Kept tiny on purpose — the shadow call is
23
+ * billed to the session's own model and must stay a rounding error (~1 completion token). */
24
+ export function shadowPrompt(text) {
25
+ const head = text.slice(0, 400);
26
+ return `Classify the REQUEST below into exactly one word: CHAT, OPERATE, VISION, CODE, DATA, SECURITY, WRITE, SUMMARIZE, or MATH.
27
+ Rules: CODE=writing/fixing code. OPERATE=running tools/system actions. WRITE=prose drafting. SUMMARIZE=condensing. DATA=tables/analytics. SECURITY=threats/vulns/auth. MATH=numeric/formal. VISION=images. CHAT=everything else.
28
+ Output ONE word, nothing else.
29
+
30
+ REQUEST: """${head}"""`;
31
+ }
32
+ /** STRICT parse: one word only (punctuation/spacing tolerated), case-insensitive. Multi-word or
33
+ * unknown answers are refusals to gate — return null, never guess. */
34
+ export function parseRouteLabel(out) {
35
+ const w = out.trim().replace(/[.!?,;:"'`]/g, "").toUpperCase();
36
+ if (!w || /\s/.test(w))
37
+ return null;
38
+ return ROUTE_LABELS.includes(w) ? w : null;
39
+ }
40
+ /** Fire-and-forget one shadow record for a completed turn. `classify` is injected so tests run
41
+ * offline and production can use any teacher endpoint (session wires aurora chat). Never throws;
42
+ * never awaits longer than the caller's own abort policy — the whole point is that observability
43
+ * cannot degrade the thing it observes. */
44
+ export async function routeShadowTurn(opts) {
45
+ if (!opts.enabled)
46
+ return;
47
+ const t0 = Date.now();
48
+ try {
49
+ const raw = await opts.classify(opts.text);
50
+ const label = parseRouteLabel(raw);
51
+ const ev = {
52
+ ts: new Date().toISOString(), label, tier: label ? TIER_BY_LABEL[label] : null,
53
+ model: opts.model, promptTokens: opts.promptTokens, genTokens: opts.genTokens,
54
+ turnMs: opts.turnMs, classifyMs: Date.now() - t0,
55
+ };
56
+ await opts.append(JSON.stringify(ev));
57
+ }
58
+ catch {
59
+ /* shadow telemetry is allowed to die in silence — never into a turn */
60
+ }
61
+ }
package/dist/session.js CHANGED
@@ -12,6 +12,7 @@ import { appendFileSync, mkdirSync } from "node:fs";
12
12
  import { dirname } from "node:path";
13
13
  import { operatorPath } from "./config/home.js";
14
14
  import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
15
+ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
15
16
  import { AuroraRouter } from "./router/router.js";
16
17
  import { operatorAgentPersona } from "./config/operator-harness.js";
17
18
  import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
@@ -271,6 +272,12 @@ export class Session {
271
272
  wantRecall;
272
273
  recallBlock = ""; // memory recalled on the first turn, folded into the system prompt thereafter
273
274
  sessionTokensTotal = 0; // cumulative prefill+output tokens across all turns (Claude-Code-style session total)
275
+ _shadowPending = Promise.resolve(); // MOA phase-0: in-flight route-shadow record (never rejects)
276
+ /** Await the in-flight route-shadow record before a short-lived process exits — fire-and-forget alone
277
+ * would drop the last turn's telemetry silently. Interactive sessions need not call this (the process
278
+ * outlives the 15s-abort classification); `operator run` headless MUST. Safe to call anytime, twice,
279
+ * from anywhere: the pending promise is swapped and failures were already swallowed by the module. */
280
+ async flushRouteShadow() { const p = this._shadowPending; this._shadowPending = Promise.resolve(); await p; }
274
281
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
275
282
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
276
283
  recalled = false;
@@ -917,6 +924,37 @@ export class Session {
917
924
  turnContinuation: { enabled: process.env.KODE_TURN_CONTINUATION !== "0" && !this.planMode },
918
925
  });
919
926
  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 });
927
+ // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): ON by default, opt out with
928
+ // KODE_MOA_SHADOW=0. Labels
929
+ // the turn with the gate's own 9-label contract and appends {label, model-that-ran, cost} to
930
+ // ~/.axe/operator/route-shadow/<date>.jsonl. The classifier runs as a BACKGROUND-priority call on
931
+ // the endpoint gate (a main turn always outranks it) with a 15s abort, and routeShadowTurn swallows
932
+ // every failure — observability that can degrade the observed thing is not observability.
933
+ if (process.env.KODE_MOA_SHADOW !== "0") {
934
+ const prof = findModel(this.registry, this.modelId);
935
+ const shadowBase = prof?.endpoint ? endpointBase(prof.endpoint) : undefined;
936
+ if (shadowBase) {
937
+ const shadowTok = prof?.byo ? getByoToken(prof.byo) : undefined;
938
+ const shadowModel = prof?.model ?? this.modelId;
939
+ this._shadowPending = routeShadowTurn({
940
+ enabled: true,
941
+ text,
942
+ model: this.currentModel(),
943
+ promptTokens: res.promptTokens,
944
+ genTokens: res.tokens,
945
+ turnMs: Math.round(performance.now() - _t0),
946
+ classify: async (t) => (await chat([{ role: "user", content: shadowPrompt(t) }], {
947
+ base: shadowBase, model: shadowModel, token: shadowTok, transport: prof?.transport,
948
+ maxTokens: 8, temperature: 0, background: true, signal: AbortSignal.timeout(15000),
949
+ })).content,
950
+ append: async (line) => {
951
+ const p = operatorPath("route-shadow", `${new Date().toISOString().slice(0, 10)}.jsonl`);
952
+ mkdirSync(dirname(p), { recursive: true, mode: 0o700 });
953
+ appendFileSync(p, line + "\n", { encoding: "utf8", mode: 0o600 });
954
+ },
955
+ });
956
+ }
957
+ }
920
958
  this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
921
959
  // Instant compaction: feed token counts to the rolling summarizer. When a round ends without
922
960
  // tool calls and we've crossed the threshold, the summarizer triggers a background summary.
@@ -17,10 +17,14 @@ export async function documentGenerate(args) {
17
17
  return "error: document_generate needs `content` (markdown or plain text)";
18
18
  const title = String(args.title ?? "").trim();
19
19
  const subtitle = String(args.subtitle ?? "").trim();
20
- const PDFDocument = (await import("pdfkit")).default;
21
- const { marked } = await import("marked");
22
- const fs = await import("node:fs");
23
- const path = await import("node:path");
20
+ // VARIABLE specifiers: esbuild must not statically resolve these (node-only deps; a literal here drags
21
+ // pdfkit + node builtins into the iOS neutral engine bundle via registry.ts's static tool catalogue —
22
+ // the exact breakage test/neutral-graph.test.mts now catches at suite time). Same idiom as nodeImport.
23
+ const nodeReq = (m) => import(m);
24
+ const PDFDocument = (await nodeReq("pdfkit")).default;
25
+ const { marked } = await nodeReq("marked");
26
+ const fs = await nodeReq("node:fs");
27
+ const path = await nodeReq("node:path");
24
28
  const { operatorPath } = await import("../config/home.js");
25
29
  // Resolve the output path: honor an explicit `out`, else a durable attachments copy.
26
30
  let out = String(args.out ?? "").trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.282",
3
+ "version": "0.1.284",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",