@0perator/operator 0.1.337 → 0.1.339

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.
@@ -80,7 +80,7 @@ export function estimateTokensHeuristic(messages) {
80
80
  }
81
81
  return Math.ceil(chars / 4);
82
82
  }
83
- function fullRequestEstimate(conversation, opts) {
83
+ export function fullRequestEstimate(conversation, opts) {
84
84
  const system = opts.systemPrompt ? [{ role: "system", content: opts.systemPrompt }] : [];
85
85
  // Calibrated path: the meter's ONE char basis (requestChars — content + tool_calls JSON + schemas,
86
86
  // plus chat-template overhead) measured at the endpoint's learned ratio. Replaces both the chars/4
@@ -99,14 +99,47 @@ export function usageRatio(conversation, opts) {
99
99
  export function needsCompaction(conversation, opts) {
100
100
  return usageRatio(conversation, opts) >= (opts.threshold ?? 0.7);
101
101
  }
102
- /** Proactive-compaction trigger for the harness gate: fire on the window-fraction threshold OR the absolute
103
- * `ceilingTokens` (whichever hits first). Kept SEPARATE from needsCompaction so the over-window circuit
102
+ /** The part of every request compaction can never shrink: the system prompt + tool schemas, measured on the same
103
+ * basis as fullRequestEstimate (calibrated per endpoint when metered). 0 when neither is set. */
104
+ export function fixedRequestTokens(opts) {
105
+ if (!opts.systemPrompt && !opts.tools?.length)
106
+ return 0;
107
+ return fullRequestEstimate([], opts);
108
+ }
109
+ // The conversation always gets at least min(ceiling, this) tokens above the fixed part. 2026-10-30: the fixed part
110
+ // alone (≈12.8K system + ≈18.2K for 102 tool schemas) was over the 24K interactive ceiling, so the ceiling could
111
+ // never be met — the gate fired every round and compaction evicted to the last 4 turns, which still held every big
112
+ // tool output (session 512d2b4f sat at 110-125K). The interactive default's 24K becomes the conversation's budget.
113
+ const MIN_CONVERSATION_TOKENS = 24_000;
114
+ // Hysteresis: a ceiling-triggered compaction sheds down to this fraction of the conversation budget, not just under
115
+ // the line — every compaction rewrites history and resets the server's prompt cache, so it must not run every round.
116
+ const CEILING_HYSTERESIS = 0.5;
117
+ /** The absolute proactive trigger actually applied: fixed + max(ceiling − fixed, min(ceiling, 24K)). Equal to
118
+ * `ceilingTokens` whenever that leaves the conversation 24K; above it only when the fixed part crowds it out.
119
+ * Recomputed per request from the CURRENT endpoint's prompt, tools and meter, so it follows `/model`. */
120
+ export function effectiveCeilingTokens(opts) {
121
+ const ceiling = opts.ceilingTokens;
122
+ if (!ceiling || ceiling <= 0)
123
+ return undefined;
124
+ const fixed = fixedRequestTokens(opts);
125
+ return fixed + Math.max(ceiling - fixed, Math.min(ceiling, MIN_CONVERSATION_TOKENS));
126
+ }
127
+ /** Proactive-compaction trigger for the harness gate: fire on the window-fraction threshold OR the effective
128
+ * absolute ceiling (whichever hits first). Kept SEPARATE from needsCompaction so the over-window circuit
104
129
  * breaker keeps testing only the real window — a soft speed ceiling must never be able to "stop" a turn. */
105
130
  export function shouldProactivelyCompact(conversation, opts) {
106
131
  if (needsCompaction(conversation, opts))
107
132
  return true;
108
- const ceiling = opts.ceilingTokens;
109
- return !!ceiling && ceiling > 0 && fullRequestEstimate(conversation, opts) >= ceiling;
133
+ const ceiling = effectiveCeilingTokens(opts);
134
+ return ceiling !== undefined && fullRequestEstimate(conversation, opts) >= ceiling;
135
+ }
136
+ /** Where a ceiling-triggered shed stops: fixed + CEILING_HYSTERESIS of the conversation budget. */
137
+ function ceilingTargetTokens(opts) {
138
+ const ceiling = effectiveCeilingTokens(opts);
139
+ if (ceiling === undefined)
140
+ return undefined;
141
+ const fixed = fixedRequestTokens(opts);
142
+ return fixed + Math.floor((ceiling - fixed) * CEILING_HYSTERESIS);
110
143
  }
111
144
  /** Last-resort shrink that GUARANTEES a request fits a known-real window. compact() evicts OLD turns; when
112
145
  * the over-budget bulk lives INSIDE the kept turns — one turn that dumped tens of KB of tool output (a
@@ -117,21 +150,42 @@ export function shouldProactivelyCompact(conversation, opts) {
117
150
  * rarely need re-reading — and the tool_call_id pairing is preserved so the message sequence stays valid.
118
151
  * Returns a new array; the input is never mutated. If eliding every tool output still won't fit (huge
119
152
  * user/assistant prose), it returns the maximally-elided array so the caller still sends the SMALLEST
120
- * possible request rather than a guaranteed-fatal one. */
153
+ * possible request rather than a guaranteed-fatal one.
154
+ * Without an explicit `targetRatio` it then sheds on to the ceiling's hysteresis target (ceilingTargetTokens) when
155
+ * `ceilingTokens` is set — the bulk of a long interactive session lives in the kept turns, and the window ratio alone
156
+ * (0.7 of 262K) never touched it. That soft pass leaves the trailing tool results alone: the model has not read
157
+ * them yet, and they are shed on the next compaction once it has. */
121
158
  export function fitToWindow(conversation, opts, targetRatio) {
122
- const target = targetRatio ?? opts.threshold ?? 0.7;
123
- if (usageRatio(conversation, opts) < target)
159
+ const hard = opts.ctxWindow > 0 ? opts.ctxWindow * (targetRatio ?? opts.threshold ?? 0.7) : Infinity;
160
+ const soft = targetRatio === undefined ? ceilingTargetTokens(opts) : undefined;
161
+ const target = soft !== undefined ? Math.min(hard, soft) : hard;
162
+ if (fullRequestEstimate(conversation, opts) < target)
124
163
  return [...conversation];
125
- const out = conversation.map((m) => ({ ...m }));
164
+ let out = shedToolOutputs(conversation.map((m) => ({ ...m })), opts, hard, 0);
165
+ if (soft !== undefined && soft < hard) {
166
+ let unseen = out.length;
167
+ while (unseen > 0 && out[unseen - 1].role === "tool")
168
+ unseen--;
169
+ out = shedToolOutputs(out, opts, soft, out.length - unseen);
170
+ }
171
+ return out;
172
+ }
173
+ const isShedStub = (content) => /^\[large tool output (offloaded|elided) to fit/.test(content);
174
+ /** Shed tool outputs in place (largest first) until the request estimate is under `targetTokens`, never touching
175
+ * the last `protectTail` messages. */
176
+ function shedToolOutputs(out, opts, targetTokens, protectTail) {
177
+ if (fullRequestEstimate(out, opts) < targetTokens)
178
+ return out;
179
+ const limit = out.length - protectTail;
126
180
  // Tool messages, largest content first — shed the worst offenders until it fits. GW-10-COMPLETE:
127
181
  // error-ish results go LAST (Manus doctrine — a failed tool trace in context suppresses repeat
128
182
  // mistakes; a success's bytes are re-fetchable from the spill file, the failure's lesson is not).
129
183
  const byLargest = out
130
- .map((m, i) => ({ i, len: m.role === "tool" ? m.content.length : 0, err: /^(error[:\s]|\(no output; exit)/i.test(m.content) }))
184
+ .map((m, i) => ({ i, len: m.role === "tool" && i < limit && !isShedStub(m.content) ? m.content.length : 0, err: /^(error[:\s]|\(no output; exit)/i.test(m.content) }))
131
185
  .filter((x) => x.len > 0)
132
186
  .sort((a, b) => (a.err === b.err ? b.len - a.len : a.err ? 1 : -1));
133
187
  for (const { i } of byLargest) {
134
- if (usageRatio(out, opts) < target)
188
+ if (fullRequestEstimate(out, opts) < targetTokens)
135
189
  break;
136
190
  const was = out[i].content.length;
137
191
  const p = opts.spill ? opts.spill(out[i].content) : null;
@@ -188,10 +242,13 @@ export function pickSummaryContent(content, reasoning) {
188
242
  /** An engine-injected user-role message (nudges, reminders, notes — continuation.ts::engineNote) is not a turn the
189
243
  * owner started and not the owner's voice: compaction must neither count it as a turn boundary nor quote it back. */
190
244
  const isEngineNote = (m) => typeof m.content === "string" && m.content.startsWith("[engine note");
245
+ // A compaction summary rides in the user role too, but it is not a turn: counted as one, the next gate saw minKeep+1
246
+ // "turns" and evicted just the summary — a summarize call and a rewritten history head (full re-prefill) EVERY round.
247
+ const isCompactedSummary = (m) => typeof m.content === "string" && m.content.startsWith("[Compacted summary");
191
248
  export function turnStarts(conversation) {
192
249
  const idxs = [];
193
250
  conversation.forEach((m, i) => {
194
- if (m.role === "user" && !isEngineNote(m))
251
+ if (m.role === "user" && !isEngineNote(m) && !isCompactedSummary(m))
195
252
  idxs.push(i);
196
253
  });
197
254
  return idxs;
@@ -352,14 +409,17 @@ export async function compact(conversation, opts) {
352
409
  summaryText = (await opts.summarize(evicted)).trim();
353
410
  }
354
411
  catch {
412
+ opts.onSkip?.("summarizer_error");
355
413
  return [...conversation];
356
414
  }
357
415
  // Never destroy the evicted span behind an EMPTY summary. If the summarizer produced nothing (e.g.
358
416
  // a model that spent its whole token budget on reasoning and returned empty content — hosts should
359
417
  // pass content||reasoningContent, but guard here regardless), SKIP this compaction rather than replace
360
418
  // real history with a bare "[Compacted summary of N]" header. The caller retries; nothing is lost.
361
- if (!summaryText)
419
+ if (!summaryText) {
420
+ opts.onSkip?.("empty_summary");
362
421
  return [...conversation];
422
+ }
363
423
  // GW-31: the deterministic backstop rides with the model's note — identifiers and the user's own
364
424
  // words are preserved by CODE, not by asking nicely. Dedup logic: the prompt rule stays (a good
365
425
  // summary embeds specifics in prose); these blocks guarantee nothing critical was dropped.
@@ -28,6 +28,8 @@ export function isMutatingCall(name, rawArgs) {
28
28
  args = JSON.parse(rawArgs || "{}");
29
29
  }
30
30
  catch { /* partial args: treat as text */ }
31
+ if (name === "tool_call")
32
+ return isMutatingCall(String(args.name ?? ""), JSON.stringify(args.args ?? {})); // deferredTools
31
33
  if (name === "git_command") {
32
34
  const cmd = String(args.command ?? args.args ?? rawArgs ?? "");
33
35
  return !/^\s*(?:git\s+)?(?:status|log|diff|show|branch|remote|rev-parse|blame|ls-files)\b/.test(cmd);
@@ -23,6 +23,11 @@ export function inferType(objective) {
23
23
  return "plan";
24
24
  if (/\b(review|audit|critique|assess|check .* for)\b/.test(s))
25
25
  return "review";
26
+ // Web research about an outside subject (a company, market, person, product) is not a repo search: typed
27
+ // "search", a 10/30 "research IMI International" agent was handed a file-path schema and listed ~/work.
28
+ if (/\b(research|investigate|competitors?|market|industry|company|companies|news|website|online)\b/.test(s)
29
+ && !/\b(repo|repository|codebase|code|file|files|function|class|module|grep|path|test|tests)\b/.test(s))
30
+ return "research";
26
31
  if (/\b(search|find|look up|research|locate|grep|where is)\b/.test(s))
27
32
  return "search";
28
33
  if (/\b(edit|fix|implement|add|refactor|write|create|change|rename|update|build)\b/.test(s))
@@ -34,6 +39,7 @@ export function schemaHintFor(type) {
34
39
  switch (type) {
35
40
  case "code-edit": return `{ "summary": "<what changed, 1-2 lines>", "files_changed": ["path", ...], "verify_command": "<cmd that proves it, e.g. npm test>", "verified": true|false }`;
36
41
  case "search": return `{ "summary": "<what you found>", "results": [{ "path": "...", "detail": "..." }] }`;
42
+ case "research": return `{ "summary": "<the answer in 2-4 lines>", "findings": [{ "claim": "...", "source": "<url>" }], "sources": ["<url>", ...] }`;
37
43
  case "review": return `{ "summary": "<overall>", "findings": [{ "severity": "high|med|low", "where": "path:line", "issue": "...", "fix": "..." }] }`;
38
44
  case "plan": return `{ "summary": "<the plan in one line>", "steps": ["step 1", "step 2", ...], "risks": ["..."] }`;
39
45
  default: return `{ "summary": "<result>", "detail": "<any specifics>" }`;
@@ -42,10 +48,64 @@ export function schemaHintFor(type) {
42
48
  const REQUIRED = {
43
49
  "code-edit": ["summary", "files_changed"],
44
50
  search: ["summary", "results"],
51
+ research: ["summary", "findings"],
45
52
  review: ["summary", "findings"],
46
53
  plan: ["summary", "steps"],
47
54
  generic: ["summary"],
48
55
  };
56
+ function defaultContext(type, cwd) {
57
+ if (type === "research")
58
+ return "This is WEB research about an outside subject. Use web_search and web_fetch, and cite a source URL " +
59
+ "for every finding. It is not about the owner's own projects or files: do not read local files unless the Objective names a path.";
60
+ return `Working directory: ${cwd}. Inspect the repo with your tools; do not assume anything not stated or verifiable.`;
61
+ }
62
+ // Sub-agent roles (design: _ai-docs/design/2026-10-30-subagent-experts-and-capability-catalog.md). A sub-agent gets
63
+ // a role prompt and a role-scoped tool set instead of a clone of the owner's session — the 10/30 demo agent
64
+ // inherited the owner's project list and every tool, and researched the owner's files instead of the web.
65
+ // Tool lists are allowlists of registry names; undefined = every tool (the previous behaviour, kept for code-edit
66
+ // and generic). skill_list / skill_fetch ride in every list: the catalog is how a scoped role reaches more.
67
+ const CATALOG_TOOLS = ["skill_list", "skill_fetch", "task_add", "task_list", "task_update", "scratchpad"];
68
+ const READ_TOOLS = ["file_read", "read_files", "grep_search", "search", "find_files", "list_directory", "glob",
69
+ "git_status", "code_search", "codebase_search", "lsp_diag"];
70
+ const WEB_TOOLS = ["web_search", "web_fetch", "deep_research", "browser_read", "knowledge_search"];
71
+ export const SUBAGENT_ROLES = {
72
+ research: {
73
+ title: "researcher", projectContext: false, maxRounds: 20,
74
+ tools: [...WEB_TOOLS, "file_read", "read_files", "image_analyze", ...CATALOG_TOOLS],
75
+ prompt: "You are a research specialist. Answer from primary, current sources on the web: search broadly, then read " +
76
+ "the best pages in full (web_fetch) rather than trusting snippets. Every finding carries the URL it came from; say " +
77
+ "so plainly when sources disagree or a fact could not be confirmed. The subject is outside this machine — never " +
78
+ "inspect local files or the owner's projects unless the brief names a path. After every two or three sources, write a " +
79
+ "short running summary of what you have found so far (with URLs) in your reply text: if you are stopped early, that " +
80
+ "summary is what gets returned. Aim to finish within about 12 rounds — answer with what you have rather than " +
81
+ "fetching more pages that repeat it.",
82
+ },
83
+ search: {
84
+ title: "code searcher", projectContext: true, tools: [...READ_TOOLS, ...CATALOG_TOOLS],
85
+ prompt: "You are a code-search specialist. Locate exactly what the brief asks for in the working tree and report " +
86
+ "file:line pointers with one line each on why it matters. Read-only: you cannot and must not change files.",
87
+ },
88
+ review: {
89
+ title: "reviewer", projectContext: true, tools: [...READ_TOOLS, "security_scan", "web_fetch", "web_search", ...CATALOG_TOOLS],
90
+ prompt: "You are a senior code reviewer. Find real defects — correctness, security, data loss, concurrency — each " +
91
+ "with path:line, why it is wrong and the fix. Verify a suspicion by reading the code before reporting it; no " +
92
+ "style nits unless asked. Read-only: you cannot and must not change files.",
93
+ },
94
+ plan: {
95
+ title: "planner", projectContext: true, tools: [...READ_TOOLS, ...WEB_TOOLS, ...CATALOG_TOOLS],
96
+ prompt: "You are a technical planner. Ground the plan in what the code and sources actually show, give ordered " +
97
+ "steps a builder can execute, and name the risks and how each is checked. Read-only: you plan, you do not build.",
98
+ },
99
+ "code-edit": {
100
+ title: "builder", projectContext: true,
101
+ prompt: "You are a builder. Make the change in the smallest correct way, match the surrounding code, and prove it " +
102
+ "with a real test or build before you report done.",
103
+ },
104
+ generic: {
105
+ title: "assistant", projectContext: true,
106
+ prompt: "You are a focused assistant sub-agent. Do exactly what the brief asks and report the result concisely.",
107
+ },
108
+ };
49
109
  /** The shared, structured core of EVERY sub-agent brief — one enterprise standard used by both spawn_agent
50
110
  * (buildBrief, which appends a typed JSON final_answer) and delegate_task (delegateBrief, which appends a
51
111
  * verbatim-result instruction). Consolidating the structure here is what keeps the two paths consistent:
@@ -61,7 +121,7 @@ export function briefCore(input, cwd) {
61
121
  input.objective.trim(),
62
122
  "",
63
123
  "## Context",
64
- input.context?.trim() || `Working directory: ${cwd}. Inspect the repo with your tools; do not assume anything not stated or verifiable.`,
124
+ input.context?.trim() || defaultContext(input.type, cwd),
65
125
  "",
66
126
  "## Deliverable",
67
127
  input.deliverable?.trim() || "Achieve the objective, then report concisely what you did and where.",
@@ -75,7 +135,7 @@ export function briefCore(input, cwd) {
75
135
  export function buildBrief(input, cwd) {
76
136
  const type = input.type ?? inferType(input.objective);
77
137
  return [
78
- ...briefCore(input, cwd),
138
+ ...briefCore({ ...input, type }, cwd),
79
139
  "",
80
140
  "## Final answer (required)",
81
141
  "When finished, your LAST output must be ONLY a fenced ```json block matching this schema — no prose after it:",
@@ -274,7 +334,7 @@ export function routeLane(brief, hint) {
274
334
  if (hint?.heavy)
275
335
  return "reasoning";
276
336
  const type = hint?.type;
277
- if (type === "plan" || type === "review")
337
+ if (type === "plan" || type === "review" || type === "research")
278
338
  return "reasoning";
279
339
  const long = brief.length > 1200;
280
340
  const mechanical = /\b(rename|grep|format|lint|list|count|read|locate|find)\b/i.test(brief);
@@ -282,3 +342,42 @@ export function routeLane(brief, hint) {
282
342
  return "fast";
283
343
  return long ? "reasoning" : "fast";
284
344
  }
345
+ /** What a sub-agent had found when it was stopped, stalled or ran out of rounds — returned in place of a bare
346
+ * "[stopped]" so its work is never thrown away (10/30: two research agents ran 8 rounds each, were stopped, and
347
+ * every finding was lost). Built from the child's own conversation: its latest notes, the pages it read, the
348
+ * searches it ran, and short excerpts of the last pages. Pure: the caller passes session.snapshot(). */
349
+ export function partialReport(msgs, why) {
350
+ const urls = [];
351
+ const queries = [];
352
+ const fetchIds = new Set();
353
+ for (const m of msgs) {
354
+ if (m.role !== "assistant" || !m.tool_calls)
355
+ continue;
356
+ for (const c of m.tool_calls) {
357
+ let a = {};
358
+ try {
359
+ a = JSON.parse(c.function.arguments || "{}");
360
+ }
361
+ catch { /* unparseable args: skip */ }
362
+ if ((c.function.name === "web_fetch" || c.function.name === "browser_read") && typeof a.url === "string") {
363
+ urls.push(a.url);
364
+ fetchIds.add(c.id);
365
+ }
366
+ if ((c.function.name === "web_search" || c.function.name === "deep_research") && typeof (a.query ?? a.question) === "string")
367
+ queries.push(String(a.query ?? a.question));
368
+ }
369
+ }
370
+ const notes = [...msgs].reverse().find((m) => m.role === "assistant" && m.content.trim() && !m.content.startsWith("[engine note"))?.content.trim() ?? "";
371
+ const excerpts = msgs.filter((m) => m.role === "tool" && m.tool_call_id && fetchIds.has(m.tool_call_id) && m.content.trim())
372
+ .slice(-2).map((m) => m.content.replace(/\s+/g, " ").trim().slice(0, 600));
373
+ const uniq = (xs) => [...new Set(xs)];
374
+ const parts = [`[${why} — PARTIAL findings below, gathered before it ended; verify before relying on them]`];
375
+ parts.push(notes ? `Notes so far:\n${notes.slice(0, 3000)}` : "Notes so far: (none written yet)");
376
+ if (urls.length)
377
+ parts.push(`Sources read (${uniq(urls).length}):\n${uniq(urls).slice(0, 15).map((u) => `- ${u}`).join("\n")}`);
378
+ if (queries.length)
379
+ parts.push(`Searches run: ${uniq(queries).slice(0, 8).map((q) => `"${q}"`).join(" · ")}`);
380
+ if (excerpts.length)
381
+ parts.push(`Last pages read (excerpts):\n${excerpts.map((e) => `> ${e}`).join("\n")}`);
382
+ return parts.join("\n\n");
383
+ }