@0perator/operator 0.1.338 → 0.1.340

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.
@@ -191,7 +191,7 @@ export function agentCliToolDescription(opts = {}) {
191
191
  const installed = presets.filter(isInstalled);
192
192
  const notInstalled = presets.filter((p) => !isInstalled(p)).map((p) => p.id);
193
193
  const list = installed.length ? installed.map((p) => `"${p.id}" (${p.label})`).join(", ") : "NONE are installed on this machine right now — the call will return each one's install hint";
194
- return `Delegate ONE self-contained task to a local AGENT CLI — a separate command-line coding agent (Cursor Agent, Claude Code, OpenAI Codex, …) that runs its OWN autonomous tool-loop in this workspace and reports back its final answer (blocks until it finishes). This is a SECOND delegation path alongside delegate_task: delegate_task runs a subtask on another MODEL inside Operator's own engine, whereas delegate_to_agent shells out to a whole external agent that edits files and runs shell commands by itself. INSTALLED agents you can pick now (\`agent\`): ${list}.${notInstalled.length ? ` Known but NOT installed here (don't pick these): ${notInstalled.join(", ")}.` : ""} \`task\` must be fully self-contained — the CLI has NO memory of this conversation and cannot ask questions; put every path, constraint and the exact deliverable in it. Optional \`model\` picks the CLI's underlying model. AUTONOMY/SAFETY: the delegate runs with FULL WRITE + SHELL access under the owner's environment and will modify the workspace and run commands on its own, so scope the task tightly to work you want done autonomously. If the chosen agent isn't installed the call fails with its exact install hint — it never spawns blindly.`;
194
+ return `Delegate ONE self-contained task to a local AGENT CLI — an external coding agent that runs its OWN tool loop in this workspace — and get its final answer (blocks until it finishes). Unlike delegate_task (another MODEL inside Operator), it edits files and runs commands by itself with FULL WRITE + SHELL access under the owner's environment, so scope the task tightly. INSTALLED agents you can pick now (\`agent\`): ${list}.${notInstalled.length ? ` Known but NOT installed here (don't pick these): ${notInstalled.join(", ")}.` : ""} \`task\` must be fully self-contained — the CLI has NO memory of this conversation and cannot ask questions. Optional \`model\` picks the CLI's model. An agent that isn't installed fails with its install hint.`;
195
195
  }
196
196
  const CAPTURE_CAP = 4 * 1024 * 1024; // in-memory stdout/stderr ceiling; the executor's capToolResult spills large results to disk downstream
197
197
  /** Spawn the CLI in its own process group, capture stdout/stderr, enforce the timeout, and on timeout kill
@@ -11,7 +11,7 @@
11
11
  // builtins and the node-bound session factory load lazily via the nodeImport idiom (same as autonomy/cron.ts).
12
12
  import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
13
  import { MemoryStore } from "../memory/index.js";
14
- import { delegateBrief } from "../engine/grandmaster.js";
14
+ import { delegateBrief, inferType } from "../engine/grandmaster.js";
15
15
  const nodeImport = (m) => import(/* @vite-ignore */ m);
16
16
  /** Model a delegation lands on when the planner names none — the fast local tier. */
17
17
  export const DEFAULT_DELEGATE_MODEL = "scout";
