@0perator/operator 0.1.321 → 0.1.325

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/session.js CHANGED
@@ -20,7 +20,7 @@ import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, DEF
20
20
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
21
21
  import { getByoToken, hasByoToken } from "./auth/byo.js";
22
22
  import { Executor } from "./tools/executor.js";
23
- import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor } from "./tools/registry.js";
23
+ import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, renderActiveTasks } from "./tools/registry.js";
24
24
  import { isFeatureEnabled } from "./config/features.js";
25
25
  import { MemoryStore } from "./memory/index.js";
26
26
  import { McpHub, withMcp } from "./mcp/index.js";
@@ -77,56 +77,47 @@ function makeSpawnTool(handler) {
77
77
  return {
78
78
  name: "spawn_agent",
79
79
  safe: false,
80
- description: "Delegate a self-contained subtask to a background sub-agent running on the same Aurora model. " +
81
- "Returns immediately with the sub-agent's id (e.g. agent-1); it runs in the background and AUTOMATICALLY " +
82
- "posts its result into THIS conversation when done. It shares your ONE model endpoint — an endpoint gate " +
83
- "keeps YOUR turn first and runs sub-agents one at a time in the gaps, so a sub-agent never steals your " +
84
- "slot (but spawning many does NOT make them finish sooner). NEVER sleep, poll, or otherwise block to WAIT " +
85
- "for a sub-agent — you do not need to; its result arrives on its own (use agent_status only to CHECK a " +
86
- "state, never as a wait loop, and never `sleep` to pass time). Use it for independent, " +
87
- "parallelizable work — searching a large tree, drafting a file, a long build — so the foreground " +
88
- "stays responsive. The sub-agent does NOT see this conversation, so make the task fully self-contained. " +
89
- "The user watches each sub-agent's live tokens and elapsed time in the background panel. Don't spawn " +
90
- "for trivial work you can do inline. " +
91
- "CRITICAL: you and every sub-agent share ONE model endpoint, so spawning many does NOT run them " +
92
- "faster — they contend for the same model and ALL run slower (a big fan-out can crawl for many " +
93
- "minutes). Use spawn_agent ONLY for genuinely independent, long-running work, and at most 1-2 at a " +
94
- "time. For a linear plan, or steps that build on each other, do them YOURSELF in sequence — that is " +
95
- "faster and simpler than fanning out. Prefer sequential. " +
96
- "NEVER re-spawn a task because you haven't seen its result yet or assume it was \"evicted\" — it is " +
97
- "still working; call agent_status (no args) to see every sub-agent's real state before concluding " +
98
- "otherwise. A sub-agent id is NOT a shell_background job id — never poll it with bash_output/bash_kill " +
99
- "(those are for shell_background only and will just error); use agent_status to check on it, " +
100
- "message_agent to nudge it, and stop_agent to actually halt it if the user asks you to stop/cancel it. " +
101
- "RETURN CONTRACT: in the task, tell the sub-agent to report back CONCISELY — a short findings list plus " +
102
- "file:line pointers, NOT pasted large output (it can re-read files itself). Its report posts back into " +
103
- "THIS conversation, so a bloated report bloats your own context and can trigger a compaction — scope the " +
104
- "ask so ~1-2k tokens of findings is enough. SINGLE WRITER: keep file EDITS on one agent in sequence (you); " +
105
- "spawn sub-agents for READ / SEARCH / REVIEW intelligence, not for parallel writes to the same files — two " +
106
- "writers on one working tree corrupt each other. Match effort to the task: a lookup is one agent (or just " +
107
- "do it inline); only genuinely independent, multi-step work is worth a spawn.",
80
+ description: "Spawn sub-agents: isolated sessions on the same model, each with its own shell; only each one's final report " +
81
+ "returns, auto-posted into THIS conversation when it finishes. Pass every subtask in `tasks` — one entry spawns " +
82
+ "one sub-agent, several run in parallel (2 at a time plus 2 queued by default — settings.background.maxConcurrent; " +
83
+ "past the cap the call tells you). When you decide to delegate, make THIS call in the same round — never announce " +
84
+ "\"I'll spawn sub-agents\" without calling spawn_agent. Keep working meanwhile: NEVER sleep, poll or wait for a " +
85
+ "result (agent_status checks state, message_agent steers, stop_agent halts; a sub-agent id is NOT a shell job id — " +
86
+ "bash_output/bash_kill will just error). NEVER re-spawn a task because its result hasn't arrived — it is still " +
87
+ "working.\n" +
88
+ "USE FOR: reasoning-heavy subtasks, work that would flood your context, or independent parallel workstreams " +
89
+ "(research per area, review per module, search per tree, drafting a file).\n" +
90
+ "DO NOT USE FOR: a single tool call; mechanical steps with no reasoning; anything that needs the user (sub-agents " +
91
+ "cannot ask); edits to the same files from several agents.\n" +
92
+ "RULES: the sub-agent knows NOTHING of this conversation — put every path, id and fact in the brief, as a spec: " +
93
+ "**Objective** · **Context** · **Deliverable** · **Constraints** · **Done** (how it proves success). A sub-agent's " +
94
+ "report is a SELF-REPORT — verify side effects (writes, pushes, uploads) yourself before telling the user they " +
95
+ "happened. SINGLE WRITER: keep file edits on one agent (you) and delegate READ / SEARCH / REVIEW / DRAFT work. " +
96
+ "Ask for a CONCISE report (findings + file:line, ~1-2k tokens) — it lands in your context.",
108
97
  parameters: {
109
98
  type: "object",
110
99
  properties: {
111
- task: { type: "string", description: "A complete, self-contained instruction for the sub-agent." },
112
- agent: { type: "string", description: "Optional: the name of a repo-local sub-agent persona from .operator/agents/ (listed in your context under 'Repo-local harness'). When set, that persona guides the sub-agent." },
100
+ tasks: { type: "array", items: { type: "string" }, description: "The subtask brief(s). One entry spawns one sub-agent; several run in parallel. A single task is a one-entry array." },
101
+ task: { type: "string", description: "A single brief (the same as a one-entry `tasks`)." },
102
+ agent: { type: "string", description: "Optional: the name of a repo-local sub-agent persona from .operator/agents/ (listed in your context under 'Repo-local harness'). When set, that persona guides every sub-agent of this call." },
113
103
  },
114
- required: ["task"],
115
104
  },
116
105
  run: async (args) => {
117
- const task = String(args.task ?? "").trim();
118
- if (!task)
119
- return "error: spawn_agent needs a non-empty task";
106
+ const briefs = (Array.isArray(args.tasks) ? args.tasks.map((t) => String(t ?? "").trim()) : [String(args.task ?? "").trim()]).filter(Boolean);
107
+ if (!briefs.length)
108
+ return "error: spawn_agent needs `tasks` (an array of briefs — one per sub-agent) or `task`";
120
109
  const agent = String(args.agent ?? "").trim();
121
- if (agent) {
122
- // A named repo-local persona: prepend it to the brief (the bg factory uses a fixed system prompt,
123
- // so the persona rides in the task — a self-contained, low-risk way to specialize the sub-agent).
124
- const persona = operatorAgentPersona(agent);
125
- if (persona)
126
- return handler(`You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`);
127
- return handler(`${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`);
128
- }
129
- return handler(task);
110
+ // A named repo-local persona: prepend it to the brief (the bg factory uses a fixed system prompt, so the
111
+ // persona rides in the task — a self-contained, low-risk way to specialize the sub-agent).
112
+ const persona = agent ? operatorAgentPersona(agent) : undefined;
113
+ const frame = (task) => !agent ? task : persona
114
+ ? `You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`
115
+ : `${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`;
116
+ if (briefs.length === 1)
117
+ return handler(frame(briefs[0]));
118
+ // Fan-out: one spawn per brief, in order; the manager queues past its running cap and refuses past the
119
+ // in-flight cap — each line reports what happened to that brief, so a partial fan-out is never silent.
120
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t))}`).join("\n");
130
121
  },
131
122
  };
132
123
  }
@@ -303,6 +294,7 @@ export class Session {
303
294
  convo = new Conversation();
304
295
  inner; // was readonly — /model rebuilds it for a "single" profile switch
305
296
  router; // rebuilt alongside inner (setModel)
297
+ chain; // the endpoint chain the shell built (cfg.router / useRouter) — what the default local model routes through
306
298
  registry; // /model's choices — built-ins + any settings.models
307
299
  moaConfig;
308
300
  fastStartConfig;
@@ -422,6 +414,7 @@ export class Session {
422
414
  this.localSchemas = toSchemas(reg);
423
415
  this.inner = cfg.router ?? new AuroraRouter();
424
416
  this.router = engineRouter(this.inner);
417
+ this.chain = cfg.router;
425
418
  this.registry = modelRegistry(cfg.models);
426
419
  this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
427
420
  this.moaConfig = cfg.moa;
@@ -467,7 +460,7 @@ export class Session {
467
460
  const sc = cfg.sleepConsolidation ?? { enabled: true, idleThresholdSec: 30, stepsBetweenPasses: 10, modelTier: "fast" };
468
461
  this.sleepScheduler = createSleepScheduler({
469
462
  consolidation: { ...sc, enabled: true },
470
- onComplete: (result) => {
463
+ onComplete: () => {
471
464
  this.telemetry.record({ type: "error", message: "consolidation completed" });
472
465
  },
473
466
  });
@@ -638,6 +631,7 @@ export class Session {
638
631
  ctxWindow: this.inner.ctxLimit(),
639
632
  systemPrompt: this.sys(),
640
633
  summarize: this.summarize,
634
+ preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
641
635
  minKeepTurns: 2,
642
636
  tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
643
637
  meter: globalTokenMeter,
@@ -738,7 +732,14 @@ export class Session {
738
732
  if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
739
733
  return { ok: false, error: `MOA needs a "moa" block (proposers + aggregator) in settings.json — see MOA-DESIGN.md` };
740
734
  }
741
- if (profile.kind === "single" && (profile.endpoint || profile.endpoints?.length)) {
735
+ if (profile.kind === "single" && profile.id === DEFAULT_MODEL_ID && this.chain) {
736
+ // The default local model IS the shell's endpoint chain (the gateway's published port + its failover
737
+ // legs). Restore it rather than rebuilding from the profile's static :8097 endpoint, which no longer
738
+ // answers on a gateway box — otherwise /model away-and-back lands on a dead port.
739
+ this.inner = this.chain;
740
+ this.router = engineRouter(this.inner);
741
+ }
742
+ else if (profile.kind === "single" && (profile.endpoint || profile.endpoints?.length)) {
742
743
  // BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
743
744
  // selectModel already refused the id if the key is not connected, so resolution can't miss here.
744
745
  const token = profile.byo ? getByoToken(profile.byo) : undefined;
@@ -764,6 +765,17 @@ export class Session {
764
765
  this.modelId = profile.id;
765
766
  return { ok: true };
766
767
  }
768
+ /** Re-point this session at a freshly built endpoint chain. The interactive shell constructs the Session at
769
+ * first render, BEFORE the boot lever has resolved the gateway's dynamic port (server.json) — the chain must
770
+ * follow that resolution or health() and every turn probe "" (unset — auto-discover). Same swap setModel does. A
771
+ * non-default /model pick keeps owning routing; the chain then waits for `/model operator-1m`. */
772
+ useRouter(router) {
773
+ this.chain = router;
774
+ if (this.modelId !== DEFAULT_MODEL_ID)
775
+ return;
776
+ this.inner = router;
777
+ this.router = engineRouter(this.inner);
778
+ }
767
779
  /** The full conversation, for persistence (auto-save / --resume). */
768
780
  snapshot() {
769
781
  return this.convo.all.map((m) => ({ ...m }));
@@ -1165,6 +1177,7 @@ export class Session {
1165
1177
  spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
1166
1178
  systemPrompt: sys,
1167
1179
  summarize: this.summarize,
1180
+ preservedState: () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list
1168
1181
  background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
1169
1182
  maxTokens: this.maxTokens,
1170
1183
  maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
@@ -139,7 +139,7 @@ function renderBlock(doc, t, left, width) {
139
139
  }
140
140
  }
141
141
  }
142
- function renderInline(doc, tokens, x, width, indentX) {
142
+ function renderInline(doc, tokens, _x, width, indentX) {
143
143
  if (!tokens.length) {
144
144
  doc.text(" ", { width });
145
145
  return;
@@ -1252,7 +1252,6 @@ async function briefUpdate(args) {
1252
1252
  const nextH2 = body.indexOf("\n## ", afterHeading);
1253
1253
  const sectionEnd = nextH2 >= 0 ? nextH2 : body.length;
1254
1254
  if (mode === "append") {
1255
- const existing = body.slice(afterHeading, sectionEnd);
1256
1255
  body = body.slice(0, sectionEnd) + "\n" + content + "\n" + body.slice(sectionEnd);
1257
1256
  }
1258
1257
  else {
@@ -1301,11 +1300,20 @@ async function bashKill(args) {
1301
1300
  }
1302
1301
  const agentTasks = [];
1303
1302
  let taskSeq = 0;
1303
+ const TASK_MARK = { pending: "[ ]", in_progress: "[>]", done: "[x]", cancelled: "[~]" };
1304
1304
  function renderTasks() {
1305
1305
  if (!agentTasks.length)
1306
1306
  return "(no tasks yet)";
1307
- const mark = { pending: "[ ]", in_progress: "[~]", done: "[x]" };
1308
- return agentTasks.map((t) => `${mark[t.status]} #${t.id} ${t.text}`).join("\n");
1307
+ return agentTasks.map((t) => `${TASK_MARK[t.status]} #${t.id} ${t.text}`).join("\n");
1308
+ }
1309
+ /** The ACTIVE plan (pending / in_progress only) for re-injection after a context compaction, or null when nothing is
1310
+ * active. Finished and cancelled items are left out on purpose — re-reading them after a compaction makes the model
1311
+ * redo work. The header names the event so the model reads it as its own preserved state, not new input. */
1312
+ export function renderActiveTasks() {
1313
+ const active = agentTasks.filter((t) => t.status === "pending" || t.status === "in_progress");
1314
+ if (!active.length)
1315
+ return null;
1316
+ return ["[Your active task list was preserved across context compaction]", ...active.map((t) => `${TASK_MARK[t.status]} #${t.id} ${t.text} (${t.status})`)].join("\n");
1309
1317
  }
