@0perator/operator 0.2.0 → 0.2.1

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.
Files changed (75) hide show
  1. package/README.md +4 -3
  2. package/dist/auth/commands.js +7 -3
  3. package/dist/auth/identity.js +1 -0
  4. package/dist/auth/staff.js +55 -0
  5. package/dist/autonomy/delegate-mode.js +2 -2
  6. package/dist/autonomy/delegate.js +41 -14
  7. package/dist/autonomy/headless.js +7 -4
  8. package/dist/autonomy/index.js +2 -4
  9. package/dist/autonomy/session-factory.js +11 -12
  10. package/dist/autonomy/subagent-model.js +17 -7
  11. package/dist/background/capacity.js +136 -0
  12. package/dist/background/evidence.js +42 -0
  13. package/dist/background/index.js +311 -44
  14. package/dist/background/lane-phase.js +60 -0
  15. package/dist/background/lane-summary.js +151 -0
  16. package/dist/background/notices.js +12 -3
  17. package/dist/background/synthesis.js +25 -0
  18. package/dist/bus/inbox.js +150 -6
  19. package/dist/cli.js +191 -96
  20. package/dist/config/features.js +3 -3
  21. package/dist/config/persona.js +29 -3
  22. package/dist/config/settings.js +261 -20
  23. package/dist/config/staff-prompt.js +12 -0
  24. package/dist/engine/agent.js +51 -40
  25. package/dist/engine/aurora.js +36 -4
  26. package/dist/engine/batch-scheduler.js +4 -13
  27. package/dist/engine/compaction.js +1 -1
  28. package/dist/engine/continuation.js +30 -32
  29. package/dist/engine/decision-points.js +2 -3
  30. package/dist/engine/fanout.js +16 -0
  31. package/dist/engine/loop-guard.js +26 -83
  32. package/dist/engine/messages.js +2 -2
  33. package/dist/engine/moa.js +16 -1
  34. package/dist/engine/native-vision-node.js +72 -0
  35. package/dist/engine/native-vision.js +103 -0
  36. package/dist/engine/verify-gate.js +37 -7
  37. package/dist/gateway-cli.js +14 -3
  38. package/dist/memory/live-progress.js +4 -5
  39. package/dist/moa/codeact-lane.js +98 -0
  40. package/dist/moa/codeact-sandbox.js +409 -0
  41. package/dist/moa/codeact.js +140 -0
  42. package/dist/permissions/artifact-visibility.js +10 -0
  43. package/dist/permissions/tier.js +4 -2
  44. package/dist/products/craft.js +2 -2
  45. package/dist/remote/grants.js +119 -0
  46. package/dist/remote/host.js +33 -5
  47. package/dist/router/models.js +24 -14
  48. package/dist/selfimprove/index.js +8 -6
  49. package/dist/services/preflight.js +35 -91
  50. package/dist/session.js +127 -41
  51. package/dist/skills/install-guard.js +68 -0
  52. package/dist/skills/install.js +67 -0
  53. package/dist/toolchain/manifest.json +13 -13
  54. package/dist/tools/background-result.js +1 -1
  55. package/dist/tools/classes.js +103 -0
  56. package/dist/tools/contract.js +1 -1
  57. package/dist/tools/craft.js +13 -2
  58. package/dist/tools/executor.js +25 -15
  59. package/dist/tools/generation-gateway.js +94 -0
  60. package/dist/tools/registry.js +83 -152
  61. package/dist/ui/App.js +15 -4
  62. package/dist/ui/BgPanel.js +15 -10
  63. package/dist/ui/Header.js +1 -6
  64. package/dist/ui/StatusRule.js +18 -7
  65. package/dist/ui/ToolStep.js +3 -3
  66. package/dist/ui/Transcript.js +36 -14
  67. package/dist/ui/batchLine.js +4 -4
  68. package/dist/ui/editdiff.js +2 -4
  69. package/dist/ui/format.js +4 -20
  70. package/dist/ui/liveTools.js +3 -3
  71. package/dist/ui/opsMode.js +20 -0
  72. package/dist/ui/types.js +0 -2
  73. package/dist/update-check.js +17 -6
  74. package/package.json +1 -1
  75. package/dist/tools/mutating.js +0 -15
@@ -11,6 +11,9 @@
11
11
  // A hard stop is on by default for unattended runs and opt-in for an interactive owner; before it ends a turn the
12
12
  // engine offers bounded recovery (LoopRecovery).
13
13
  import { unwrapToolCall } from "./decision-points.js";
14
+ import { AUTOPOST_POLLERS, DISPATCH, DISPATCH_BOOKKEEPING, FAILURE_TOLERANT, FILE_WRITE, IDEMPOTENT, PATH_READ, POLLERS, PROGRESS, SHELL_FOREGROUND, SUBAGENT_SPAWN, SUPERVISION, WRITE_PROGRESS, mutationLanded, refusedResult, resultFailed as failedResult, } from "../tools/classes.js";
15
+ // The classes under the names this module's importers know (tools/classes.ts defines them).
16
+ export { IDEMPOTENT as IDEMPOTENT_TOOLS, PROGRESS as PROGRESS_TOOLS, FAILURE_TOLERANT as FAILURE_TOLERANT_TOOLS, POLLERS as POLLER_TOOLS, WRITE_PROGRESS as WRITE_PROGRESS_TOOLS, AUTOPOST_POLLERS, DISPATCH as DISPATCH_TOOLS, DISPATCH_BOOKKEEPING, SUPERVISION as SUPERVISION_TOOLS, refusedResult, } from "../tools/classes.js";
14
17
  export const LOOP_GUARD_DEFAULTS = {
15
18
  warnIdentical: 3, warnExactFailure: 2, warnSameToolFailure: 3, warnNoProgress: 2, warnInvestigateLoop: 8,
16
19
  stopIdentical: 5, stopExactFailure: 5, stopSameToolFailure: 8, stopNoProgress: 5, stopInvestigateLoop: 15,
@@ -55,76 +58,28 @@ export function resolveLoopGuardConfig(raw, ctx, env = safeEnv()) {
55
58
  maxLoopCompactions: Math.min(5, intAtLeast(s.maxLoopCompactions, 2, 0)),
56
59
  };
57
60
  }
