@0perator/operator 0.1.339 → 0.1.341

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/cli.js CHANGED
@@ -1882,7 +1882,7 @@ function Root() {
1882
1882
  break;
1883
1883
  }
1884
1884
  s.activateSkill(arg, content);
1885
- sys(`skill '${arg}' activated — its instructions are now injected into the system prompt`);
1885
+ sys(`skill '${arg}' activated — its instructions ride with your next message`);
1886
1886
  break;
1887
1887
  }
1888
1888
  case "whoami":
@@ -75,12 +75,13 @@ const DEFAULTS = {
75
75
  vision: { autostart: false, launchdLabel: "co.0perator.vision", plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist", legacyLabels: ["axe.vision-bot"], url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
76
76
  stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
77
77
  },
78
- // MOA (2026-10-28, James): Dolphin 7B + Cortana propose, Cortana aggregates — both on JL1, reached through the
79
- // 0perator gateway so every signed-in Operator has the same team. settings.moa replaces it wholesale.
78
+ // MOA (2026-10-30, James): gpt-oss-20b + Cortana propose, Cortana aggregates and reads images (its own vision
79
+ // projector) — both on JL1, reached through the 0perator gateway so every signed-in Operator has the same team.
80
+ // Was Dolphin 7B + Cortana (10/28). settings.moa replaces it wholesale.
80
81
  moa: {
81
82
  proposers: [
83
+ { id: "gpt-oss-20b", endpoint: GATEWAY_BASE, model: "gpt-oss-20b" },
82
84
  { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
83
- { id: "dolphin-7b", endpoint: GATEWAY_BASE, model: "dolphin-7b" },
84
85
  ],
85
86
  aggregator: { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
86
87
  },
@@ -2,7 +2,7 @@
2
2
  // text tool-call recovery (toolcalls.ts) and compaction (compaction.ts). Tools and routing are
3
3
  // NOT implemented here — this file depends only on the two interfaces below, which the
4
4
  // kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
5
- import { chat, endpointSlots } from "./aurora.js";
5
+ import { chat, endpointSlots, getOperatorToken, requiresOperatorToken } from "./aurora.js";
6
6
  import { parseToolArgs } from "./json-repair.js";
7
7
  import { buildMessages } from "./messages.js";
8
8
  import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
@@ -540,6 +540,18 @@ function watchRepetition(opts, on) {
540
540
  return w;
541
541
  }
542
542
  /** Runs one user turn to completion: compacts, loops model↔tools ≤maxRounds, self-heals, finalizes. */
543
+ /** A gateway 401/403 with the reason a person can act on: no token was loaded at all (signed out, or the keychain
544
+ * is locked — every SSH session on macOS), versus a token the gateway rejected. */
545
+ export function authError(err, base) {
546
+ const msg = err instanceof Error ? err.message : String(err);
547
+ if (!requiresOperatorToken(base))
548
+ return err instanceof Error ? err : new Error(msg);
549
+ const why = getOperatorToken()
550
+ ? "the gateway rejected this Operator's sign-in token — run `operator auth login` to renew it"
551
+ : "no sign-in token was loaded — run `operator auth login`; over SSH the macOS keychain is locked, so unlock it " +
552
+ "(`security unlock-keychain`) first";
553
+ return new Error(`${msg}\n${why}; or set a failover endpoint that needs no token (settings endpoints.failover)`);
554
+ }
543
555
  export async function runTurn(userInput, conversation, opts) {
544
556
  const softRounds = opts.maxRounds ?? 10;
545
557
  const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
@@ -660,6 +672,7 @@ export async function runTurn(userInput, conversation, opts) {
660
672
  let promptTokensTotal = 0; // prompt tokens PREFILLED, summed across rounds
661
673
  let promptMsTotal = 0; // prefill ms summed across rounds
662
674
  let emptyRetries = 0; // reasoning models sometimes return a "dud" round (no content, no tool calls)
675
+ let authFailedOver = false; // one hop off a gateway that refused our credentials (see the auth branch)
663
676
  let truncRetries = 0; // chunk-write nudges spent recovering a truncated-tool-call 500 (truncatedToolNudge)
664
677
  let truncDispatched = 0; // cut-off calls let through to dispatch after the retry budget; a 2nd means the loop isn't converging → hand back
665
678
  let loadingRetries = 0; // patient waits spent while an endpoint reports it's still (re)loading its model
@@ -730,6 +743,7 @@ export async function runTurn(userInput, conversation, opts) {
730
743
  ceilingTokens: opts.compactionCeilingTokens,
731
744
  minKeepTurns: opts.minKeepTurns,
732
745
  preservedState: opts.preservedState?.(), // the active task list rides with the summary
746
+ pinnedContext: opts.pinnedContext?.(),
733
747
  meter: globalTokenMeter, // SPEC §5: size to THIS endpoint's learned ratio, not chars/4
734
748
  meterKey: endpointKey(ep.base, ep.model),
735
749
  spill: opts.spill, // GW-10-COMPLETE: fitToWindow offloads (re-readable) when the host can write files
@@ -915,9 +929,22 @@ export async function runTurn(userInput, conversation, opts) {
915
929
  opts.onSelfHeal?.("server_error", 1); // footer ↻ — a recovery is in flight
916
930
  continue;
917
931
  }
918
- // Non-retryable: a malformed request (a bad tool call) or bad credentials won't be fixed by
919
- // resending — fail fast rather than spin (that futile-retry storm is what burned minutes).
920
- if (recovery === "bad_request" || recovery === "auth" || selfHealBudget <= 0)
932
+ // Bad credentials: resending to the same gateway never helps, but the owner's failover (a LAN or loopback
933
+ // model that needs no token) can still answer — JL1 over SSH has a locked keychain, so no token loads and
934
+ // the gateway says 401 while Cortana sits on localhost. One hop per turn; then fail with the cause.
935
+ if (recovery === "auth") {
936
+ const next = authFailedOver ? null : opts.router.recover(endpoint, "unavailable");
937
+ if (next) {
938
+ authFailedOver = true;
939
+ endpoint = next;
940
+ opts.onRoute?.(endpoint);
941
+ continue;
942
+ }
943
+ throw authError(err, endpoint.base);
944
+ }
945
+ // Non-retryable: a malformed request (a bad tool call) won't be fixed by resending — fail fast rather
946
+ // than spin (that futile-retry storm is what burned minutes).
947
+ if (recovery === "bad_request" || selfHealBudget <= 0)
921
948
  throw err;
922
949
  const attempt = MAX_SELF_HEAL_PER_TURN - selfHealBudget; // 0-based
923
950
  selfHealBudget -= 1;
@@ -425,7 +425,7 @@ export async function compact(conversation, opts) {
425
425
  // summary embeds specifics in prose); these blocks guarantee nothing critical was dropped.
426
426
  const summaryMsg = {
427
427
  role: "user", // never a 2nd system message — SPEC §1/§5
428
- content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.preservedState ? `\n\n${opts.preservedState}` : ""}`,
428
+ content: `[Compacted summary of ${evicted.length} earlier message(s)]\n${summaryText}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.preservedState ? `\n\n${opts.preservedState}` : ""}${opts.pinnedContext ? `\n\n${opts.pinnedContext}` : ""}`,
429
429
  };
430
430
  // N1 VERIFIED COMPACTION: proof-of-preservation rides with the summary (shared helper now — the
431
431
  // instant/prewritten path in session.ts MUST get the same guarantee, audit-engine §2).
@@ -48,4 +48,12 @@ export function labelDrafts(drafts) {
48
48
  .map((d, i) => `Candidate ${String.fromCharCode(65 + i)} (${d.id}):\n${d.content}`)
49
49
  .join("\n\n");
50
50
  }
51
+ /** The team, as fact, for the aggregator. Without it the model guessed its own members from the fleet notes in the
52
+ * prompt (10/30: it named Aurora and the vision model while only Cortana had answered, Dolphin being down). */
53
+ export function teamLine(proposers, answered, aggregator) {
54
+ const missing = proposers.map((p) => p.id).filter((id) => !answered.includes(id));
55
+ return `This mixture's team: proposers ${proposers.map((p) => p.id).join(", ")}; aggregator ${aggregator}.` +
56
+ (missing.length ? ` Did not answer this turn: ${missing.join(", ")}.` : "") +
57
+ " Asked which models make up the mixture, name exactly these.";
58
+ }
51
59
  export const DEFAULT_AGGREGATOR_PROMPT = "You are given candidate answers from several models. Synthesize the single best, correct, complete answer. Do not mention the candidates.";
@@ -139,7 +139,7 @@ export const BUILTIN_MODELS = [
139
139
  { id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
140
140
  { id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
141
141
  // ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
142
- { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — each turn goes to Cortana + Dolphin 7B (JL1) through the 0perator gateway in parallel, then Cortana writes the answer (settings.moa overrides)" },
142
+ { id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — each turn goes to gpt-oss-20b + Cortana (JL1) through the 0perator gateway in parallel, then Cortana writes the answer and reads any images (settings.moa overrides)" },
143
143
  ];
144
144
  export const OPERATOR_FREE_ACCOUNT = "0perator";
145
145
  export const BYO_PRESETS = {
package/dist/session.js CHANGED
@@ -13,7 +13,7 @@ import { engineRouter } from "./engine/router-adapter.js";
13
13
  import { appendFileSync, mkdirSync } from "node:fs";
14
14
  import { dirname } from "node:path";
15
15
  import { operatorPath } from "./config/home.js";
16
- import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
16
+ import { fanOutProposers, labelDrafts, teamLine, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
17
17
  import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0 observability (KODE_MOA_SHADOW)
18
18
  import { AuroraRouter } from "./router/router.js";
19
19
  import { operatorAgentPersona } from "./config/operator-harness.js";
@@ -246,14 +246,17 @@ function makeSelfStatusTool(facts) {
246
246
  };
247
247
  }
248
248
  // The `skill_activate` / `skill_deactivate` pair — unlike skill_fetch (skill text returned as tool-result
249
- // DATA), activation injects the skill's instructions into the system prompt as a privileged behavioral
250
- // directive for every subsequent turn, until deactivated or replaced. The fetch itself reuses the registry's
251
- // skill_fetch (profile skills first, then hub), so activation accepts any slug skill_fetch does.
249
+ // DATA), activation makes the skill's instructions a standing directive for every subsequent turn, until
250
+ // deactivated or replaced. The directive rides in the conversation, never the system prompt: a system prompt
251
+ // that changes mid-session makes llama.cpp re-read every tool schema and the whole conversation (see
252
+ // Session.activateSkill). The fetch itself reuses the registry's skill_fetch (profile skills first, then hub),
253
+ // so activation accepts any slug skill_fetch does.
254
+ const skillHeader = (name) => `## Active skill: ${name}`;
252
255
  function makeSkillActivateTool(activate) {
253
256
  return {
254
257
  name: "skill_activate",
255
258
  safe: false,
256
- description: "Activate a skill as a system-prompt directive for the rest of the session — to FOLLOW a skill, not just read" +
259
+ description: "Activate a skill as a standing directive for the rest of the session — to FOLLOW a skill, not just read" +
257
260
  " it (that is skill_fetch). One at a time; a new one replaces the last.",
258
261
  parameters: {
259
262
  type: "object",
@@ -274,7 +277,7 @@ function makeSkillDeactivateTool(deactivate) {
274
277
  return {
275
278
  name: "skill_deactivate",
276
279
  safe: true,
277
- description: "Remove the active skill from the system prompt. No-op if no skill is active.",
280
+ description: "Stop following the active skill. No-op if no skill is active.",
278
281
  parameters: { type: "object", properties: {} },
279
282
  run: async () => deactivate(),
280
283
  };
@@ -346,8 +349,9 @@ export class Session {
346
349
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
347
350
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
348
351
  recalled = false;
349
- activeSkillBlock = ""; // capped skill instructions injected into the system prompt
352
+ activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
350
353
  activeSkillName = ""; // name of the active skill (for status display)
354
+ skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
351
355
  // Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
352
356
  // maintains a structured session-memory/summary.md during the session. When compact() fires,
353
357
  // it loads the pre-written summary — /compact went from up to 2 minutes to instant.
@@ -363,7 +367,7 @@ export class Session {
363
367
  // on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
364
368
  globalTokenMeter.setPersistence(operatorPath("token-calibration.json"));
365
369
  // Per-session tool registry: the base set, plus session-scoped tools (skill_activate/skill_deactivate
366
- // are always available since they mutate THIS session's system prompt; spawn_agent/message_agent/
370
+ // are always available since they hold THIS session's active skill; spawn_agent/message_agent/
367
371
  // ask_user only when the shell provides delegate handlers). Both the executor (dispatch) and
368
372
  // localSchemas (what the model sees) are built from the same map, so a tool is advertised iff runnable.
369
373
  const reg = new Map(registry);
@@ -374,13 +378,13 @@ export class Session {
374
378
  const content = await fetchTool.run({ slug: name });
375
379
  if (content.startsWith("error:"))
376
380
  return content;
377
- this.activateSkill(name, content);
378
- return `skill '${name}' activated — its instructions are now injected into the system prompt. Deactivate with skill_deactivate.`;
381
+ return this.activateSkill(name, content);
379
382
  }));
380
383
  reg.set("skill_deactivate", makeSkillDeactivateTool(() => {
381
384
  const was = this.activeSkillName;
382
385
  this.deactivateSkill();
383
- return was ? `skill '${was}' deactivated` : "no skill was active";
386
+ this.skillNote = ""; // this tool result already tells the model
387
+ return was ? `skill '${was}' deactivated — stop following its instructions` : "no skill was active";
384
388
  }));
385
389
  // Flag-gated cloud-agent tools (config/features.ts `cloudAgents`): absent from the base registry, merged in
386
390
  // here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
@@ -498,15 +502,13 @@ export class Session {
498
502
  `commands resolve in the working directory. This is authoritative over any working dir named elsewhere; create ` +
499
503
  `files there unless the owner names another path.${SESSION_CONTEXT_CLOSE}`;
500
504
  }
501
- /** The effective system prompt: the base persona plus any memory recalled this session, plus any
502
- * active skill. Injected as ONE system prompt — never a second system message, which 400s llama.cpp's
503
- * chat template. */
505
+ /** The effective system prompt: the base persona plus any memory recalled this session. Injected as ONE system
506
+ * prompt — never a second system message, which 400s llama.cpp's chat template. An active skill is NOT here
507
+ * (activateSkill). */
504
508
  sys() {
505
509
  let base = this.recallBlock
506
510
  ? (this.systemPrompt ? `${this.systemPrompt}\n\n${this.recallBlock}` : this.recallBlock)
507
511
  : this.systemPrompt;
508
- if (this.activeSkillBlock)
509
- base = (base ?? "") + this.activeSkillBlock;
510
512
  base = (base ?? "") + this.activeModelBlock() + this.sessionContextBlock();
511
513
  if (!this.planMode)
512
514
  return base;
@@ -593,23 +595,39 @@ export class Session {
593
595
  currentThinkMode() {
594
596
  return this.thinkMode;
595
597
  }
596
- /** Activate a skill as a system-prompt-level behavioral directive. The skill's instructions are
597
- * injected into every subsequent turn's system prompt until deactivated. Capped at SKILL_CAP chars
598
- * so a huge skill doesn't crowd working memory. */
598
+ /** Activate a skill as a standing directive until deactivated or replaced; returns the directive. Capped at
599
+ * SKILL_CAP chars so a huge skill doesn't crowd working memory. The system prompt never changes mid-session —
600
+ * doing so made the server re-read tools + conversation on the next request — so the directive rides in the
601
+ * conversation tail instead: as skill_activate's tool result, or (for /skill) on the owner's next message, and
602
+ * after a compaction evicts it, in the summary (pinnedSkill). */
599
603
  activateSkill(name, content) {
600
604
  const capped = content.length > SKILL_CAP
601
605
  ? content.slice(0, SKILL_CAP) + "\n\n[… skill truncated at " + SKILL_CAP + " chars]"
602
606
  : content;
603
- this.activeSkillBlock = `\n\n## Active skill: ${name}\nFollow these instructions for this task:\n\n${capped}`;
607
+ const replaces = this.activeSkillName && this.activeSkillName !== name ? ` It replaces skill '${this.activeSkillName}' — stop following that one.` : "";
608
+ this.activeSkillBlock = `${skillHeader(name)}\nFollow these instructions for this task until skill_deactivate.${replaces}\n\n${capped}`;
604
609
  this.activeSkillName = name;
610
+ this.skillNote = "";
611
+ return this.activeSkillBlock;
605
612
  }
606
613
  deactivateSkill() {
614
+ if (this.activeSkillName)
615
+ this.skillNote = `[Skill '${this.activeSkillName}' is no longer active — stop following its instructions.]`;
607
616
  this.activeSkillBlock = "";
608
617
  this.activeSkillName = "";
609
618
  }
610
619
  currentSkill() {
611
620
  return this.activeSkillName || null;
612
621
  }
622
+ /** The active skill's directive when the conversation no longer carries it (never delivered, or compacted
623
+ * away); undefined otherwise. */
624
+ pinnedSkill() {
625
+ if (!this.activeSkillBlock)
626
+ return undefined;
627
+ const header = skillHeader(this.activeSkillName);
628
+ const carried = this.convo.all.some((m) => typeof m.content === "string" && m.content.includes(header));
629
+ return carried ? undefined : this.activeSkillBlock;
630
+ }
613
631
  /** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
614
632
  health() {
615
633
  return health(this.inner.base);
@@ -712,6 +730,7 @@ export class Session {
712
730
  systemPrompt: this.sys(),
713
731
  summarize: this.summarize,
714
732
  preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
733
+ pinnedContext: this.activeSkillBlock || undefined,
715
734
  minKeepTurns: 2,
716
735
  tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
717
736
  meter: globalTokenMeter,
@@ -744,7 +763,7 @@ export class Session {
744
763
  // render-side and mechanical — the "instant" property is untouched (microseconds, zero calls).
745
764
  const summaryMsg = {
746
765
  role: "user",
747
- content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
766
+ content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.pinnedContext ? `\n\n${opts.pinnedContext}` : ""}`,
748
767
  };
749
768
  const kept = this.convo.all.slice(cutIndex);
750
769
  this.convo.replaceAll([summaryMsg, ...kept]);
@@ -1191,7 +1210,7 @@ export class Session {
1191
1210
  const aggRouter = this.wrap(new AuroraRouter([
1192
1211
  { name: moa.aggregator.id, base: endpointBase(moa.aggregator.endpoint), model: moa.aggregator.model, ctxLimit: this.inner.ctxLimit() },
1193
1212
  ]));
1194
- const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
1213
+ const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n${teamLine(moa.proposers, survivors.map((d) => d.id), moa.aggregator.id)}\n\n${labelDrafts(drafts)}`;
1195
1214
  return this.execute(text, h, aggRouter, aggSys, moa.aggregator.id);
1196
1215
  }
1197
1216
  /** Fire scout (settings.fastStart) with a bounded, independent timeout — never the real turn's own
@@ -1274,6 +1293,10 @@ export class Session {
1274
1293
  // for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
1275
1294
  // message itself, so everything from here on is this turn's.
1276
1295
  const convoStart = this.convo.all.length;
1296
+ const carry = [this.skillNote, this.pinnedSkill()].filter(Boolean).join("\n\n");
1297
+ this.skillNote = "";
1298
+ if (carry)
1299
+ text = `${carry}\n\n${text}`;
1277
1300
  try {
1278
1301
  const res = await runTurn(text, this.convo, {
1279
1302
  router,
@@ -1282,6 +1305,7 @@ export class Session {
1282
1305
  spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
1283
1306
  systemPrompt: sys,
1284
1307
  summarize: this.summarize,
1308
+ pinnedContext: () => this.activeSkillBlock || undefined, // a summary is a rewrite anyway: the skill rides it
1285
1309
  preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
1286
1310
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
1287
1311
  liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.339",
3
+ "version": "0.1.341",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",