@@ -154,6 +154,7 @@ export async function runDelegateTask(args, deps = defaultDeps) {
154
154
  let session;
155
155
  try {
156
156
  session = await deps.createSession(deriveDelegateSettings(settings, profile, auroraOverride), {
157
+ role: inferType(task), // the child runs as a role (prompt + scoped tools), not a clone of the owner's session
157
158
  extra: {
158
159
  sessionId: id,
159
160
  memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
@@ -15,6 +15,7 @@ function handlersFor(reporter, json, prompt = "") {
15
15
  const session = `headless-${process.pid}`;
16
16
  return {
17
17
  onRoute: (label, ctxPct) => reporter.event("route", { route: label, ctxPct }),
18
+ onServed: (s) => reporter.event("fallback", { from: s.fallbackFrom, servedBy: s.backend ?? null }), // the selected model was down; another box answered
18
19
  onAutoContinue: (round) => reporter.event("auto_continue", { round }),
19
20
  onSelfHeal: (kind, attempt) => reporter.event("self_heal", { kind, attempt }),
20
21
  onToolBatch: (events, durationMs) => {
@@ -6,7 +6,8 @@ import { randomUUID } from "node:crypto";
6
6
  import { Session } from "../session.js";
7
7
  import { AuroraRouter } from "../router/router.js";
8
8
  import { buildMemory } from "../memory/providers.js";
9
- import { composeSystemPrompt } from "../config/persona.js";
9
+ import { composeSystemPrompt, subagentSystemPrompt } from "../config/persona.js";
10
+ import { SUBAGENT_ROLES } from "../engine/grandmaster.js";
10
11
  import { ensureScratchDir } from "../config/scratch.js";
11
12
  import { modelCtxFor, leanHarnessFor, DEFAULT_MODEL_ID } from "../router/models.js";
12
13
  import { compactionThreshold, compactionCeilingTokens, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
@@ -24,12 +25,22 @@ export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
24
25
  const lean = leanHarnessFor(settings.activeModel, settings.models); // small-ctx OR a weak big-ctx model (leanPersona) → trim persona + drop heavy memory/handoff
25
26
  return composeSystemPrompt({ settings, cwd, ctxTokens, lean, interactive: false });
26
27
  }
28
+ const ROLE_NAMES = ["research", "search", "review", "plan", "code-edit", "generic"];
29
+ /** KODE_SUBAGENT_ROLE, when it names a role. */
30
+ export function envSubagentRole(env = process.env) {
31
+ const r = (env.KODE_SUBAGENT_ROLE ?? "").trim();
32
+ return ROLE_NAMES.includes(r) ? r : undefined;
33
+ }
27
34
  /** Construct a headless Session from settings. Unattended runs get NO ask_user handler (there's no owner
28
35
  * to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
29
36
  * MCP tool set directly. Permissions default to the owner's configured policy. */
30
37
  export function createAutonomySession(settings, opts = {}) {
38
+ const role = opts.role ?? envSubagentRole();
31
39
  const session = new Session({
32
- systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
40
+ systemPrompt: role
41
+ ? subagentSystemPrompt({ cwd: opts.cwd ?? process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), type: role })
42
+ : buildHeadlessSystemPrompt(settings, opts.cwd),
43
+ ...(role ? { toolAllow: SUBAGENT_ROLES[role].tools, ...(SUBAGENT_ROLES[role].maxRounds ? { maxRoundsHard: SUBAGENT_ROLES[role].maxRounds } : {}) } : {}),
33
44
  router: buildRouterFromSettings(settings),
34
45
  memory: buildMemory(settings.memory), // headless sessions get the same provider-layer memory surface
35
46
  cwd: opts.cwd,
@@ -1,4 +1,4 @@
1
- import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, } from "../engine/grandmaster.js";
1
+ import { buildBrief, inferType, routeLane, extractFinalAnswer, repairPrompt, verifyFinalAnswer, partialReport, } from "../engine/grandmaster.js";
2
2
  import { createWorktree, finalizeWorktree } from "./worktree.js";
3
3
  const RECENT_STEPS = 5; // tool steps kept per agent for the live view (older ones scroll off)
4
4
  const THOUGHT_MAX = 160; // chars of the latest reasoning snippet retained (tail)
@@ -124,11 +124,11 @@ export class BackgroundAgents {
124
124
  * "no background job bg1", concluded the sub-agent had been "evicted", and re-spawned a duplicate onto
125
125
  * the one shared endpoint. Same-looking ids in two different registries was the whole bug; disjoint
126
126
  * namespaces make that specific confusion structurally impossible, not just better-worded. */
127
- spawn(task) {
127
+ spawn(task, role) {
128
128
  if (this.inFlight() >= this.maxConcurrent + this.maxQueued)
129
129
  return "";
130
130
  const id = `agent-${++this.seq}`;
131
- const type = inferType(task);
131
+ const type = role ?? inferType(task);
132
132
  const brief = buildBrief({ objective: task, type }, process.cwd());
133
133
  const lane = routeLane(brief, { type });
134
134
  const label = summarizeTask(task);
@@ -191,8 +191,9 @@ export class BackgroundAgents {
191
191
  return;
192
192
  } // progressed → not stalled
193
193
  const mins = Math.round(this.stallTimeoutMs / 60_000);
194
+ const snap = (typeof a.session?.snapshot === "function" ? a.session.snapshot() : []);
194
195
  this.stop(id);
195
- this.onDone(a.info, `[${id} stopped: no progress for ${mins}m (stalled or a hung request) — any partial result above may be incomplete]`);
196
+ this.onDone(a.info, partialReport(snap, `${id} stopped: no progress for ${mins}m (stalled or a hung request) after ${a.info.round ?? 0} rounds`));
196
197
  }, Math.max(100, delay));
197
198
  timer.unref?.();
198
199
  const entry = this.agents.get(id);
@@ -225,7 +226,7 @@ export class BackgroundAgents {
225
226
  const cwd = wt?.dir;
226
227
  let session;
227
228
  try {
228
- session = this.makeSession(cwd);
229
+ session = this.makeSession(cwd, type);
229
230
  }
230
231
  catch (e) {
231
232
  // makeSession is a caller-supplied factory (a real `new Session(...)`, not just an object literal) —
@@ -460,8 +461,9 @@ export class BackgroundAgents {
460
461
  if (!a || (a.info.status !== "working" && a.info.status !== "queued"))
461
462
  return false;
462
463
  const info = a.info;
464
+ const snap = (typeof a.session?.snapshot === "function" ? a.session.snapshot() : []);
463
465
  this.stop(id);
464
- this.onDone(info, "[stopped by user]");
466
+ this.onDone(info, snap.length ? partialReport(snap, `${id} stopped by request after ${info.round ?? 0} rounds`) : "[stopped by user]");
465
467
  return true;
466
468
  }
467
469
  /** stop_agent with no id (or "all"): stop EVERY currently running or queued sub-agent. Returns the ids
package/dist/cli.js CHANGED
@@ -27,7 +27,8 @@ import { loadSettings, saveSettings, compactionThreshold, compactionCeilingToken
27
27
  import { resolveSeat } from "./auth/identity.js";
28
28
  import { PermissionPolicy } from "./permissions/index.js";
29
29
  import { caps } from "./ui/capabilities.js";
30
- import { composeSystemPrompt, appendMemory } from "./config/persona.js";
30
+ import { composeSystemPrompt, appendMemory, subagentSystemPrompt } from "./config/persona.js";
31
+ import { SUBAGENT_ROLES } from "./engine/grandmaster.js";
31
32
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
32
33
  import { ensureOperatorHome } from "./config/scaffold.js";
33
34
  import { listLocalSkills } from "./config/skills-index.js";
@@ -673,11 +674,11 @@ function Root() {
673
674
  // sub-agent can't spawn more (no fork bombs). BackgroundAgents itself is the single source of truth
674
675
  // for the cap (running + queued) — it refuses ("") past it, so there's exactly one number to keep in
675
676
  // sync, not a second constant here that can drift from the manager's own.
676
- spawnAgent: (task) => {
677
+ spawnAgent: (task, role) => {
677
678
  const mgr = bgRef.current;
678
679
  if (!mgr)
679
680
  return "background manager not ready yet — retry in a moment";
680
- const id = mgr.spawn(task);
681
+ const id = mgr.spawn(task, role);
681
682
  if (!id)
682
683
  return mgr.capacityLine();
683
684
  // Deliberately does NOT invite polling — a prior wording ("watch its ... time") read as "you can
@@ -741,43 +742,57 @@ function Root() {
741
742
  return stopped.length ? `stopped ${stopped.length} sub-agent(s): ${stopped.join(", ")}.` : "no running or queued sub-agents to stop.";
742
743
  }
743
744
  return mgr.requestStop(id)
744
- ? `stopped ${id} — a "[stopped by user]" note replaces its result.`
745
+ ? `stopped ${id} — its partial findings (notes, sources read) arrive as its report at the start of your next turn.`
745
746
  : `${id} isn't a running or queued sub-agent (already finished, unknown, or never existed) — nothing to stop.`;
746
747
  },
747
748
  });
748
749
  }
749
750
  const session = sessionRef.current;
750
751
  const [ctxPin, setCtxPin] = useState(() => session.contextPin()); // the footer's "ctx 600K" — the pin the engine took, undefined = auto
751
- // Background sub-agents run on their own Session against the same single Aurora 1M endpoint as the
752
- // foreground — one model, one context tier.
752
+ // Background sub-agents run on their own Session with a ROLE (engine/grandmaster.ts SUBAGENT_ROLES): a role prompt
753
+ // and role-scoped tools instead of a clone of this session (design: _ai-docs/design/2026-10-30-subagent-experts-
754
+ // and-capability-catalog.md). The model is settings.autonomy.subagentModel when set, else the Aurora chain.
755
+ const subagentModel = settings.autonomy?.subagentModel?.trim() || undefined;
753
756
  const bgRef = useRef(null);
754
757
  if (!bgRef.current) {
755
- bgRef.current = new BackgroundAgents((cwd) => new Session({
756
- systemPrompt: SYSTEM_PROMPT,
757
- router: new AuroraRouter(buildEndpointChain(settings)), // same multi-tier self-heal chain as the foreground
758
- memory: buildMemory(settings.memory), // sub-agents share the same provider-layer memory surface
759
- maxTokens: settings.maxTokens,
760
- maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling also bounds a sub-agent's spend
761
- loopGuard: settings.loopGuard,
762
- hooks: settings.hooks, // sub-agents are gated by the same hooks (e.g. git-safety)
763
- maxRoundsHard: 50, // a focused delegated sub-agent that hits 50 rounds isn't converging — cap it well below the foreground's 200 so a review/fix agent can't run away to round 40+ burning the shared Aurora (seen live 09-26)
764
- contextPin: sessionRef.current?.contextPin() ?? settings.contextPin, // a sub-agent runs on the owner's current window choice, not the full served one
765
- background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
766
- cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
767
- temperature: settings.temperature,
768
- // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
769
- // denied outright. (No-op when computer control is off.) Everything else runs as normal.
770
- permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
771
- eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
772
- }), throttle(() => setBgAgents(bgRef.current.list()), 90), // coalesce per-update churn: a 3+ agent swarm streaming at once would otherwise redraw the whole frame dozens×/s (flicker). Final state lands via the immediate setBgAgents on the done path below.
758
+ bgRef.current = new BackgroundAgents((cwd, type) => {
759
+ const role = type ?? "generic";
760
+ const child = new Session({
761
+ systemPrompt: subagentSystemPrompt({ cwd: cwd ?? process.cwd(), ctxTokens: modelCtxFor(subagentModel ?? settings.activeModel, settings.models), type: role }),
762
+ toolAllow: SUBAGENT_ROLES[role]?.tools,
763
+ router: new AuroraRouter(buildEndpointChain(settings)), // same multi-tier self-heal chain as the foreground
764
+ memory: buildMemory(settings.memory), // sub-agents share the same provider-layer memory surface
765
+ maxTokens: settings.maxTokens,
766
+ maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling also bounds a sub-agent's spend
767
+ loopGuard: settings.loopGuard,
768
+ hooks: settings.hooks, // sub-agents are gated by the same hooks (e.g. git-safety)
769
+ maxRoundsHard: SUBAGENT_ROLES[role]?.maxRounds ?? 50, // role cap (research 20: past it the final-answer repair round makes it answer with what it has); otherwise a focused delegated sub-agent that hits 50 rounds isn't converging — cap it well below the foreground's 200 so a review/fix agent can't run away to round 40+ burning the shared Aurora (seen live 09-26)
770
+ contextPin: sessionRef.current?.contextPin() ?? settings.contextPin, // a sub-agent runs on the owner's current window choice, not the full served one
771
+ background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
772
+ cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
773
+ temperature: settings.temperature,
774
+ // Sub-agents may NOT drive the computer: they have no approval prompt, so any computer_* call is
775
+ // denied outright. (No-op when computer control is off.) Everything else runs as normal.
776
+ permissions: settings.computer.enabled ? { mode: "bypass", rules: computerDenyRules } : undefined,
777
+ eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
778
+ });
779
+ if (subagentModel) {
780
+ const r = child.setModel(subagentModel);
781
+ if (!r.ok)
782
+ console.error(`sub-agent model "${subagentModel}" not usable (${r.error ?? "unknown"}) — staying on the Aurora chain`);
783
+ }
784
+ return child;
785
+ }, throttle(() => setBgAgents(bgRef.current.list()), 90), // coalesce per-update churn: a 3+ agent swarm streaming at once would otherwise redraw the whole frame dozens×/s (flicker). Final state lands via the immediate setBgAgents on the done path below.
773
786
  (agent, result) => {
774
787
  queueAgentReport(agent, result); // the MODEL gets the report at the start of the next turn (an idle session wakes for it); the screen line below is for the owner
775
788
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
776
789
  setBgAgents(bgRef.current.list());
777
- }, settings.endpoints.aurora.model, // model name recorded on each child for UI surfacing (grandmaster §5)
790
+ }, subagentModel ?? settings.endpoints.aurora.model, // model name recorded on each child for UI surfacing (grandmaster §5)
778
791
  () => setTasks(getAgentTasks()));
779
792
  }
780
793
  const bg = bgRef.current;
794
+ const lastFallbackRef = useRef(undefined); // last gateway-fallback notice shown (once per change)
795
+ const compactionWarnedRef = useRef(false); // a failed auto-compaction is said once, until one succeeds again
781
796
  const tokHist = useRef([]); // per-turn decode tok/s, for the /stats throughput sparkline
782
797
  const toolTotal = useRef(0); // cumulative tool calls this session, for /stats
783
798
  const liveText = useRef("");
@@ -1091,6 +1106,25 @@ function Root() {
1091
1106
  if (notice)
1092
1107
  sys("⚠ " + notice);
1093
1108
  },
1109
+ onServed: ({ backend, fallbackFrom }) => {
1110
+ // The gateway answered from a fallback box: the selected model is down and another model is replying under
1111
+ // its name (10/30: a parked Cortana answered by Aurora fooled every check). Say so once per change.
1112
+ const key = `${fallbackFrom}->${backend ?? "?"}`;
1113
+ if (lastFallbackRef.current === key)
1114
+ return;
1115
+ lastFallbackRef.current = key;
1116
+ sys(`⚠ ${fallbackFrom} is unavailable — this answer came from ${backend ?? "another backend"} (gateway fallback)`);
1117
+ },
1118
+ onCompaction: (e) => {
1119
+ if (!e.skipped) {
1120
+ compactionWarnedRef.current = false;
1121
+ return;
1122
+ }
1123
+ if (compactionWarnedRef.current)
1124
+ return;
1125
+ compactionWarnedRef.current = true;
1126
+ sys(`⚠ auto-compaction failed (${e.skipped === "empty_summary" ? "the summarizer returned nothing" : "the summarizer errored"}) — context stays at ~${Math.round(e.after / 1000)}K tokens; /compact retries, /new starts fresh`);
1127
+ },
1094
1128
  onAutoContinue: (round) => {
1095
1129
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
1096
1130
  },
@@ -1848,7 +1882,7 @@ function Root() {
1848
1882
  break;
1849
1883
  }
1850
1884
  s.activateSkill(arg, content);
1851
- 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`);
1852
1886
  break;
1853
1887
  }
1854
1888
  case "whoami":
@@ -35,6 +35,13 @@ export const FEATURES = {
35
35
  default: false,
36
36
  description: "Race a fast, swappable small model against the real turn; use its answer instead when it wins on a simple, tool-free request",
37
37
  },
38
+ /** Deferred tools (tools/deferred.ts native catalog): the main session advertises a fixed core set
39
+ * (NATIVE_CORE_TOOLS) plus tool_search/tool_call; the long tail and every MCP tool are found and run through
40
+ * those two. The tools array never changes mid-session (cache-safe). Default OFF — every tool advertised. */
41
+ deferredTools: {
42
+ default: false,
43
+ description: "Advertise a fixed core tool set + tool_search/tool_call; the rest are found and run on demand (smaller cached prefix)",
44
+ },
38
45
  };
39
46
  /** Env var that overrides one feature: camelCase → UPPER_SNAKE, e.g. classifierGate → KODE_FEATURE_CLASSIFIER_GATE. */
40
47
  export function featureEnvName(name) {