@0perator/operator 0.1.327 → 0.1.330

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.
@@ -0,0 +1,40 @@
1
+ // A finished sub-agent's report reaches the model BETWEEN turns, the way a finished background shell job does
2
+ // (tools/shell-jobs.ts): the shell queues the report here when the agent finishes, the next turn's prompt opens
3
+ // with every queued report, and an idle shell starts that turn by itself (the wake). Before 0.1.328 the report was
4
+ // only drawn on screen (a 500-char "done" line in the transcript panel) — the model never saw it, so every
5
+ // "its result auto-posts, END YOUR TURN" instruction asked the model to give up the one way it had of learning the
6
+ // outcome, and the turns that kept polling were the ones that worked. Side-effect-free store: the shell decides
7
+ // when to wake; a surface without a shell never queues.
8
+ const REPORT_CHARS = 8000; // the spawn brief asks for a ~1-2k token report; a runaway one is clipped, never dropped
9
+ const reports = [];
10
+ const listeners = new Set();
11
+ const clip = (s, n) => s.length <= n ? s : s.slice(0, n) + `\n… [report clipped at ${n} chars — re-run the sub-agent with a tighter deliverable if the rest matters]`;
12
+ /** The notice the model reads: who finished, then the report verbatim, framed as the self-report it is. */
13
+ export function formatAgentReport(agent, result) {
14
+ return [
15
+ `[system notice] sub-agent ${agent.id} (${agent.label}) finished. Its report follows — a SELF-REPORT: verify any ` +
16
+ `side effect it claims (writes, pushes, uploads) before telling the owner it happened.`,
17
+ clip(result.trim() || "(no output)", REPORT_CHARS),
18
+ ].join("\n");
19
+ }
20
+ /** Queue a finished agent's report for the next turn and tell the shell (which wakes an idle session). */
21
+ export function queueAgentReport(agent, result) {
22
+ reports.push(formatAgentReport(agent, result));
23
+ for (const fn of listeners) {
24
+ try {
25
+ fn();
26
+ }
27
+ catch { /* a bad listener must not lose a report */ }
28
+ }
29
+ }
30
+ export function pendingAgentReports() {
31
+ return reports.length;
32
+ }
33
+ /** Take every queued report (joined), or "" when none. Called at the start of a turn. */
34
+ export function drainAgentReports() {
35
+ return reports.length ? reports.splice(0).join("\n\n") : "";
36
+ }
37
+ export function onAgentReport(fn) {
38
+ listeners.add(fn);
39
+ return () => { listeners.delete(fn); };
40
+ }
package/dist/bus/inbox.js CHANGED
@@ -68,7 +68,21 @@ export function buildMentorWake(incoming, allow) {
68
68
  if (!toWake.length)
69
69
  return null;
70
70
  return (`[mentor-wake] ${toWake.length} new bus message(s) arrived — review and act on them now:\n\n` +
71
- toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n"));
71
+ toWake.map((m) => `--- from ${m.from}${m.subject ? ` · ${m.subject}` : ""} (${m.ts}) ---\n${m.body}`).join("\n\n") +
72
+ `\n\n${replyProtocol([...new Set(toWake.map((m) => m.from))])}`);
73
+ }
74
+ /** The reply contract a woken turn owes its sender, spelled out in the frame itself. The sender is another agent
75
+ * on the bus and cannot see this screen: a turn that works in silence is invisible to the teacher, and the plan
76
+ * message BEFORE the work is what lets the teacher stop a wrong plan early. It lived only in memories.md until
77
+ * 2026-10-28, when a lesson wake went straight to the fix round and never posted — the model treated "post your
78
+ * plan first" in the lesson body as optional; the frame is the one place every wake passes through. */
79
+ export function replyProtocol(senders) {
80
+ const send = senders.map((s) => `\`switch send ${s} "…"\``).join(" / ");
81
+ return (`Reply protocol — the sender cannot see this screen. Read what the message points you at, then, BEFORE any other ` +
82
+ `action (no edit, build, search or spawn first), send ONE plan message back with ${send}: what you understood, the ` +
83
+ `steps you will take, what you will verify. Then do the work. When it is done, send ONE report the same way: what ` +
84
+ `changed (files, commit), what you verified and HOW, what is still open. A woken turn that acts without the plan ` +
85
+ `message or ends without the report has broken the protocol.`);
72
86
  }