58
- /** Read-only tools: the same call returning the same result again is no new information. */
59
- export const IDEMPOTENT_TOOLS = new Set([
60
- "file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search",
61
- "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch",
62
- "skill_list",
63
- ]);
64
- /** A successful call to one of these is progress: every failing call still counted this turn is retried as a
65
- * new experiment (edit -> re-run), not a replay. */
66
- export const PROGRESS_TOOLS = new Set([
67
- "file_write", "file_edit", "bash", "shell_exec", "shell_background", "git_command", "delegate_task",
68
- "spawn_agent", "email_send", "cronjob", "task_add", "task_update", "task_clear", "memory_store", "checkpoint",
69
- "http_request", "browser", "chauffeur",
70
- ]);
71
- /** Tools whose "failure" is normal work output (a red test run, an empty page): a run of DIFFERENT failing
72
- * calls is diagnosis, so the same-tool failure run only warns for them and never stops the turn. */
73
- export const FAILURE_TOLERANT_TOOLS = new Set([
74
- "bash", "shell_exec", "shell_background", "bash_output", "browser", "web_fetch", "http_request", "chauffeur",
75
- ]);
76
- /** Pollers: re-invoked with identical args while waiting on async work. Never flagged as a loop. */
77
- export const POLLER_TOOLS = new Set(["agent_status", "bash_output"]);
78
61
  // A shell command that waits on or inspects a running job: sleeps/waits, process checks, following or tailing a
79
62
  // log, reading a job's log/pid/status file. An unchanged answer there means "not done yet", which is progress.
