@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.
package/dist/session.js CHANGED
@@ -26,7 +26,7 @@ import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudA
26
26
  import { isFeatureEnabled } from "./config/features.js";
27
27
  import { MemoryStore } from "./memory/index.js";
28
28
  import { McpHub, withMcp } from "./mcp/index.js";
29
- import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred } from "./tools/deferred.js";
29
+ import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
30
30
  import { withPermissions, PermissionPolicy } from "./permissions/index.js";
31
31
  import { withHooks } from "./hooks/index.js";
32
32
  import { Telemetry } from "./observability/index.js";
@@ -56,6 +56,9 @@ export function thinkDirective(mode) {
56
56
  }
57
57
  /** Render the per-turn BUDGET block that makes the model self-pace (pure, so it's unit-testable). Each line
58
58
  * is omitted when its value is unset/zero; returns "" when nothing is known. See Session.budgetDirective. */
59
+ // No per-turn counters here ("session spent so far: ~Nk"): this block rides in the system prompt, and a value that
60
+ // changes every turn invalidated the server's prompt cache for the tools and the whole conversation after it — measured
61
+ // 2026-10-30 on Cortana: ~58K tokens (~115 s) re-read on every new owner message.
59
62
  export function renderBudgetBlock(b) {
60
63
  const k = (n) => `${Math.round(n / 1000)}k`;
61
64
  const lines = [];
@@ -66,9 +69,6 @@ export function renderBudgetBlock(b) {
66
69
  if (b.wallClockMs && b.wallClockMs > 0) {
67
70
  lines.push(`- This turn's time budget: ~${Math.round(b.wallClockMs / 1000)}s of wall-clock (a crawling turn is wrapped at the limit).`);
68
71
  }
69
- if (b.sessionTokens && b.sessionTokens > 0) {
70
- lines.push(`- Session spent so far: ~${k(b.sessionTokens)} tokens.`);
71
- }
72
72
  if (!lines.length)
73
73
  return "";
74
74
  return `\n\n## BUDGET — pace yourself\nYou run under a bounded budget. The engine auto-compacts and wraps a crawling turn, but don't rely on it:\n${lines.join("\n")}\nKeep tool results LEAN (fetch fewer items, narrow queries, one thing at a time), converge toward the deliverable instead of exploring indefinitely, and if a turn is clearly dragging — long wall-clock, big context, round after round of the same tool — SUMMARIZE what you have and stop or hand back rather than spinning.`;
@@ -80,31 +80,27 @@ function makeSpawnTool(handler) {
80
80
  return {
81
81
  name: "spawn_agent",
82
82
  safe: false,
83
- description: "Spawn sub-agents: isolated sessions on the same model, each with its own shell; only each one's final report " +
84
- "returns — delivered as a message at the start of your NEXT turn, never mid-turn. Pass every subtask in `tasks` — one entry spawns " +
85
- "one sub-agent, several run in parallel (2 at a time plus 2 queued by default — settings.background.maxConcurrent; " +
86
- "past the cap the call tells you). When you decide to delegate, make THIS call in the same round — never announce " +
87
- "\"I'll spawn sub-agents\" without calling spawn_agent. Keep working meanwhile: NEVER sleep, poll or wait for a " +
88
- "result (agent_status checks state, message_agent steers, stop_agent halts; a sub-agent id is NOT a shell job id — " +
89
- "bash_output/bash_kill will just error). NEVER re-spawn a task because its result hasn't arrived — it is still " +
90
- "working. Then finish only what does NOT depend on them, give a one-line status and END YOUR TURN — reports " +
91
- "re-enter as new messages; a turn that keeps polling holds the model slot and starves the sub-agents (on a " +
92
- "single-slot endpoint the engine ends the turn itself once you have dispatched and have no independent work in the round).\n" +
93
- "USE FOR: reasoning-heavy subtasks, work that would flood your context, or independent parallel workstreams " +
94
- "(research per area, review per module, search per tree, drafting a file).\n" +
95
- "DO NOT USE FOR: a single tool call; mechanical steps with no reasoning; anything that needs the user (sub-agents " +
96
- "cannot ask); edits to the same files from several agents.\n" +
97
- "RULES: the sub-agent knows NOTHING of this conversation — put every path, id and fact in the brief, as a spec: " +
98
- "**Objective** · **Context** · **Deliverable** · **Constraints** · **Done** (how it proves success). A sub-agent's " +
99
- "report is a SELF-REPORT — verify side effects (writes, pushes, uploads) yourself before telling the user they " +
100
- "happened. SINGLE WRITER: keep file edits on one agent (you) and delegate READ / SEARCH / REVIEW / DRAFT work. " +
101
- "Ask for a CONCISE report (findings + file:line, ~1-2k tokens) — it lands in your context.",
83
+ description: "Spawn sub-agents: isolated sessions on the same model, each with its own shell. One `tasks` entry = one " +
84
+ "sub-agent; several run in parallel (2 running + 2 queued by default). Each one's final report arrives as a " +
85
+ "message at the start of your NEXT turn. Make THIS call in the same round you decide to delegate, finish only" +
86
+ " what does NOT depend on them, give a one-line status and END YOUR TURN — never sleep, poll or re-spawn a " +
87
+ "task whose report hasn't arrived; a polling turn starves them. agent_status checks, message_agent steers, " +
88
+ "stop_agent halts (a sub-agent id is not a shell job id).\n" +
89
+ "USE FOR: reasoning-heavy or context-flooding subtasks, independent parallel workstreams (research per area, " +
90
+ "review per module, search per tree, drafting a file).\n" +
91
+ "DO NOT USE FOR: a single tool call; mechanical steps; anything that needs the user; edits to the same files " +
92
+ "from several agents.\n" +
93
+ "RULES: the sub-agent knows NOTHING of this conversation — brief it as a spec: **Objective** · **Context** " +
94
+ "(every path, id, fact) · **Deliverable** · **Constraints** · **Done**. A report is a SELF-REPORT — verify " +
95
+ "side effects (writes, pushes, uploads) yourself. SINGLE WRITER: keep file edits on one agent. Ask for a " +
96
+ "CONCISE report (~1-2k tokens).",
102
97
  parameters: {
103
98
  type: "object",
104
99
  properties: {
105
- 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." },
106
- task: { type: "string", description: "A single brief (the same as a one-entry `tasks`)." },
107
- 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." },
100
+ tasks: { type: "array", items: { type: "string" }, description: "the brief(s); one entry per sub-agent" },
101
+ task: { type: "string", description: "a single brief (same as a one-entry `tasks`)" },
102
+ role: { type: "string", enum: ["research", "search", "review", "plan", "code-edit", "generic"], description: "research = web research on an outside subject (web tools only, cites URLs); search = find things in this repo; review = code review; plan = a plan (those three read-only); code-edit = change files (own worktree); generic. Omit to infer from the brief." },
103
+ agent: { type: "string", description: "optional repo-local persona from .operator/agents/ (listed under 'Repo-local harness')" },
108
104
  },
109
105
  },
110
106
  run: async (args) => {
@@ -112,6 +108,8 @@ function makeSpawnTool(handler) {
112
108
  if (!briefs.length)
113
109
  return "error: spawn_agent needs `tasks` (an array of briefs — one per sub-agent) or `task`";
114
110
  const agent = String(args.agent ?? "").trim();
111
+ const roleArg = String(args.role ?? "").trim();
112
+ const role = ["research", "search", "review", "plan", "code-edit", "generic"].includes(roleArg) ? roleArg : undefined;
115
113
  // A named repo-local persona: prepend it to the brief (the bg factory uses a fixed system prompt, so the
116
114
  // persona rides in the task — a self-contained, low-risk way to specialize the sub-agent).
117
115
  const persona = agent ? operatorAgentPersona(agent) : undefined;
@@ -119,10 +117,10 @@ function makeSpawnTool(handler) {
119
117
  ? `You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`
120
118
  : `${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`;
121
119
  if (briefs.length === 1)
122
- return handler(frame(briefs[0]));
120
+ return handler(frame(briefs[0]), role);
123
121
  // Fan-out: one spawn per brief, in order; the manager queues past its running cap and refuses past the
124
122
  // in-flight cap — each line reports what happened to that brief, so a partial fan-out is never silent.
125
- return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t))}`).join("\n");
123
+ return briefs.map((t, i) => `[${i + 1}/${briefs.length}] ${handler(frame(t), role)}`).join("\n");
126
124
  },
127
125
  };
128
126
  }
@@ -133,15 +131,13 @@ function makeMessageTool(handler) {
133
131
  return {
134
132
  name: "message_agent",
135
133
  safe: false,
136
- description: "Send a message to a background sub-agent that is STILL RUNNING (see the background panel, or " +
137
- "agent_status, for ids like agent-1). It receives the message as a follow-up turn and continues — use " +
138
- "it to steer, add context, or answer something it asked. No-op if the agent already finished. Pair " +
139
- "with spawn_agent for two-way work.",
134
+ description: "Send a message to a background sub-agent that is STILL RUNNING (ids like agent-1): it continues with it as a" +
135
+ " follow-up turn — steer it, add context, answer its question. No-op once it has finished.",
140
136
  parameters: {
141
137
  type: "object",
142
138
  properties: {
143
- id: { type: "string", description: "the sub-agent id, e.g. agent-1" },
144
- text: { type: "string", description: "the message to deliver to that running sub-agent" },
139
+ id: { type: "string", description: "sub-agent id, e.g. agent-1" },
140
+ text: { type: "string", description: "the message" },
145
141
  },
146
142
  required: ["id", "text"],
147
143
  },
@@ -162,16 +158,13 @@ function makeStatusTool(handler) {
162
158
  return {
163
159
  name: "agent_status",
164
160
  safe: true,
165
- description: "Check on background sub-agents WITHOUT re-spawning them. Omit `id` to list every sub-agent spawned " +
166
- "this session with its real current status (queued/working/idle/stopped) — use this BEFORE concluding " +
167
- "one was lost, evicted, or silently dropped; it almost certainly wasn't, and its result auto-posts to " +
168
- "this conversation when it finishes. Pass `id` to check just that one. This is the only correct way to " +
169
- "poll a sub-agent — never bash_output/bash_kill (those are for shell_background jobs, a different id " +
170
- "space, and will just return an error for a sub-agent id). To actually HALT one (the user asked you to " +
171
- "stop/cancel it), use stop_agent — checking status alone doesn't stop anything.",
161
+ description: "Check background sub-agents WITHOUT re-spawning them: no `id` lists every one with its real status " +
162
+ "(queued/working/idle/stopped); `id` checks one. Use it BEFORE concluding one was lost — it almost certainly " +
163
+ "wasn't, and its report auto-posts when it finishes. bash_output/bash_kill are for shell jobs and will error " +
164
+ "on a sub-agent id. Checking doesn't stop anything — use stop_agent.",
172
165
  parameters: {
173
166
  type: "object",
174
- properties: { id: { type: "string", description: "optional: a specific sub-agent id (e.g. agent-1); omit to list all" } },
167
+ properties: { id: { type: "string", description: "optional sub-agent id; omit to list all" } },
175
168
  },
176
169
  run: async (args) => {
177
170
  const id = String(args.id ?? "").trim();
@@ -187,14 +180,13 @@ function makeStopTool(handler) {
187
180
  return {
188
181
  name: "stop_agent",
189
182
  safe: false,
190
- description: "Stop a background sub-agent — use this whenever the user asks you to stop, cancel, or kill a " +
191
- "sub-agent (or all of them); never just acknowledge it and let it keep running unseen. Pass `id` (e.g. " +
192
- "agent-1) to stop just that one; omit `id` (or pass \"all\") to stop EVERY running/queued sub-agent at " +
193
- "once. Its turn is interrupted immediately and a \"[stopped by user]\" note replaces whatever result it " +
194
- "would have posted, so it's clear it was cancelled, not lost.",
183
+ description: "Stop a background sub-agent whenever the user asks to stop, cancel or kill one (or all) — never just " +
184
+ "acknowledge it. `id` stops one; omit it (or \"all\") to stop every running/queued one. Its PARTIAL findings " +
185
+ "come back as its report. Don't stop a working sub-agent because no files appeared — it was not asked to " +
186
+ "write any; research on a busy model can take 10-30 min.",
195
187
  parameters: {
196
188
  type: "object",
197
- properties: { id: { type: "string", description: "a sub-agent id (e.g. agent-1); omit or pass \"all\" to stop every running/queued sub-agent" } },
189
+ properties: { id: { type: "string", description: "sub-agent id; omit or \"all\" for every one" } },
198
190
  },
199
191
  run: async (args) => {
200
192
  const id = String(args.id ?? "").trim();
@@ -209,22 +201,19 @@ function makeAskTool(handler) {
209
201
  return {
210
202
  name: "ask_user",
211
203
  safe: false,
212
- description: "Put a decision to the owner as a multiple-choice question; blocks until they choose, then returns the " +
213
- "chosen option(s). ASK at a decision point: before the first change of a new build, feature or multi-step " +
214
- "refactor (offer your short plan as the first option), when there are 2+ genuinely different approaches, " +
215
- "scopes or tradeoffs, or before a destructive/irreversible step. DON'T ask for routine work (a typo, a clear " +
216
- "small edit, a bug you found, running a check) or for anything you can determine from the code or the request. " +
217
- "Give 2-4 concrete options, the recommended one FIRST labelled \"(recommended)\", each a short line saying " +
218
- "what happens — the owner ALWAYS also gets a free-text 'type your own' choice, so list the likely paths, " +
219
- "don't enumerate every one. Once answered, proceed with that choice. By default the owner picks exactly ONE " +
220
- "option; set multiSelect:true when the options are not mutually exclusive (they toggle each with Space and " +
221
- "confirm the set) — the reply then lists every option they chose.",
204
+ description: "Put a decision to the owner as a multiple-choice question; blocks until they choose. ASK at a decision " +
205
+ "point: before the first change of a new build, feature or multi-step refactor (your short plan as the first " +
206
+ "option), when there are 2+ genuinely different approaches or tradeoffs, or before a destructive/irreversible" +
207
+ " step. DON'T ask for routine work (a typo, a small clear edit, a bug you found, a check) or what the code or" +
208
+ " request answers. Give 2-4 concrete options, the recommended one FIRST labelled \"(recommended)\", each a " +
209
+ "short line; the owner can always type their own. Then proceed. multiSelect:true when options are not " +
210
+ "exclusive.",
222
211
  parameters: {
223
212
  type: "object",
224
213
  properties: {
225
- question: { type: "string", description: "The decision, one sentence." },
214
+ question: { type: "string", description: "the decision, one sentence" },
226
215
  options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices, recommended first (labelled \"(recommended)\")." },
227
- multiSelect: { type: "boolean", description: "Allow the owner to select more than one option (default false = pick exactly one)." },
216
+ multiSelect: { type: "boolean", description: "allow several choices (default false)" },
228
217
  },
229
218
  required: ["question", "options"],
230
219
  },
@@ -249,11 +238,9 @@ function makeSelfStatusTool(facts) {
249
238
  return {
250
239
  name: "self_status",
251
240
  safe: true,
252
- description: "Your OWN live runtime facts: active model + route, context % used, session token total, the " +
253
- "max-output-tokens cap, thinking mode, permission mode, turn count. Call it when the user asks about " +
254
- "your model, context budget, or runtime state, or before you state one of those numbers — it is exact " +
255
- "where your own introspection is not. It returns the same facts for the whole turn, so call it at most " +
256
- "once per turn, and never call it to decide what to do next — that is not what it is for.",
241
+ description: "Your OWN live runtime facts: model + route, context % used, session tokens, max-output cap, thinking mode, " +
242
+ "permission mode, turn count. Call it (at most once per turn) when asked about these or before stating one — " +
243
+ "it is exact where introspection is not — never to decide what to do next.",
257
244
  parameters: { type: "object", properties: {} },
258
245
  run: async () => JSON.stringify(facts()),
259
246
  };
@@ -266,15 +253,12 @@ function makeSkillActivateTool(activate) {
266
253
  return {
267
254
  name: "skill_activate",
268
255
  safe: false,
269
- description: "Activate a skill as a system-prompt-level behavioral directive. Unlike skill_fetch (which returns " +
270
- "skill text as data), this injects the skill's instructions directly into the system prompt so they " +
271
- "guide your behavior for the remainder of the session (or until deactivated). Use this when you need " +
272
- "to FOLLOW a skill's instructions, not just read them. Only one skill can be active at a time — " +
273
- "activating a new one replaces the previous.",
256
+ description: "Activate a skill as a system-prompt directive for the rest of the session — to FOLLOW a skill, not just read" +
257
+ " it (that is skill_fetch). One at a time; a new one replaces the last.",
274
258
  parameters: {
275
259
  type: "object",
276
260
  properties: {
277
- name: { type: "string", description: "The skill slug (same as skill_fetch's slug param)." },
261
+ name: { type: "string", description: "the skill slug (as for skill_fetch)" },
278
262
  },
279
263
  required: ["name"],
280
264
  },
@@ -329,6 +313,7 @@ export class Session {
329
313
  sessionId;
330
314
  mcpSchemas = []; // merged in after first-turn discovery (empty until then)
331
315
  deferred = null; // HV3-04: set when the MCP surface crosses the threshold
316
+ nativeDeferred = null; // `deferredTools` flag: fixed core + tool_search/tool_call
332
317
  wantMcp; // mutable: `/mcp on` flips it for the live session (enableMcp)
333
318
  systemPrompt;
334
319
  maxTokens;
@@ -425,9 +410,19 @@ export class Session {
425
410
  })));
426
411
  for (const t of cloudTools)
427
412
  reg.set(t.name, t);
413
+ if (cfg.toolAllow) {
414
+ const allow = new Set([...cfg.toolAllow, "self_status"]);
415
+ for (const name of [...reg.keys()])
416
+ if (!allow.has(name))
417
+ reg.delete(name);
418
+ }
428
419
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
429
420
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
430
421
  this.localSchemas = toSchemas(reg);
422
+ // Main sessions only: a sub-agent's prompt (subagentSystemPrompt) lists its tools as attached, and a role's
423
+ // allowlist is already small.
424
+ if (!cfg.toolAllow && !cfg.background && isFeatureEnabled("deferredTools", { features: cfg.features }))
425
+ this.nativeDeferred = nativeCatalog(this.localSchemas);
431
426
  this.setContextPin(cfg.contextPin); // before the first wrap(): the engine router reads the pin live
432
427
  this.inner = cfg.router ?? new AuroraRouter();
433
428
  this.router = this.wrap(this.inner);
@@ -550,7 +545,6 @@ export class Session {
550
545
  ctxWindow,
551
546
  ceilingTokens: this.compactionCeilingTokens,
552
547
  wallClockMs: this.maxTurnWallClockMs,
553
- sessionTokens: this.sessionTokensTotal,
554
548
  });
555
549
  }
556
550
  /** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
@@ -564,6 +558,8 @@ export class Session {
564
558
  const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
565
559
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
566
560
  const hooked = withHooks(base, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
561
+ if (this.nativeDeferred)
562
+ return withNativeDeferred(hooked, this.nativeDeferred);
567
563
  return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
568
564
  }
569
565
  /** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
@@ -1050,7 +1046,9 @@ export class Session {
1050
1046
  this.mcpSchemas = this.hub.schemas();
1051
1047
  // HV3-04: when the MCP surface is fat, its schemas stop riding every request — they move
1052
1048
  // behind tool_search/describe/call meta-tools, loaded on demand.
1053
- this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
1049
+ this.deferred = !this.nativeDeferred && deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
1050
+ if (this.nativeDeferred)
1051
+ setNativeCatalogMcp(this.nativeDeferred, this.mcpSchemas);
1054
1052
  this.tools = this.buildTools(); // rebind again so the deferred layer wraps the permission stack
1055
1053
  }
1056
1054
  catch { /* gateway unreachable — stay local-only */ }
@@ -1078,7 +1076,9 @@ export class Session {
1078
1076
  await this.hub.discover({ force: true });
1079
1077
  this.tools = this.buildTools();
1080
1078
  this.mcpSchemas = this.hub.schemas();
1081
- this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
1079
+ this.deferred = !this.nativeDeferred && deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
1080
+ if (this.nativeDeferred)
1081
+ setNativeCatalogMcp(this.nativeDeferred, this.mcpSchemas);
1082
1082
  this.tools = this.buildTools();
1083
1083
  }
1084
1084
  catch { /* stay local-only */ }
@@ -1087,6 +1087,8 @@ export class Session {
1087
1087
  /** Local registry schemas plus any fleet MCP tool schemas discovered this session.
1088
1088
  * Under HV3-04 deferral: locals + only the MCP tools described this session + the meta trio. */
1089
1089
  allSchemas() {
1090
+ if (this.nativeDeferred)
1091
+ return this.nativeDeferred.request; // byte-identical every turn, MCP or not
1090
1092
  if (this.deferred)
1091
1093
  return deferredRequestSchemas(this.localSchemas, this.deferred);
1092
1094
  return this.mcpSchemas.length ? [...this.localSchemas, ...this.mcpSchemas] : this.localSchemas;
@@ -1305,7 +1307,9 @@ export class Session {
1305
1307
  onToolBatch: h.onToolBatch,
1306
1308
  onAutoContinue: h.onAutoContinue,
1307
1309
  onCacheStats: h.onCacheStats,
1310
+ onServed: h.onServed,
1308
1311
  onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
1312
+ onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
1309
1313
  // Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
1310
1314
  // local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
1311
1315
  // still goes to telemetry so dashboards can count incidents without reading content.
@@ -116,3 +116,140 @@ export function deferredEnabled(mcpToolCount, env) {
116
116
  return mcpToolCount > 0;
117
117
  return mcpToolCount >= DEFERRED_THRESHOLD;
118
118
  }
119
+ // ── Native deferral (feature flag `deferredTools`, default OFF) ───────────────────────────────────────────────────
120
+ // The main session's own long tail behind two FIXED meta-tools. Unlike the MCP layer above, nothing ever joins the
121
+ // request: the tools array is [core schemas + tool_search + tool_call] for the whole session, byte-identical every
122
+ // turn, so the cached prefix survives (design 2026-10-30-subagent-experts-and-capability-catalog.md, cache rule).
123
+ // Schemas reach the model only as tool RESULTS (tool_search's signatures, tool_call's validation errors). Dispatch
124
+ // goes through the wrapped executor, so permissions, plan mode and hooks apply to the real tool name.
125
+ /** Always advertised in full under native deferral: the shell/file/search/plan/web/delegation loop plus the media
126
+ * and doc tools the persona names. Everything else in the session's registry (and every MCP tool) is deferred. */
127
+ export const NATIVE_CORE_TOOLS = [
128
+ "bash", "shell_exec", "shell_background", "bash_output", "bash_kill", "download_file",
129
+ "file_read", "read_files", "file_write", "file_edit", "file_create", "list_directory", "glob", "search", "find_files",
130
+ "git_status", "git_command", "task_add", "task_list", "task_update", "task_clear", "scratchpad", "session_handoff",
131
+ "web_search", "web_fetch", "http_request", "deep_research", "browser", "browser_read",
132
+ "image_generate", "image_analyze", "video_generate", "video_analyze", "artifact_create", "document_generate",
133
+ "memory_search", "memory_store", "skill_list", "skill_fetch", "delegate_task",
134
+ "spawn_agent", "message_agent", "agent_status", "stop_agent", "ask_user", "self_status",
135
+ ];
136
+ export const NATIVE_META_NAMES = ["tool_search", "tool_call"];
137
+ const byName = (schemas) => {
138
+ const m = new Map();
139
+ for (const s of schemas) {
140
+ const n = s.function?.name;
141
+ if (n)
142
+ m.set(n, s);
143
+ }
144
+ return m;
145
+ };
146
+ export function nativeMetaSchemas() {
147
+ return [
148
+ metaSchema("tool_search", "Find a deferred tool (the capability map lists their names): returns up to 8 matches as name(arguments) — description, '*' = required. Then run one with tool_call.", { query: { type: "string", description: "words matched against tool names and descriptions; empty lists them all" } }, []),
149
+ metaSchema("tool_call", "Run a deferred tool by exact name. `args` is checked against its schema first (a mismatch returns the schema); permissions apply exactly as for a direct call.", { name: { type: "string", description: "exact tool name" }, args: { type: "object", description: "the tool's arguments" } }, ["name"]),
150
+ ];
151
+ }
152
+ export function nativeCatalog(localSchemas, core = NATIVE_CORE_TOOLS) {
153
+ const coreSet = new Set(core);
154
+ const all = byName(localSchemas);
155
+ const request = [...all.values()].filter((s) => coreSet.has(s.function.name));
156
+ return {
157
+ request: [...request, ...nativeMetaSchemas()],
158
+ native: new Map([...all].filter(([n]) => !coreSet.has(n))),
159
+ mcp: new Map(),
160
+ core: new Set(request.map((s) => s.function.name)),
161
+ };
162
+ }
163
+ /** MCP tools join the catalog, never the request (replaces the previous MCP set). */
164
+ export function setNativeCatalogMcp(cat, mcpSchemas) {
165
+ cat.mcp = byName(mcpSchemas);
166
+ }
167
+ export function nativeCatalogNames(cat) {
168
+ return [...cat.native.keys(), ...cat.mcp.keys()];
169
+ }
170
+ function catalogGet(cat, name) {
171
+ return cat.native.get(name) ?? cat.mcp.get(name);
172
+ }
173
+ function signature(s) {
174
+ const p = s.function?.parameters ?? {};
175
+ const req = new Set(p.required ?? []);
176
+ const args = Object.entries(p.properties ?? {}).map(([k, v]) => `${k}${req.has(k) ? "*" : ""}: ${Array.isArray(v?.enum) ? v.enum.map((e) => JSON.stringify(e)).join("|") : v?.type ?? "any"}`);
177
+ return `${s.function?.name}(${args.join(", ")})`;
178
+ }
179
+ function nativeSearch(cat, query) {
180
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
181
+ const scored = [];
182
+ for (const s of [...cat.native.values(), ...cat.mcp.values()]) {
183
+ const name = (s.function?.name ?? "").toLowerCase();
184
+ const text = `${name} ${(s.function?.description ?? "").toLowerCase()}`;
185
+ const score = terms.reduce((n, t) => n + (name.includes(t) ? 3 : text.includes(t) ? 1 : 0), 0);
186
+ if (!terms.length || score > 0)
187
+ scored.push([score, s]);
188
+ }
189
+ if (!scored.length)
190
+ return "tool_search: no deferred tool matches — try other words, or use a tool you already have";
191
+ scored.sort((a, b) => b[0] - a[0]);
192
+ const lines = scored.slice(0, terms.length ? 8 : 200).map(([, s]) => {
193
+ const d = (s.function?.description ?? "").replace(/\s+/g, " ");
194
+ return `${signature(s)} — ${d.length > 220 ? d.slice(0, 220) + "…" : d}`;
195
+ });
196
+ return lines.join("\n");
197
+ }
198
+ const typeOk = (t, v) => !t ? true : t === "array" ? Array.isArray(v) : t === "object" ? !!v && typeof v === "object" && !Array.isArray(v)
199
+ : t === "integer" ? Number.isInteger(v) : typeof v === t;
200
+ /** Required keys present, declared types and enums respected. Unknown keys pass (tools accept aliases). */
201
+ export function validateToolArgs(schema, args) {
202
+ const p = schema.function?.parameters ?? {};
203
+ const errs = [];
204
+ for (const k of p.required ?? [])
205
+ if (args[k] === undefined)
206
+ errs.push(`missing required \`${k}\``);
207
+ for (const [k, v] of Object.entries(args)) {
208
+ const spec = p.properties?.[k];
209
+ if (!spec || v === undefined)
210
+ continue;
211
+ if (!typeOk(spec.type, v))
212
+ errs.push(`\`${k}\` should be ${spec.type}`);
213
+ else if (Array.isArray(spec.enum) && !spec.enum.includes(v))
214
+ errs.push(`\`${k}\` must be one of ${spec.enum.map((e) => JSON.stringify(e)).join(", ")}`);
215
+ }
216
+ return errs;
217
+ }
218
+ /** Wrap the composed (permission + hooks) executor: the meta pair routes here, everything else falls through, so
219
+ * a deferred tool called directly by name still runs. tool_call is a batch barrier (it can run anything). */
220
+ export function withNativeDeferred(base, cat) {
221
+ const runMeta = async (name, args) => {
222
+ if (name === "tool_search")
223
+ return nativeSearch(cat, String(args.query ?? ""));
224
+ const target = String(args.name ?? "").trim();
225
+ const schema = catalogGet(cat, target);
226
+ if (!schema && !cat.core.has(target))
227
+ return `tool_call: '${target}' is not a tool here — run tool_search`;
228
+ const toolArgs = (args.args && typeof args.args === "object" && !Array.isArray(args.args) ? args.args : {});
229
+ if (schema) {
230
+ const errs = validateToolArgs(schema, toolArgs);
231
+ if (errs.length)
232
+ return `tool_call ${target}: ${errs.join("; ")}. Schema: ${JSON.stringify(schema.function?.parameters ?? {})}`;
233
+ }
234
+ return base.execute(target, toolArgs);
235
+ };
236
+ const isMeta = (n) => NATIVE_META_NAMES.includes(n);
237
+ const classify = (n) => (n === "tool_call" ? "barrier"
238
+ : n === "tool_search" ? "read"
239
+ : base.sched ? base.sched.classify(n) : "write");
240
+ const keys = (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a));
241
+ return {
242
+ async execute(name, args) {
243
+ return isMeta(name) ? runMeta(name, args) : base.execute(name, args);
244
+ },
245
+ async executeParallel(calls, onSettle, signal) {
246
+ return runBatch(calls, {
247
+ classify, keys,
248
+ runOne: (c) => (isMeta(c.name) ? runMeta(c.name, c.args) : base.execute(c.name, c.args)),
249
+ onSettle,
250
+ signal,
251
+ });
252
+ },
253
+ sched: { classify, keys },
254
+ };
255
+ }