73
87
  /** Per-source cooldown selection for wake-on-mentor (ping-pong guard). From a buffer of pending wake messages,
74
88
  * return the subset whose source last woke the session at least `cooldownMs` ago — a source's FIRST message is
package/dist/cli.js CHANGED
@@ -37,6 +37,7 @@ import { hasByoToken } from "./auth/byo.js";
37
37
  import { getDiscoveredModels } from "./router/discovery.js";
38
38
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
39
39
  import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
40
+ import { drainAgentReports, onAgentReport, pendingAgentReports, queueAgentReport } from "./background/notices.js";
40
41
  import { lastActiveAt as idleLastActiveAt, resolveIdlePolicy, startIdleMonitor, touchWork } from "./idle/index.js";
41
42
  import { disposeBrowserNow } from "./browser/session.js";
42
43
  import { EventSink, defaultEventsFile } from "./telemetry/events.js";
@@ -664,8 +665,8 @@ function Root() {
664
665
  // id, got "no background job", and concluded the sub-agent had been evicted — then re-spawned a
665
666
  // duplicate onto the one shared endpoint (the actual live bug, 09-26). State the auto-post + the
666
667
  // real status path plainly instead.
667
- return `spawned background sub-agent ${id}. Its result auto-posts to THIS conversation when done — ` +
668
- `keep working, do not poll it. Do NOT call bash_output/bash_kill on ${id} (that's for shell_background ` +
668
+ return `spawned background sub-agent ${id}. Its report is delivered as a message at the start of your NEXT turn — ` +
669
+ `it cannot reach you mid-turn, so do not poll for it. Do NOT call bash_output/bash_kill on ${id} (that's for shell_background ` +
669
670
  `jobs only and will just error). Use agent_status to check on it, or message_agent to nudge it. ` +
670
671
  `Never re-spawn ${id}'s task assuming it was lost — it wasn't. When nothing else is independent of ${id}, ` +
671
672
  `give a one-line status and END YOUR TURN — its report resumes this conversation; a turn that keeps ` +
@@ -705,6 +706,9 @@ function Root() {
705
706
  }
706
707
  return "no sub-agents spawned this session yet.";
707
708
  },
709
+ // Read by a WAKE turn only: with sub-agents still running, the turn that delivers one report yields from its
710
+ // first idle round (it folds the report in, then ends) instead of checking on the others while they starve.
711
+ liveAgents: () => bgRef.current?.list().filter((a) => a.status === "working" || a.status === "queued").length ?? 0,
708
712
  // stop_agent: cancel one sub-agent (a real id) or every running/queued one (undefined = "all").
709
713
  // BackgroundAgents.requestStop(All) already posts the "[stopped by user]" note via onDone — this
710
714
  // handler just relays whether there was anything to stop.
@@ -745,6 +749,7 @@ function Root() {
745
749
  eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // a sub-agent's tool calls belong to THIS session in the ledger
746
750
  }), 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.
747
751
  (agent, result) => {
752
+ 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
748
753
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.id} (${agent.label}) done:\n${result.slice(0, 500)}` } }]);
749
754
  setBgAgents(bgRef.current.list());
750
755
  }, settings.endpoints.aurora.model, // model name recorded on each child for UI surfacing (grandmaster §5)
@@ -944,15 +949,20 @@ function Root() {
944
949
  })();
945
950
  }, []);
946
951
  const sendTurn = useCallback(async (text, opts) => {
947
- // Finished background shell jobs are announced at the start of the next turn (capped notices, never the
948
- // full output). A wake turn has no user text: the notices are the whole prompt.
949
- const notices = drainJobNotices();
952
+ // Finished background shell jobs and finished sub-agents are announced at the start of the next turn (job notices
953
+ // are capped, never the full output; a sub-agent's report goes in full — it IS the deliverable). A wake turn has
954
+ // no user text: the notices are the whole prompt.
955
+ const reports = drainAgentReports();
956
+ const notices = [drainJobNotices(), reports].filter(Boolean).join("\n\n");
950
957
  if (notices) {
951
958
  const heads = notices.split("\n\n").map((n) => "⤷ " + n.split("\n")[0].replace(/^\[system notice\] /, "")).join("\n");
952
959
  push({ kind: "message", message: { id: nextId(), role: "system", content: heads } });
953
960
  remoteRef.current?.system(heads);
954
961
  }
955
- const toSend = (notices ? notices + "\n\n" : "") + (opts?.wake ? "A background job finished (notice above). Continue the task if it matters; otherwise reply in one line." : text);
962
+ const wakePrompt = reports
963
+ ? "A sub-agent reported (notice above). Fold the report into the task: verify any side effect it claims, update the task list, do what depended on it. When every part is in, give the owner the result; if parts are still running, one line of status and end the turn."
964
+ : "A background job finished (notice above). Continue the task if it matters; otherwise reply in one line.";
965
+ const toSend = (notices ? notices + "\n\n" : "") + (opts?.wake ? wakePrompt : text);
956
966
  if (!opts?.wake) {
957
967
  push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
958
968
  remoteRef.current?.userPrompt(text); // mirror to followers
@@ -1119,7 +1129,7 @@ function Root() {
1119
1129
  setTasks(getAgentTasks()); // refresh the plan pane
1120
1130
  setStat("thinking");
1121
1131
  },
1122
- }, turnDirective);
1132
+ }, turnDirective, { wake: opts?.wake === true });
1123
1133
  // A completed (not interrupted) turn while still in plan mode counts as "a plan was proposed" —
1124
1134
  // arms the exit-time Approve & run picker (see applyMode).
1125
1135
  if (!outcome.interrupted && session.inPlanMode())
@@ -1184,7 +1194,7 @@ function Root() {
1184
1194
  setStat("idle");
1185
1195
  const live = bg.list().filter((a) => a.status === "working" || a.status === "queued");
1186
1196
  if (live.length)
1187
- push({ kind: "message", message: { id: nextId(), role: "system", content: `${live.length} sub-agent${live.length > 1 ? "s" : ""} still running — results post when done. /agents for status` } });
1197
+ push({ kind: "message", message: { id: nextId(), role: "system", content: `${live.length} sub-agent${live.length > 1 ? "s" : ""} still running — each report starts a turn here when it lands. /agents for status` } });
1188
1198
  // H4 (audit-tools §1): transcripts hold bearer tokens — they were world-readable by default.
1189
1199
  try {
1190
1200
  writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()), { mode: 0o600 });
@@ -1203,11 +1213,14 @@ function Root() {
1203
1213
  wakeIfIdleRef.current();
1204
1214
  }
1205
1215
  }, []);
1206
- // A background shell job finished (wake mode): start a turn so Operator reacts without being polled. Only when
1207
- // idle with nothing typed-ahead; otherwise the notice rides along on the next turn. Jobs ending together coalesce.
1216
+ // A background shell job finished (wake mode) or a sub-agent reported: start a turn so Operator reacts without
1217
+ // being polled. Only when idle with nothing typed-ahead; otherwise the notice rides along on the next turn. Jobs
1218
+ // or reports ending together coalesce. A sub-agent report ALWAYS wakes — delivering it is the spawn contract
1219
+ // ("its report resumes this conversation"); only shell jobs honor settings.background.jobNotices.
1208
1220
  const wakeIfIdleRef = useRef(() => { });
1209
1221
  wakeIfIdleRef.current = () => {
1210
- if (getJobNoticeMode() !== "wake" || pendingJobNotices() === 0)
1222
+ const jobs = getJobNoticeMode() === "wake" && pendingJobNotices() > 0;
1223
+ if (!jobs && pendingAgentReports() === 0)
1211
1224
  return;
1212
1225
  if (statusRef.current !== "idle" || queued.current)
1213
1226
  return;
@@ -1215,15 +1228,16 @@ function Root() {
1215
1228
  };
1216
1229
  useEffect(() => {
1217
1230
  let timer;
1231
+ const wakeSoon = () => { if (timer)
1232
+ clearTimeout(timer); timer = setTimeout(() => wakeIfIdleRef.current(), 400); };
1218
1233
  const off = onJobEvent((e) => {
1219
1234
  setShellJobs(listShellJobs().filter((j) => j.status === "running"));
1220
1235
  if (e.type !== "finished")
1221
1236
  return;
1222
- if (timer)
1223
- clearTimeout(timer);
1224
- timer = setTimeout(() => wakeIfIdleRef.current(), 400);
1237
+ wakeSoon();
1225
1238
  });
1226
- return () => { off(); if (timer)
1239
+ const offReports = onAgentReport(wakeSoon);
1240
+ return () => { off(); offReports(); if (timer)
1227
1241
  clearTimeout(timer); };
1228
1242
  }, []);
1229
1243
  const sys = useCallback((text) => {
@@ -402,7 +402,7 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
402
402
  `"let me delegate" without making that call in the same round. For independent, parallelizable subtasks ` +
403
403
  `(research per area, search a large tree, draft a file, a long build) give each a fully self-contained ` +
404
404
  `instruction — it runs on another ` +
405
- `session in parallel and posts its result back here. Do only the work that does NOT depend on it, then give ` +
405
+ `session in parallel and its report arrives here as a message at the start of your next turn. Do only the work that does NOT depend on it, then give ` +
406
406
  `a one-line status and END YOUR TURN — the result resumes the conversation; a turn that keeps polling holds ` +
407
407
  `the model slot and starves the sub-agents. Never redo a delegated subtask yourself — reading up on the topic ` +
408
408
  `you just handed off is the busywork that starves them. The user watches each ` +
@@ -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 } from "./aurora.js";
5
+ import { chat, endpointSlots } 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";
@@ -539,7 +539,7 @@ export async function runTurn(userInput, conversation, opts) {
539
539
  const guardCfg = resolveLoopGuardConfig(opts.loopGuard, { unattended: opts.unattended === true });
540
540
  const guard = guardCfg.enabled ? new LoopGuard(guardCfg) : undefined; // result-aware tool loop guard (engine/loop-guard.ts)
541
541
  const pollSpin = guardCfg.enabled ? new PollSpinGuard() : undefined; // auto-post-poller (agent_status) spin guard — a separate detector, since pollers are EXEMPT from `guard`
542
- const yieldGuard = guardCfg.enabled ? new YieldAfterDispatchGuard() : undefined; // after spawn_agent: non-mutating rounds are waiting-with-busywork — yield so the reports resume the turn
542
+ const yieldGuard = guardCfg.enabled ? new YieldAfterDispatchGuard(undefined, undefined, (opts.liveSubAgents?.() ?? 0) > 0) : undefined; // after spawn_agent (or from round one of a wake turn with sub-agents live): non-mutating rounds are waiting-with-busywork — yield so the reports resume the turn
543
543
  const noWriteProgress = guardCfg.enabled ? new NoWriteProgressGuard(guardCfg.warnInvestigateLoop, guardCfg.stopInvestigateLoop, guardCfg.hardStop) : undefined; // investigate-loop detector — catches rounds with zero mutating calls
544
544
  const rca = { succeeded: new Map(), refused: new Map() }; // normalized-fingerprint → completed exact spellings; + refusal tally (see RCA_STOP)
545
545
  const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
@@ -1170,7 +1170,7 @@ export async function runTurn(userInput, conversation, opts) {
1170
1170
  }
1171
1171
  }
1172
1172
  if (yieldGuard) {
1173
- const yg = yieldGuard.observe(response.toolCalls.map((c) => c.function.name), response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")));
1173
+ const yg = yieldGuard.observe(response.toolCalls.map((c) => c.function.name), response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")), endpointSlots(endpoint.base));
1174
1174
  if (yg.action === "halt")
1175
1175
  return stopTurn(yg.message, rounds + 1);
1176
1176
  if (yg.action === "nudge") {
@@ -1227,7 +1227,7 @@ export async function runTurn(userInput, conversation, opts) {
1227
1227
  }
1228
1228
  }
1229
1229
  if (yieldGuard) {
1230
- const yg = yieldGuard.observe(recovered.calls.map((c) => c.function.name), recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")));
1230
+ const yg = yieldGuard.observe(recovered.calls.map((c) => c.function.name), recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")), endpointSlots(endpoint.base));
1231
1231
  if (yg.action === "halt")
1232
1232
  return stopTurn(yg.message, rounds + 1);
1233
1233
  if (yg.action === "nudge") {
@@ -3,7 +3,7 @@
3
3
  import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
4
4
  import { globalTokenMeter } from "./token-meter.js";
5
5
  const _endpointGates = new Map();
6
- function endpointSlots(_base) {
6
+ export function endpointSlots(_base) {
7
7
  // One knob for now (the fleet runs one single-slot Aurora); keyed by base so a future per-endpoint override
8
8
  // slots in without touching callers. Any value < 1 is coerced to 1 — a gate must admit at least one request.
9
9
  return Math.max(1, Number(process.env.KODE_ENDPOINT_SLOTS) || 1);