80
63
  const POLL_COMMAND_RE = /(?:^|[;&|(]\s*)(?:sleep|wait|until|watch|pgrep|pidof|jobs|tail)\b|\bkill\s+-0\b|\bps\s+(?:-|aux)|\.(?:log|out|pid|status)\b/i;
81
- const SHELL_TOOLS = new Set(["bash", "shell_exec"]);
82
- const SPAWN_TOOLS = new Set(["delegate_task", "spawn_agent"]);
83
64
  const MAX_CYCLE_PERIOD = 4;
84
65
  const CYCLE_HISTORY = 64;
85
66
  /** From the 2nd byte-identical repeat a duplicate result of at least this size becomes a reference stub. */
86
67
  export const STUB_MIN_CHARS = 512;
87
68
  const STUB_ARGS_PREVIEW = 120;
88
- const FAILURE_PREFIX_RE = /^(?:error|permission denied|cancelled)\b/i;
89
69
  const EXIT_TRAILER_RE = /(?:\[exit (\d+)\]|^\(no output; exit (\d+|\?)\))\s*$/;
90
70
  /** True when a poll-style call is legitimately repeated while waiting (never a loop). */
91
71
  export function isRepeatable(name, args) {
92
72
  ({ name, args } = unwrapToolCall(name, args));
93
- if (POLLER_TOOLS.has(name))
73
+ if (POLLERS.has(name))
94
74
  return true;
95
75
  // A known allowance: generated/MCP poller naming conventions are legitimately re-invoked with identical args.
96
76
  if (name.endsWith("_poll") || name.endsWith("_get_result"))
97
77
  return true;
98
- return SHELL_TOOLS.has(name) && POLL_COMMAND_RE.test(String(args.command ?? ""));
78
+ return SHELL_FOREGROUND.has(name) && POLL_COMMAND_RE.test(String(args.command ?? ""));
99
79
  }
100
- /** Whether a tool result reports failure. A refusal by the engine's own guards is not the tool failing. */
101
- export function resultFailed(name, result) {
102
- const t = result.trimStart();
103
- if (/^(?:loop guard|repeated action)/i.test(t))
104
- return false;
105
- if (FAILURE_PREFIX_RE.test(t))
106
- return true;
107
- if (SHELL_TOOLS.has(name) || name === "shell_background") {
108
- const m = EXIT_TRAILER_RE.exec(result);
109
- if (m)
110
- return (m[1] ?? m[2]) !== "0";
111
- }
112
- return false;
113
- }
114
- /** A landed workspace edit: file_write / file_edit that did not come back as an error. */
115
- function mutationOk(name, result) {
116
- return (name === "file_write" || name === "file_edit") && !FAILURE_PREFIX_RE.test(result.trimStart()) && !/^(?:loop guard|repeated action)/i.test(result.trimStart());
117
- }
118
- /** Tools that constitute genuine write-progress for the investigate-loop detector.
119
- * Deliberately narrower than PROGRESS_TOOLS: bash/git_command are excluded because
120
- * grep/search/ls inside bash are the exact pattern that motivated this detector.
121
- * Trade: one cheap nudge vs a 3-hour marathon of bash-based investigation. */
122
- export const WRITE_PROGRESS_TOOLS = new Set([
123
- "file_write", "file_edit", "file_create", "checkpoint",
124
- "task_add", "task_update", "task_clear", "memory_store",
125
- "delegate_task", "delegate_to_agent", "spawn_agent",
126
- "cronjob",
127
- ]);
80
+ /** Whether a tool result reports failure (tools/classes.ts toolOutcome). A refusal by the engine's own guards is not
81
+ * the tool failing. `name` is kept for callers; the reading does not depend on the tool. */
82
+ export const resultFailed = (_name, result) => failedResult(result);
128
83
  function canonical(v) {
129
84
  if (Array.isArray(v))
130
85
  return "[" + v.map(canonical).join(",") + "]";
@@ -205,7 +160,7 @@ export class LoopGuard {
205
160
  }
206
161
  this.webSearches++;
207
162
  }
208
- if (SPAWN_TOOLS.has(name) && c.maxSubagents > 0) {
163
+ if (SUBAGENT_SPAWN.has(name) && c.maxSubagents > 0) {
209
164
  if (this.spawns >= c.maxSubagents) {
210
165
  return this.stop("subagent_cap", name, this.spawns, `this turn already started ${this.spawns} sub-agents (limit ${c.maxSubagents}) — that looks like a runaway delegation loop`);
211
166
  }
@@ -215,7 +170,7 @@ export class LoopGuard {
215
170
  // Read-only no-progress: the SAME idempotent read returning the SAME result. hardStop on → stop at the low
216
171
  // count; hardStop off → at the high terminal (so an attended read-only loop still halts). Varied reads never
217
172
  // reach this (different sig each time), so legitimate research is untouched.
218
- const rec = IDEMPOTENT_TOOLS.has(name) ? this.noProgress.get(sig) : undefined;
173
+ const rec = IDEMPOTENT.has(name) ? this.noProgress.get(sig) : undefined;
219
174
  const noProgStop = this.noProgressStopAt(c.stopNoProgress);
220
175
  if (rec && noProgStop > 0 && rec.count >= noProgStop) {
221
176
  return this.stop("no_progress", name, rec.count, `${name} returned the same result ${rec.count} times`);
@@ -260,7 +215,7 @@ export class LoopGuard {
260
215
  const same = (this.sameToolFailures.get(name) ?? 0) + 1;
261
216
  this.sameToolFailures.set(name, same);
262
217
  this.noProgress.delete(sig);
263
- if (c.hardStop && !FAILURE_TOLERANT_TOOLS.has(name) && same >= c.stopSameToolFailure) {
218
+ if (c.hardStop && !FAILURE_TOLERANT.has(name) && same >= c.stopSameToolFailure) {
264
219
  decision = this.stop("same_tool_failure", name, same, `${name} failed ${same} times this turn`);
265
220
  }
266
221
  else if (exact >= c.warnExactFailure) {
@@ -273,7 +228,7 @@ export class LoopGuard {
273
228
  else {
274
229
  this.exactFailures.delete(sig);
275
230
  this.sameToolFailures.delete(name);
276
- const landed = mutationOk(name, result);
231
+ const landed = mutationLanded(name, result);
277
232
  if (landed) {
278
233
  // The workspace changed: every earlier observation is stale, so a re-run is a new experiment.
279
234
  for (const k of this.exactFailures.keys())
@@ -283,12 +238,12 @@ export class LoopGuard {
283
238
  this.history = [];
284
239
  this.streak = { sig: "", hash: "", count: 0, firstId: "" };
285
240
  }
286
- else if (PROGRESS_TOOLS.has(name)) {
241
+ else if (PROGRESS.has(name)) {
287
242
  for (const k of this.exactFailures.keys())
288
243
  this.progressSinceFailure.add(k);
289
244
  this.sameToolFailures.clear();
290
245
  }
291
- if (IDEMPOTENT_TOOLS.has(name)) {
246
+ if (IDEMPOTENT.has(name)) {
292
247
  const h = hash(result);
293
248
  const prev = this.noProgress.get(sig);
294
249
  const count = prev && prev.hash === h ? prev.count + 1 : 1;
@@ -396,7 +351,6 @@ export class LoopGuard {
396
351
  // legitimate (an unchanged result there means "not done yet"), and a round containing any non-poller tool
397
352
  // resets the streak. The distinction is intrinsic: auto-posting pollers never need a wait loop; everything
398
353
  // else might.
399
- export const AUTOPOST_POLLERS = new Set(["agent_status"]);
400
354
  export const POLL_SPIN_DEFAULTS = { nudgeAfter: 2, stopAfter: 3 };
401
355
  export const POLL_SPIN_NUDGE = "agent_status will not change faster by asking again — each report, and a STUCK notice if one stalls, arrives " +
402
356
  "as a message on its own. Act on what it shows: steer an agent that is stuck or off its brief (message_agent), " +
@@ -458,10 +412,6 @@ export class PollSpinGuard {
458
412
  // not progress: nudge at `nudgeAfter`, end the turn at `stopAfter` so the auto-posted reports resume it and the
459
413
  // sub-agents get the slot. Only spawn_agent counts as a dispatch — delegate_task / delegate_to_agent block until
460
414
  // the child is done, so nothing is running after they return.
461
- export const DISPATCH_TOOLS = new Set(["spawn_agent"]);
462
- /** Calls that only book-keep around a dispatch (the plan pane, the agent panel): a dispatch round made of these
463
- * alone has no independent work in it. */
464
- export const DISPATCH_BOOKKEEPING = new Set(["task_add", "task_update", "task_list", "task_clear", "agent_status", "message_agent"]);
465
415
  export const YIELD_DEFAULTS = { nudgeAfter: 1, stopAfter: 2 };
466
416
  export const YIELD_NUDGE = "Your sub-agents are working their steps and this round changed nothing. Do not redo their work: finish what does " +
467
417
  "not depend on them, or close the turn — one status line per agent and 2-3 options for the owner.";
@@ -469,8 +419,6 @@ export const YIELD_STOP = "[turn ended — sub-agents are running on this model'
469
419
  "arrives as a new message and resumes this conversation. Nothing was lost.]";
470
420
  export const YIELD_DISPATCHED = "[turn ended — sub-agents dispatched onto this model's only slot, so the turn hands it to them now; each report " +
471
421
  "arrives as a new message and resumes this conversation. Nothing was lost.]";
472
- /** Supervising IS progress: stopping a sub-agent (to take its step over) or asking the owner never counts as idling. */
473
- export const SUPERVISION_TOOLS = new Set(["stop_agent", "ask_user"]);
474
422
  /** Watches settled tool rounds after a spawn_agent dispatch. Fed one round at a time via observe(); a MUTATING
475
423
  * round resets the streak. The endpoint's slot count sets the policy: on ONE slot (the fleet default) the parent
476
424
  * working beside its sub-agents is pure contention — every parent round waits behind a sub-agent round and then
@@ -497,15 +445,15 @@ export class YieldAfterDispatchGuard {
497
445
  * supervising, with one nudge against redoing their work. */
498
446
  observe(names, mutating, slots = 1, shared = true) {
499
447
  const single = slots <= 1;
500
- if (names.some((n) => DISPATCH_TOOLS.has(n))) {
448
+ if (names.some((n) => DISPATCH.has(n))) {
501
449
  this.dispatched = true;
502
450
  this.streak = 0;
503
- const pure = names.every((n) => DISPATCH_TOOLS.has(n) || DISPATCH_BOOKKEEPING.has(n));
451
+ const pure = names.every((n) => DISPATCH.has(n) || DISPATCH_BOOKKEEPING.has(n));
504
452
  return shared && single && pure ? { action: "halt", streak: 0, message: YIELD_DISPATCHED } : { action: "allow", streak: 0 };
505
453
  }
506
454
  if (!this.dispatched)
507
455
  return { action: "allow", streak: 0 };
508
- if (mutating || names.some((n) => SUPERVISION_TOOLS.has(n))) {
456
+ if (mutating || names.some((n) => SUPERVISION.has(n))) {
509
457
  this.streak = 0;
510
458
  return { action: "allow", streak: 0 };
511
459
  }
@@ -550,7 +498,7 @@ export class NoWriteProgressGuard {
550
498
  /** One settled round: the tools it ran (names) and their results, index-aligned. */
551
499
  observe(names, results) {
552
500
  // Any write-progress call ⇒ progress, reset.
553
- if (names.some((n, i) => WRITE_PROGRESS_TOOLS.has(n) && (!results || (results[i] !== undefined && !resultFailed(n, results[i]) && !/^(?:loop guard|repeated action|blocked)\b/i.test(results[i].trimStart()))))) {
501
+ if (names.some((n, i) => WRITE_PROGRESS.has(n) && (!results || (results[i] !== undefined && !resultFailed(n, results[i]) && !refusedResult(results[i]))))) {
554
502
  this.reset();
555
503
  return { action: "allow", streak: 0 };
556
504
  }
@@ -859,25 +807,23 @@ function shellReads(command, cwd) {
859
807
  const display = command.replace(/^\s*cd\s+\S+\s*&&\s*/, "").replace(/\s+/g, " ").trim();
860
808
  return { files, display: display.length > 100 ? display.slice(0, 100) + "…" : display, mutates };
861
809
  }
862
- const FILE_READ_TOOLS = new Set(["file_read", "read_file", "image_inspect"]);
863
- const WRITE_TOOLS = new Set(["file_write", "file_edit", "file_create", "file_delete"]);
864
810
  /** What one tool call READ: files, or — for a read-only call with no file in it — the call itself; `mutates` when a shell
865
811
  * command changes the tree. Pollers, writes and everything that is not a read return nothing. Pure and node-free;
866
812
  * shared by the engine and the backfill. */
867
813
  export function readTargets(name, args, cwd) {
868
- if (FILE_READ_TOOLS.has(name) && typeof args.path === "string")
814
+ if (PATH_READ.has(name) && typeof args.path === "string")
869
815
  return { files: [joinPath(cwd, args.path)] };
870
816
  if (name === "read_files" && Array.isArray(args.paths)) { // paths, or {path, offset, limit} objects
871
817
  const paths = args.paths.map((p) => (typeof p === "string" ? p : p?.path)).filter((p) => typeof p === "string");
872
818
  return { files: paths.map((p) => joinPath(cwd, p)) };
873
819
  }
874
- if (SHELL_TOOLS.has(name) && typeof args.command === "string") {
820
+ if (SHELL_FOREGROUND.has(name) && typeof args.command === "string") {
875
821
  const r = shellReads(args.command, typeof args.cwd === "string" ? args.cwd : cwd);
876
822
  if (r.files.length)
877
823
  return { files: r.files, mutates: r.mutates };
878
824
  return r.mutates || isRepeatable(name, args) || !r.display ? { files: [], mutates: r.mutates } : { files: [], call: `$ ${r.display}` };
879
825
  }
880
- if (IDEMPOTENT_TOOLS.has(name)) {
826
+ if (IDEMPOTENT.has(name)) {
881
827
  const c = canonical(args);
882
828
  return { files: [], call: `${name} ${c.length > 100 ? c.slice(0, 100) + "…" : c}` };
883
829
  }
@@ -905,16 +851,13 @@ export function isLooped(e) {
905
851
  // are also the engine's reaction to a reply it just received (agent.ts), so one of them means the model has answered.
906
852
  const REPETITION_KINDS = new Set(["reasoning_loop", "repeated_step", "self_loop"]);
907
853
  // A call the engine or the executor refused without running it (a guard, a re-worded repeat, a cap, a denial): no read.
908
- const REFUSED_RE = /^(?:loop guard|repeated action|blocked |permission denied|cancelled|\[interrupted)/i;
909
- /** A result that says the call never ran (REFUSED_RE). */
910
- export const refusedResult = (result) => REFUSED_RE.test(result.trimStart());
911
854
  // The result guard's own marks (LoopGuard.afterCall): a byte-identical duplicate swapped for a stub, short notes appended.
912
855
  const STUB_RE = /^\[note: this result is byte-identical to the /;
913
856
  const GUARD_NOTES_RE = /\n\n\[note: [^\n]*\](?:\n\[note: [^\n]*\])*\s*$/;
914
857
  /** How a call is named in the loop reset's digest and the dead-round note: `$ sed -n '1,80p' src/a.ts`,
915
858
  * `file_read {"path":"src/a.ts"}`. */
916
859
  export function callLabel(name, args) {
917
- if (SHELL_TOOLS.has(name) && typeof args.command === "string")
860
+ if (SHELL_FOREGROUND.has(name) && typeof args.command === "string")
918
861
  return `$ ${shellReads(args.command).display}`;
919
862
  const c = canonical(args);
920
863
  return `${name} ${c.length > 100 ? c.slice(0, 100) + "…" : c}`;
@@ -949,7 +892,7 @@ export function toolSkeleton(name, args) {
949
892
  return callSkeleton(name, args).skeleton;
950
893
  }
951
894
  function callSkeleton(name, args) {
952
- if (SHELL_TOOLS.has(name) && typeof args.command === "string") {
895
+ if (SHELL_FOREGROUND.has(name) && typeof args.command === "string") {
953
896
  const literals = [];
954
897
  const segs = segments(shellWords(args.command)).map((seg) => seg.map((w, i, arr) => {
955
898
  const afterFlag = i > 0 && typeof arr[i - 1] === "string" && arr[i - 1].startsWith("-") && arr[i - 1].length > 1;
@@ -1122,10 +1065,10 @@ export class LoopEvidenceTracker {
1122
1065
  observe(name, args, result = "") {
1123
1066
  this.struggle.observe(name, args, result); // advisory: populates evidence().struggles, changes nothing this phase
1124
1067
  const head = result.trimStart();
1125
- if (REFUSED_RE.test(head))
1068
+ if (refusedResult(head))
1126
1069
  return; // the call never ran
1127
- if (WRITE_TOOLS.has(name)) {
1128
- if (FAILURE_PREFIX_RE.test(head))
1070
+ if (FILE_WRITE.has(name)) {
1071
+ if (!mutationLanded(name, result))
1129
1072
  return;
1130
1073
  this.unheeded = 0;
1131
1074
  this.staleSinceWrite = 0;
@@ -134,8 +134,8 @@ export class Conversation {
134
134
  get all() {
135
135
  return this.messages;
136
136
  }
137
- user(content) {
138
- this.messages.push({ role: "user", content });
137
+ user(content, images) {
138
+ this.messages.push({ role: "user", content, ...(images?.length ? { images } : {}) });
139
139
  }
140
140
  assistant(content, toolCalls) {
141
141
  // Neutralize unparseable arguments at the point they enter history, so the SAVED session file never carries
@@ -1,3 +1,4 @@
1
+ import { codeActEnabled } from "../moa/codeact.js";
1
2
  /** The team from settings.moa, new shape or the pre-10/31 one (aggregator → planner, first other proposer →
2
3
  * specialist). Undefined when no planner is configured. A missing specialist falls back to the planner itself. */
3
4
  export function moaTeam(cfg) {
@@ -8,8 +9,16 @@ export function moaTeam(cfg) {
8
9
  const specialist = cfg?.specialist?.id?.trim()
9
10
  || cfg?.proposers?.find((p) => p.id !== planner.id)?.id
10
11
  || planner.id;
11
- return { planner, specialist, prompt: cfg?.planner_prompt };
12
+ return { planner, specialist, prompt: cfg?.planner_prompt, ...(codeActEnabled(cfg?.codeact) ? { codeact: true } : {}) };
12
13
  }
14
+ /** The CodeAct lane's lines in the brief, only while moa.codeact.enabled (moa/codeact.ts decides eligibility in code). */
15
+ const CODEACT_LINES = [
16
+ "- A bulk step that only reads and always gives the same answer (scan a repo, count or list matches across many files,",
17
+ " batch-check files, analyse a log): delegate_task it with lane \"codeact\", targets (the paths), items or",
18
+ " est_round_trips, read_only true, deterministic true. The specialist does it in one sandboxed program instead of a",
19
+ " call per item. Never for edits, commits, pushes, network or messages: those stay normal steps. A step the check",
20
+ " refuses runs on tools and the report says why.",
21
+ ];
13
22
  /** The planner's standing brief. Identical every turn for a given team, so it stays in the prompt cache. */
14
23
  export function plannerBrief(team) {
15
24
  if (team.prompt)
@@ -22,6 +31,12 @@ export function plannerBrief(team) {
22
31
  `- Hand each self-contained step to the specialist with delegate_task (it runs on ${s} by default). The specialist sees`,
23
32
  " only the task you write: include the goal, the inputs (paths, URLs, facts) and what to report back. Independent",
24
33
  " steps can be delegated together.",
34
+ "- Two or more independent read, search, summarize or verify steps (none needs another's result): spawn_agent them in",
35
+ " one call, role generic, each with its own small slice (paths and line windows, not a whole digest), a concrete",
36
+ " deliverable and deadline_minutes; list nice-to-have ones in `optional`. They run beside you on the sub-agent route,",
37
+ " as many as it has free lanes; a brief it hands back, do yourself. Keep decisions, edits and the synthesis here.",
38
+ "- No fan-out for one step, a step quicker than ~20 s inline, or a chain where each step needs the last.",
39
+ ...(team.codeact ? CODEACT_LINES : []),
25
40
  "- Do yourself: a single quick tool call, anything that needs reading an image (only you read images), and the final",
26
41
  " answer.",
27
42
  "- Check every report before marking the step done (task_update); fix or redo a wrong one instead of passing it on.",
@@ -0,0 +1,72 @@
1
+ // Node side of native vision (engine/native-vision.ts): finding the image files a message names and encoding one for the
2
+ // wire. Kept apart because the engine itself is also bundled for the browser, where fs does not exist.
3
+ import { existsSync, statSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { resolve } from "node:path";
6
+ import { NATIVE_IMAGE_LIMITS } from "./native-vision.js";
7
+ /** Largest file read for an attachment at all (matches the screenshot snapshot cap). */
8
+ const MAX_IMAGE_FILE_BYTES = 64 * 1024 * 1024;
9
+ const IMG_EXT = "(?:png|jpe?g|gif|bmp|webp)";
10
+ // A quoted path may hold spaces; a bare one is a run of non-space characters (shell-escaped spaces allowed). Both must
11
+ // start at an absolute or ~/ root, so an http(s) url — whose path follows "//" — never matches.
12
+ const QUOTED_PATH_RE = new RegExp(`(["'\`])((?:~|/)[^"'\`\\n]*?\\.${IMG_EXT})\\1`, "gi");
13
+ const BARE_PATH_RE = new RegExp(`(?:^|[\\s(\\[])((?:~|/)(?:\\\\ |[^\\s"'\`<>|()\\[\\]])+?\\.${IMG_EXT})(?=$|[\\s)\\],.;:!?])`, "gi");
14
+ /** The local image files a message names, in order, deduplicated, existing and readable, at most `max`. */
15
+ export function extractImagePaths(text, max = NATIVE_IMAGE_LIMITS.maxImages) {
16
+ if (!text)
17
+ return [];
18
+ const found = [];
19
+ for (const m of text.matchAll(QUOTED_PATH_RE))
20
+ found.push({ at: m.index ?? 0, raw: m[2] });
21
+ for (const m of text.matchAll(BARE_PATH_RE))
22
+ found.push({ at: m.index ?? 0, raw: m[1].replace(/\\ /g, " ") });
23
+ found.sort((a, b) => a.at - b.at);
24
+ const out = [];
25
+ for (const { raw } of found) {
26
+ const p = resolve(raw.startsWith("~/") ? `${homedir()}/${raw.slice(2)}` : raw);
27
+ if (out.includes(p))
28
+ continue;
29
+ try {
30
+ if (!existsSync(p))
31
+ continue;
32
+ const st = statSync(p);
33
+ if (!st.isFile() || st.size === 0 || st.size > MAX_IMAGE_FILE_BYTES)
34
+ continue;
35
+ }
36
+ catch {
37
+ continue;
38
+ }
39
+ out.push(p);
40
+ if (out.length >= max)
41
+ break;
42
+ }
43
+ return out;
44
+ }
45
+ /** One image file as a data url at the wire limits, or null when it cannot be read (gone since the message was sent) or
46
+ * is blank. Cached by path, size and mtime. */
47
+ const encoded = new Map();
48
+ export async function encodeImage(path) {
49
+ let key;
50
+ try {
51
+ const st = statSync(path);
52
+ key = `${path}|${st.size}|${st.mtimeMs}`;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ if (encoded.has(key))
58
+ return encoded.get(key) ?? null;
59
+ let url = null;
60
+ try {
61
+ const { visionImageDataUrl } = await import("../tools/registry.js");
62
+ const r = await visionImageDataUrl(path, NATIVE_IMAGE_LIMITS);
63
+ url = "url" in r ? r.url : null;
64
+ }
65
+ catch {
66
+ url = null;
67
+ }
68
+ if (encoded.size >= 8)
69
+ encoded.delete(encoded.keys().next().value);
70
+ encoded.set(key, url);
71
+ return url;
72
+ }
@@ -0,0 +1,103 @@
1
+ /** What goes on the wire for an attached image. 1568 px keeps a screenshot's text legible; a file heavier than
2
+ * `maxBytes` at that size is re-encoded as JPEG. At most `maxImages` per message. `keepBlank`: a flat picture is still
3
+ * the owner's picture, so the tool's "image is blank" refusal does not apply. */
4
+ export const NATIVE_IMAGE_LIMITS = { maxEdge: 1568, maxBytes: 1_500_000, maxImages: 4, keepBlank: true };
5
+ // ── capability ────────────────────────────────────────────────────────────────────────────────────────────
6
+ /** llama.cpp `GET /props`: `modalities.vision` is true only when the server was started with a multimodal projector. */
7
+ export function visionFromProps(props) {
8
+ const v = props?.modalities?.vision;
9
+ return typeof v === "boolean" ? (v ? "yes" : "no") : "unknown";
10
+ }
11
+ /** A model row from `GET /v1/models/<id>` on a gateway or vendor. Understands the shapes in use (`modalities.vision`,
12
+ * `capabilities.vision`, `vision`, `input_modalities`/`architecture.input_modalities` listing "image"); anything
13
+ * else is unknown, never a guess. */
14
+ export function visionFromModelRow(row) {
15
+ const r = row;
16
+ if (!r || typeof r !== "object")
17
+ return "unknown";
18
+ for (const v of [r.modalities?.vision, r.capabilities?.vision, r.vision])
19
+ if (typeof v === "boolean")
20
+ return v ? "yes" : "no";
21
+ const list = r.input_modalities ?? r.architecture?.input_modalities;
22
+ if (Array.isArray(list))
23
+ return list.includes("image") ? "yes" : "no";
24
+ return "unknown";
25
+ }
26
+ const SUPPORT_TTL_MS = 10 * 60_000;
27
+ const support = new Map();
28
+ const supportKey = (base, model) => `${base.replace(/\/+$/, "").replace(/\/v1$/, "")}|${model}`;
29
+ async function getJson(url, timeoutMs, f) {
30
+ try {
31
+ const r = await f(url, { signal: AbortSignal.timeout(timeoutMs) });
32
+ return r.ok ? await r.json() : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ /** Whether the endpoint serves a model that takes images. llama.cpp's own `/props` first, then the model's row on a
39
+ * gateway; "unknown" when neither says. Cached per endpoint and model (10 minutes); a rejected image flips it to "no". */
40
+ export async function detectVision(base, model, opts = {}) {
41
+ const key = supportKey(base, model);
42
+ const now = opts.now ?? Date.now();
43
+ const hit = support.get(key);
44
+ if (hit && now - hit.at < SUPPORT_TTL_MS)
45
+ return hit.v;
46
+ const f = opts.fetchImpl ?? fetch;
47
+ const timeoutMs = opts.timeoutMs ?? 1500;
48
+ const bare = key.split("|")[0];
49
+ let v = visionFromProps(await getJson(`${bare}/props`, timeoutMs, f));
50
+ if (v === "unknown")
51
+ v = visionFromModelRow(await getJson(`${bare}/v1/models/${encodeURIComponent(model)}`, timeoutMs, f));
52
+ support.set(key, { v, at: now });
53
+ return v;
54
+ }
55
+ /** The server turned an image down: remember it, so the rest of the session sends no more. */
56
+ export function markVisionRejected(base, model) {
57
+ support.set(supportKey(base, model), { v: "no", at: Date.now() });
58
+ }
59
+ export function resetVisionCache() { support.clear(); }
60
+ /** The error an endpoint raises for an image it cannot take (llama.cpp without a projector: "image input is not
61
+ * supported"; vendors: "does not support image"/"multimodal"). Only a client or server error that names it. */
62
+ const IMAGE_REJECT_RE = /\bimage(?:_url|s)?\b.*\b(?:not supported|unsupported|not support|invalid|cannot|can't|does not|doesn't)\b|\b(?:not supported|unsupported|does not support|doesn't support)\b.*\b(?:image|multimodal|vision)|\bmmproj\b|\bmultimodal\b/i;
63
+ export function imageRejected(err) {
64
+ const status = err?.status;
65
+ if (typeof status !== "number" || status < 400)
66
+ return false;
67
+ return IMAGE_REJECT_RE.test(err instanceof Error ? err.message : String(err));
68
+ }
69
+ // ── message construction ──────────────────────────────────────────────────────────────────────────────────
70
+ const SEEN_NOTE = "[The image(s) above are attached to this message and you can see them directly: describe or read them from the picture, with no image_analyze call.]";
71
+ /** The request's messages with each message's `images` turned into image_url parts after its text. An image that
72
+ * cannot be encoded is left out (its path is still in the text). `images` itself never reaches the wire. */
73
+ export async function toWireMessages(messages, encode) {
74
+ const out = [];
75
+ for (const m of messages) {
76
+ const { images, ...rest } = m;
77
+ if (!images?.length) {
78
+ out.push(rest);
79
+ continue;
80
+ }
81
+ const parts = [];
82
+ for (const p of images) {
83
+ const url = await encode(p);
84
+ if (url)
85
+ parts.push({ type: "image_url", image_url: { url } });
86
+ }
87
+ out.push(parts.length ? { ...rest, content: [{ type: "text", text: `${m.content}\n\n${SEEN_NOTE}` }, ...parts] } : rest);
88
+ }
89
+ return out;
90
+ }
91
+ /** The conversation with every message's images taken back off: the owner's text gains a line pointing at each file,
92
+ * so the model can still look at it with image_analyze. Returns how many images were taken off. */
93
+ export function withoutImages(messages) {
94
+ let removed = 0;
95
+ const out = messages.map((m) => {
96
+ if (!m.images?.length)
97
+ return m;
98
+ removed += m.images.length;
99
+ const { images, ...rest } = m;
100
+ return { ...rest, content: `${m.content}\n\n[Attached image${images.length > 1 ? "s" : ""} not sent to the model directly: ${images.join(", ")}. Look at ${images.length > 1 ? "them" : "it"} with image_analyze.]` };
101
+ });
102
+ return { messages: out, removed };
103
+ }
@@ -156,9 +156,20 @@ export function isStrongVerifyCmd(cmd) {
156
156
  export function reportedChecks(text) {
157
157
  return REPORTED.filter(([, re]) => re.test(text)).map(([k]) => k);
158
158
  }
159
- import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
159
+ import { FILE_WRITE, SHELL_FOREGROUND } from "../tools/classes.js";
160
160
  import { backgroundJobId, finishedJob, stillInBackground } from "../tools/background-result.js";
161
- const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
161
+ // A prose / document deliverable (markdown, a report, plain text) is verified by a CONTENT or DOC check,
162
+ // never a code test/build — so a research write-up must not read as "not verified" just because no test ran.
163
+ const PROSE_EXT_RE = /\.(?:md|markdown|mdx|mdc|txt|text|rst|adoc|asciidoc)$/i;
164
+ /** A content check of a written file — read it back (wc/cat/head/tail/sed -n/grep) or lint the prose
165
+ * (markdownlint, markdown-link-check, vale, …). This is what verifies a document deliverable. */
166
+ function isContentCheckCmd(cmd) {
167
+ if (!cmd || /\$\(|`/.test(cmd))
168
+ return false;
169
+ return /(?:^|\|\||&&|[;|]\s*)\s*(?:wc|cat|head|tail|less|more|nl|bat|fold|markdownlint|markdownlint-cli2|markdown-link-check|lychee|vale|mdl|textlint|cspell)\b/.test(cmd) ||
170
+ /(?:^|\|\||&&|[;|]\s*)\s*sed\s+-n\b/.test(cmd) ||
171
+ /(?:^|\|\||&&|[;|]\s*)\s*grep\b[^|]*\.(?:md|txt|markdown|rst)\b/i.test(cmd);
172
+ }
162
173
  /** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
163
174
  * Turn-scoped (one runTurn = one task): a verify from an earlier turn must not satisfy this turn's new
164
175
  * changes — the same reason grandmaster re-derives `verified` per result and never trusts prior state. */
@@ -166,6 +177,8 @@ export class TaskVerification {
166
177
  mutated = false;
167
178
  verified = false;
168
179
  verifiedStrong = false; // a STRONG verify ran+passed (test/build/typecheck/run) — the enforced-gate signal
180
+ codeMutated = false; // a NON-prose (code/config) file changed → a real test/build is the verify
181
+ contentChecked = false; // a content/doc check ran (read the file back, or a prose linter) — verifies a doc deliverable
169
182
  ran = new Set(); // run at all this turn: a piped `tsc | head` exits 0 whatever it found
170
183
  latest = new Map(); // each check's LAST result this turn: null = it passed
171
184
  background = new Map(); // job id → the check it runs, started after the last change, result unread
@@ -176,12 +189,16 @@ export class TaskVerification {
176
189
  const name = names[i];
177
190
  let res = results[i] ?? "";
178
191
  let cmd = (commands[i] ?? "").trim();
179
- let shell = VERIFY_TOOLS.has(name);
192
+ let shell = SHELL_FOREGROUND.has(name);
180
193
  // a change makes every earlier check stale, a job started before it included: only a check that runs after the last change verifies it
181
- if (MUTATING_TOOLS.has(name) && !/^error/i.test(res.trim())) {
194
+ if (FILE_WRITE.has(name) && !/^error/i.test(res.trim())) {
182
195
  this.mutated = true;
183
- this.verified = this.verifiedStrong = false;
196
+ this.verified = this.verifiedStrong = this.contentChecked = false;
184
197
  this.background.clear();
198
+ // file_edit/file_write report "edited <path>" / "wrote <path>"; a non-prose (or unknown) path needs a real test/build.
199
+ const path = /^(?:edited|wrote|created|updated)\s+(\S+)/i.exec(res.trim())?.[1] ?? "";
200
+ if (!path || !PROSE_EXT_RE.test(path))
201
+ this.codeMutated = true;
185
202
  }
186
203
  const jobId = shell || name === "shell_background" ? backgroundJobId(res) : undefined;
187
204
  if (jobId && isVerifyCmd(cmd))
@@ -200,6 +217,8 @@ export class TaskVerification {
200
217
  this.verified = true;
201
218
  if (isStrongVerifyCmd(cmd))
202
219
  this.verifiedStrong = true;
220
+ if (isContentCheckCmd(cmd))
221
+ this.contentChecked = true;
203
222
  }
204
223
  if (shell && !/^error running command:/i.test(res.trim()) && !stillInBackground(res))
205
224
  for (const k of checksRun(cmd))
@@ -232,13 +251,24 @@ export class TaskVerification {
232
251
  changedFiles() {
233
252
  return this.mutated;
234
253
  }
235
- /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path). */
254
+ /** A document/prose deliverable: files changed but NONE were code/config — it is verified by a content or
255
+ * doc check, not a code test. (Falls back to "treat as code" when a mutation's path can't be read.) */
256
+ proseOnly() {
257
+ return this.mutated && !this.codeMutated;
258
+ }
259
+ /** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate (ADVISORY path).
260
+ * A prose/doc deliverable is instead cleared by a content/doc check — so a verified report never reads "not verified". */
236
261
  gate() {
262
+ if (this.proseOnly())
263
+ return !this.contentChecked;
237
264
  return this.mutated && !this.verified;
238
265
  }
239
266
  /** True ⇒ changed code but never ran a STRONG (test/build/typecheck/run) check ⇒ the ENFORCED hard
240
- * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it). */
267
+ * precondition for unattended turns (an allowlisted-but-empty command like `npm ls` does NOT clear it).
268
+ * A prose/doc deliverable has no code to strong-verify, so it is never held for a test/build. */
241
269
  gateStrong() {
270
+ if (this.proseOnly())
271
+ return false;
242
272
  return this.mutated && !this.verifiedStrong;
243
273
  }
244
274
  /** The checks `answer` reports as clean that never ran this turn ⇒ nudge, then annotate. */
@@ -8,7 +8,10 @@ import { join } from "node:path";
8
8
  import { ToolchainError, isManaged, resolveToolchainBin, storeEntryMeta, storeEntryOf, verifyState } from "./config/toolchain.js";
9
9
  import { formatAge } from "./memory/session-catalog.js";
10
10
  import { isLaunchdDisabled } from "./services/preflight.js";
11
+ import { BUILTIN_MODELS, findModel, isRetired } from "./router/models.js";
11
12
  const LABEL = "co.0perator.gateway";
13
+ /** The catalog row this gateway serves (Aurora). While it is retired, `start` needs --force. */
14
+ const GATEWAY_MODEL_ID = "operator-1m";
12
15
  function paths() {
13
16
  const home = process.env.OPERATOR_HOME || join(homedir(), ".operator"); // the runtime's home, not the CLI's config home
14
17
  return {
@@ -80,9 +83,10 @@ function mappedExecutable(pid) {
80
83
  const r = spawnSync("/usr/sbin/lsof", ["-nP", "-a", "-p", String(pid), "-d", "txt", "-Fn"], { encoding: "utf8", timeout: 5000 });
81
84
  return r.status === 0 ? r.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) : undefined;
82
85
  }
83
- const USAGE = `usage: operator gateway {start [-d]|stop|status|health|logs}
86
+ const USAGE = `usage: operator gateway {start [-d] [--force]|stop|status|health|logs}
84
87
  start run the gateway in the foreground
85
88
  start -d start it through launchd (${LABEL})
89
+ --force start it although its model is retired
86
90
  stop stop the gateway and its llama-server
87
91
  status gateway, llama-server, models, binary and toolchain
88
92
  health llama-server /health
@@ -92,7 +96,14 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
92
96
  const [cmd = "status", ...rest] = args;
93
97
  switch (cmd) {
94
98
  case "start": {
95
- if (rest[0] === "-d") {
99
+ const force = rest.includes("--force");
100
+ const opts = rest.filter((a) => a !== "--force");
101
+ const served = findModel(BUILTIN_MODELS, GATEWAY_MODEL_ID);
102
+ if (isRetired(served) && !force) {
103
+ out(`${served.label} (${GATEWAY_MODEL_ID}) is retired — not starting the gateway. Run with --force to start it anyway.`);
104
+ return 1;
105
+ }
106
+ if (opts[0] === "-d") {
96
107
  if (!existsSync(p.plist)) {
97
108
  out(`${p.plist} is not installed — run operator-runtime/scripts/install.sh first.`);
98
109
  return 1;
@@ -107,7 +118,7 @@ export async function runGateway(args, out = (s) => process.stdout.write(s + "\n
107
118
  out(code === 0 ? "gateway started through launchd" : "launchctl kickstart failed");
108
119
  return code;
109
120
  }
110
- return spawnSync(process.execPath, [p.gateway, ...rest], { stdio: "inherit" }).status ?? 1;
121
+ return spawnSync(process.execPath, [p.gateway, ...opts], { stdio: "inherit" }).status ?? 1;
111
122
  }
112
123
  case "stop": {
113
124
  launchctl(["bootout", `${domain()}/${LABEL}`]);