1310
1318
  async function taskAdd(args) {
1311
1319
  const items = Array.isArray(args.tasks) ? args.tasks.map(String) : [str(args.text)].filter(Boolean);
@@ -1327,10 +1335,16 @@ async function taskUpdate(args) {
1327
1335
  return agentTasks.length
1328
1336
  ? `error: no task #${id}. task IDs are assigned by task_add (don't guess them) — current tasks:\n${renderTasks()}`
1329
1337
  : `error: no tasks exist yet — call task_add first to create them (it returns each task's id), then task_update by that id.`;
1330
- if (status !== "pending" && status !== "in_progress" && status !== "done")
1331
- return "error: status must be pending | in_progress | done";
1338
+ if (status !== "pending" && status !== "in_progress" && status !== "done" && status !== "cancelled")
1339
+ return "error: status must be pending | in_progress | done | cancelled";
1340
+ // Exactly ONE step in progress at a time — enforced by code, not by asking: a second in_progress returns the
1341
+ // earlier one to pending and says so, so the plan pane always shows the single step being worked.
1342
+ const demoted = status === "in_progress" ? agentTasks.filter((x) => x.id !== id && x.status === "in_progress") : [];
1343
+ for (const d of demoted)
1344
+ d.status = "pending";
1332
1345
  t.status = status;
1333
- return `task #${id} → ${status}\n${renderTasks()}`;
1346
+ const note = demoted.length ? ` (${demoted.map((d) => `#${d.id}`).join(", ")} returned to pending — one task in progress at a time)` : "";
1347
+ return `task #${id} → ${status}${note}\n${renderTasks()}`;
1334
1348
  }
1335
1349
  // Clear the plan. Default wipes the whole list (the model had no way to honor "clear the list / reset the
1336
1350
  // plan / move on" — it could only mark items done). `completed_only` drops finished tasks and keeps the rest.
@@ -1338,7 +1352,7 @@ async function taskClear(args) {
1338
1352
  const before = agentTasks.length;
1339
1353
  if (Boolean(args.completed_only)) {
1340
1354
  for (let i = agentTasks.length - 1; i >= 0; i--)
1341
- if (agentTasks[i].status === "done")
1355
+ if (agentTasks[i].status === "done" || agentTasks[i].status === "cancelled")
1342
1356
  agentTasks.splice(i, 1);
1343
1357
  return `cleared ${before - agentTasks.length} completed task(s)\n${renderTasks()}`;
1344
1358
  }
@@ -1840,7 +1854,7 @@ async function imageInspect(args) {
1840
1854
  return "error: image_inspect needs an image (a local path or an http(s) url)";
1841
1855
  const os = await nodeImport("node:os");
1842
1856
  const { join } = await nodeImport("node:path");
1843
- const { mkdtemp, writeFile, rm, readFile, stat } = await nodeImport("node:fs/promises");
1857
+ const { mkdtemp, writeFile, rm, stat } = await nodeImport("node:fs/promises");
1844
1858
  const { execFile } = await nodeImport("node:child_process");
1845
1859
  const { promisify } = await nodeImport("node:util");
1846
1860
  const pexec = promisify(execFile);
@@ -2230,20 +2244,20 @@ const TOOLS = [
2230
2244
  },
2231
2245
  {
2232
2246
  name: "task_add", safe: false,
2233
- description: "Add one or more tasks to the session TODO list (multi-step work tracking the user can see). Give `text` for one or `tasks` (array) for several.",
2247
+ description: "Track a task list for multi-step work (3+ steps) or when the user gives several tasks — write it FIRST, before acting, with every step as its own item (for \"all N items\" work enumerate each instance so none is silently dropped). List order is priority. The owner sees this list live in the plan pane, so it REPLACES restating the plan in prose. Give `text` for one task or `tasks` (array) for several; returns each task's id.",
2234
2248
  parameters: { type: "object", properties: { text: { type: "string" }, tasks: { type: "array", items: { type: "string" } } } },
2235
2249
  run: taskAdd,
2236
2250
  },
2237
2251
  {
2238
2252
  name: "task_list", safe: true,
2239
- description: "Show the session TODO list with each task's status ([ ] pending, [~] in progress, [x] done).",
2253
+ description: "Show the session task list with each task's status ([ ] pending, [>] in progress, [x] done, [~] cancelled). Read it before resuming work after a compaction.",
2240
2254
  parameters: { type: "object", properties: {} },
2241
2255
  run: taskList,
2242
2256
  },
2243
2257
  {
2244
2258
  name: "task_update", safe: false,
2245
- description: "Set a task's status. status = pending | in_progress | done. Update IMMEDIATELY as work lands — mark a task `in_progress` when you start it and `done` the moment it's finished, one at a time, not in a batch at the end. This keeps the live plan honest so the user sees real progress.",
2246
- parameters: { type: "object", properties: { id: { type: "number" }, status: { type: "string", enum: ["pending", "in_progress", "done"] } }, required: ["id", "status"] },
2259
+ description: "Set a task's status: pending | in_progress | done | cancelled. Exactly ONE task in_progress at a time (marking another in_progress returns the previous one to pending). Mark `in_progress` when you start a step and `done` only after the work is VERIFIED — never on intent. If a step fails, mark it cancelled and task_add a revised one. Update as each step lands, not in a batch at the end.",
2260
+ parameters: { type: "object", properties: { id: { type: "number" }, status: { type: "string", enum: ["pending", "in_progress", "done", "cancelled"] } }, required: ["id", "status"] },
2247
2261
  run: taskUpdate,
2248
2262
  },
2249
2263
  {
@@ -2,8 +2,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
3
  import { theme } from "./theme.js";
4
4
  import { bar } from "./chart.js";
5
- const GLYPH = { pending: "☐", in_progress: "◐", done: "☑" };
6
- const COLOR = { pending: theme.muted, in_progress: theme.running, done: theme.success };
5
+ const GLYPH = { pending: "☐", in_progress: "◐", done: "☑", cancelled: "⊘" };
6
+ const COLOR = { pending: theme.muted, in_progress: theme.running, done: theme.success, cancelled: theme.muted };
7
+ const finished = (t) => t.status === "done" || t.status === "cancelled";
7
8
  /** The header count "n/total done" (pure, testable). */
8
9
  export function planProgress(tasks) {
9
10
  const done = tasks.filter((t) => t.status === "done").length;
@@ -14,10 +15,10 @@ export function PlanPane({ tasks, title = "plan" }) {
14
15
  return null;
15
16
  // A fully-completed plan clears itself — once every step is done it has no live value and shouldn't keep
16
17
  // occupying the frame. The per-step ✓ already showed as each landed; the finished list drops away.
17
- if (tasks.every((t) => t.status === "done"))
18
+ if (tasks.every(finished))
18
19
  return null;
19
20
  // Borderless: this pane renders in Ink's DYNAMIC region; a box border there orphans its rows into
20
21
  // scrollback whenever the Static transcript grows during a long turn (the v0.1.92 line-flood). The
21
22
  // dim header labels the group without a border.
22
- return (_jsxs(Box, { flexDirection: "column", paddingLeft: 1, children: [_jsxs(Text, { dimColor: true, children: [`${title} · ${planProgress(tasks)} `, _jsx(Text, { color: theme.success, children: bar(tasks.filter((t) => t.status === "done").length, tasks.length, 8) })] }), tasks.map((t) => (_jsxs(Text, { children: [_jsxs(Text, { color: COLOR[t.status], children: [GLYPH[t.status], " "] }), _jsx(Text, { dimColor: t.status === "done", strikethrough: t.status === "done", children: t.text })] }, t.id)))] }));
23
+ return (_jsxs(Box, { flexDirection: "column", paddingLeft: 1, children: [_jsxs(Text, { dimColor: true, children: [`${title} · ${planProgress(tasks)} `, _jsx(Text, { color: theme.success, children: bar(tasks.filter((t) => t.status === "done").length, tasks.length, 8) })] }), tasks.map((t) => (_jsxs(Text, { children: [_jsxs(Text, { color: COLOR[t.status], children: [GLYPH[t.status], " "] }), _jsx(Text, { dimColor: finished(t), strikethrough: finished(t), children: t.text })] }, t.id)))] }));
23
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.321",
3
+ "version": "0.1.325",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",