@0perator/operator 0.1.338 → 0.1.340
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/autonomy/agent-cli.js +1 -1
- package/dist/autonomy/delegate.js +2 -1
- package/dist/autonomy/headless.js +1 -0
- package/dist/autonomy/session-factory.js +13 -2
- package/dist/background/index.js +8 -6
- package/dist/cli.js +60 -26
- package/dist/config/features.js +7 -0
- package/dist/config/persona.js +134 -231
- package/dist/engine/agent.js +17 -2
- package/dist/engine/aurora.js +3 -0
- package/dist/engine/compaction.js +74 -14
- package/dist/engine/decision-points.js +2 -0
- package/dist/engine/grandmaster.js +102 -3
- package/dist/session.js +121 -93
- package/dist/tools/deferred.js +137 -0
- package/dist/tools/registry.js +223 -242
- package/package.json +1 -1
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
|
|
84
|
-
"
|
|
85
|
-
"
|
|
86
|
-
"
|
|
87
|
-
"
|
|
88
|
-
"
|
|
89
|
-
"
|
|
90
|
-
"
|
|
91
|
-
"
|
|
92
|
-
"
|
|
93
|
-
"
|
|
94
|
-
"(
|
|
95
|
-
"
|
|
96
|
-
"
|
|
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: "
|
|
106
|
-
task: { type: "string", description: "
|
|
107
|
-
|
|
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 (
|
|
137
|
-
"
|
|
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: "
|
|
144
|
-
text: { type: "string", description: "the message
|
|
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
|
|
166
|
-
"
|
|
167
|
-
"
|
|
168
|
-
"
|
|
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
|
|
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
|
|
191
|
-
"
|
|
192
|
-
"
|
|
193
|
-
"
|
|
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: "
|
|
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
|
|
213
|
-
"
|
|
214
|
-
"
|
|
215
|
-
"
|
|
216
|
-
"
|
|
217
|
-
"
|
|
218
|
-
"
|
|
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: "
|
|
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: "
|
|
216
|
+
multiSelect: { type: "boolean", description: "allow several choices (default false)" },
|
|
228
217
|
},
|
|
229
218
|
required: ["question", "options"],
|
|
230
219
|
},
|
|
@@ -249,32 +238,30 @@ function makeSelfStatusTool(facts) {
|
|
|
249
238
|
return {
|
|
250
239
|
name: "self_status",
|
|
251
240
|
safe: true,
|
|
252
|
-
description: "Your OWN live runtime facts:
|
|
253
|
-
"
|
|
254
|
-
"
|
|
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
|
};
|
|
260
247
|
}
|
|
261
248
|
// The `skill_activate` / `skill_deactivate` pair — unlike skill_fetch (skill text returned as tool-result
|
|
262
|
-
// DATA), activation
|
|
263
|
-
//
|
|
264
|
-
//
|
|
249
|
+
// DATA), activation makes the skill's instructions a standing directive for every subsequent turn, until
|
|
250
|
+
// deactivated or replaced. The directive rides in the conversation, never the system prompt: a system prompt
|
|
251
|
+
// that changes mid-session makes llama.cpp re-read every tool schema and the whole conversation (see
|
|
252
|
+
// Session.activateSkill). The fetch itself reuses the registry's skill_fetch (profile skills first, then hub),
|
|
253
|
+
// so activation accepts any slug skill_fetch does.
|
|
254
|
+
const skillHeader = (name) => `## Active skill: ${name}`;
|
|
265
255
|
function makeSkillActivateTool(activate) {
|
|
266
256
|
return {
|
|
267
257
|
name: "skill_activate",
|
|
268
258
|
safe: false,
|
|
269
|
-
description: "Activate a skill as a
|
|
270
|
-
"
|
|
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.",
|
|
259
|
+
description: "Activate a skill as a standing directive for the rest of the session — to FOLLOW a skill, not just read" +
|
|
260
|
+
" it (that is skill_fetch). One at a time; a new one replaces the last.",
|
|
274
261
|
parameters: {
|
|
275
262
|
type: "object",
|
|
276
263
|
properties: {
|
|
277
|
-
name: { type: "string", description: "
|
|
264
|
+
name: { type: "string", description: "the skill slug (as for skill_fetch)" },
|
|
278
265
|
},
|
|
279
266
|
required: ["name"],
|
|
280
267
|
},
|
|
@@ -290,7 +277,7 @@ function makeSkillDeactivateTool(deactivate) {
|
|
|
290
277
|
return {
|
|
291
278
|
name: "skill_deactivate",
|
|
292
279
|
safe: true,
|
|
293
|
-
description: "
|
|
280
|
+
description: "Stop following the active skill. No-op if no skill is active.",
|
|
294
281
|
parameters: { type: "object", properties: {} },
|
|
295
282
|
run: async () => deactivate(),
|
|
296
283
|
};
|
|
@@ -329,6 +316,7 @@ export class Session {
|
|
|
329
316
|
sessionId;
|
|
330
317
|
mcpSchemas = []; // merged in after first-turn discovery (empty until then)
|
|
331
318
|
deferred = null; // HV3-04: set when the MCP surface crosses the threshold
|
|
319
|
+
nativeDeferred = null; // `deferredTools` flag: fixed core + tool_search/tool_call
|
|
332
320
|
wantMcp; // mutable: `/mcp on` flips it for the live session (enableMcp)
|
|
333
321
|
systemPrompt;
|
|
334
322
|
maxTokens;
|
|
@@ -361,8 +349,9 @@ export class Session {
|
|
|
361
349
|
planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
|
|
362
350
|
thinkMode = "off"; // /think, /ultrathink — extended reasoning
|
|
363
351
|
recalled = false;
|
|
364
|
-
activeSkillBlock = ""; // capped skill instructions
|
|
352
|
+
activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
|
|
365
353
|
activeSkillName = ""; // name of the active skill (for status display)
|
|
354
|
+
skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
|
|
366
355
|
// Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
|
|
367
356
|
// maintains a structured session-memory/summary.md during the session. When compact() fires,
|
|
368
357
|
// it loads the pre-written summary — /compact went from up to 2 minutes to instant.
|
|
@@ -378,7 +367,7 @@ export class Session {
|
|
|
378
367
|
// on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
|
|
379
368
|
globalTokenMeter.setPersistence(operatorPath("token-calibration.json"));
|
|
380
369
|
// Per-session tool registry: the base set, plus session-scoped tools (skill_activate/skill_deactivate
|
|
381
|
-
// are always available since they
|
|
370
|
+
// are always available since they hold THIS session's active skill; spawn_agent/message_agent/
|
|
382
371
|
// ask_user only when the shell provides delegate handlers). Both the executor (dispatch) and
|
|
383
372
|
// localSchemas (what the model sees) are built from the same map, so a tool is advertised iff runnable.
|
|
384
373
|
const reg = new Map(registry);
|
|
@@ -389,13 +378,13 @@ export class Session {
|
|
|
389
378
|
const content = await fetchTool.run({ slug: name });
|
|
390
379
|
if (content.startsWith("error:"))
|
|
391
380
|
return content;
|
|
392
|
-
this.activateSkill(name, content);
|
|
393
|
-
return `skill '${name}' activated — its instructions are now injected into the system prompt. Deactivate with skill_deactivate.`;
|
|
381
|
+
return this.activateSkill(name, content);
|
|
394
382
|
}));
|
|
395
383
|
reg.set("skill_deactivate", makeSkillDeactivateTool(() => {
|
|
396
384
|
const was = this.activeSkillName;
|
|
397
385
|
this.deactivateSkill();
|
|
398
|
-
|
|
386
|
+
this.skillNote = ""; // this tool result already tells the model
|
|
387
|
+
return was ? `skill '${was}' deactivated — stop following its instructions` : "no skill was active";
|
|
399
388
|
}));
|
|
400
389
|
// Flag-gated cloud-agent tools (config/features.ts `cloudAgents`): absent from the base registry, merged in
|
|
401
390
|
// here only when the flag resolves on — so both dispatch (executor) and the advertised schemas include them iff enabled.
|
|
@@ -425,9 +414,19 @@ export class Session {
|
|
|
425
414
|
})));
|
|
426
415
|
for (const t of cloudTools)
|
|
427
416
|
reg.set(t.name, t);
|
|
417
|
+
if (cfg.toolAllow) {
|
|
418
|
+
const allow = new Set([...cfg.toolAllow, "self_status"]);
|
|
419
|
+
for (const name of [...reg.keys()])
|
|
420
|
+
if (!allow.has(name))
|
|
421
|
+
reg.delete(name);
|
|
422
|
+
}
|
|
428
423
|
this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
|
|
429
424
|
this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
|
|
430
425
|
this.localSchemas = toSchemas(reg);
|
|
426
|
+
// Main sessions only: a sub-agent's prompt (subagentSystemPrompt) lists its tools as attached, and a role's
|
|
427
|
+
// allowlist is already small.
|
|
428
|
+
if (!cfg.toolAllow && !cfg.background && isFeatureEnabled("deferredTools", { features: cfg.features }))
|
|
429
|
+
this.nativeDeferred = nativeCatalog(this.localSchemas);
|
|
431
430
|
this.setContextPin(cfg.contextPin); // before the first wrap(): the engine router reads the pin live
|
|
432
431
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
433
432
|
this.router = this.wrap(this.inner);
|
|
@@ -503,15 +502,13 @@ export class Session {
|
|
|
503
502
|
`commands resolve in the working directory. This is authoritative over any working dir named elsewhere; create ` +
|
|
504
503
|
`files there unless the owner names another path.${SESSION_CONTEXT_CLOSE}`;
|
|
505
504
|
}
|
|
506
|
-
/** The effective system prompt: the base persona plus any memory recalled this session
|
|
507
|
-
*
|
|
508
|
-
*
|
|
505
|
+
/** The effective system prompt: the base persona plus any memory recalled this session. Injected as ONE system
|
|
506
|
+
* prompt — never a second system message, which 400s llama.cpp's chat template. An active skill is NOT here
|
|
507
|
+
* (activateSkill). */
|
|
509
508
|
sys() {
|
|
510
509
|
let base = this.recallBlock
|
|
511
510
|
? (this.systemPrompt ? `${this.systemPrompt}\n\n${this.recallBlock}` : this.recallBlock)
|
|
512
511
|
: this.systemPrompt;
|
|
513
|
-
if (this.activeSkillBlock)
|
|
514
|
-
base = (base ?? "") + this.activeSkillBlock;
|
|
515
512
|
base = (base ?? "") + this.activeModelBlock() + this.sessionContextBlock();
|
|
516
513
|
if (!this.planMode)
|
|
517
514
|
return base;
|
|
@@ -550,7 +547,6 @@ export class Session {
|
|
|
550
547
|
ctxWindow,
|
|
551
548
|
ceilingTokens: this.compactionCeilingTokens,
|
|
552
549
|
wallClockMs: this.maxTurnWallClockMs,
|
|
553
|
-
sessionTokens: this.sessionTokensTotal,
|
|
554
550
|
});
|
|
555
551
|
}
|
|
556
552
|
/** Compose the tool executor: local tools + MCP (composite) with the permission/audit layer on top.
|
|
@@ -564,6 +560,8 @@ export class Session {
|
|
|
564
560
|
const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
|
|
565
561
|
const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
|
|
566
562
|
const hooked = withHooks(base, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
|
|
563
|
+
if (this.nativeDeferred)
|
|
564
|
+
return withNativeDeferred(hooked, this.nativeDeferred);
|
|
567
565
|
return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
|
|
568
566
|
}
|
|
569
567
|
/** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
|
|
@@ -597,23 +595,39 @@ export class Session {
|
|
|
597
595
|
currentThinkMode() {
|
|
598
596
|
return this.thinkMode;
|
|
599
597
|
}
|
|
600
|
-
/** Activate a skill as a
|
|
601
|
-
*
|
|
602
|
-
* so
|
|
598
|
+
/** Activate a skill as a standing directive until deactivated or replaced; returns the directive. Capped at
|
|
599
|
+
* SKILL_CAP chars so a huge skill doesn't crowd working memory. The system prompt never changes mid-session —
|
|
600
|
+
* doing so made the server re-read tools + conversation on the next request — so the directive rides in the
|
|
601
|
+
* conversation tail instead: as skill_activate's tool result, or (for /skill) on the owner's next message, and
|
|
602
|
+
* after a compaction evicts it, in the summary (pinnedSkill). */
|
|
603
603
|
activateSkill(name, content) {
|
|
604
604
|
const capped = content.length > SKILL_CAP
|
|
605
605
|
? content.slice(0, SKILL_CAP) + "\n\n[… skill truncated at " + SKILL_CAP + " chars]"
|
|
606
606
|
: content;
|
|
607
|
-
this.
|
|
607
|
+
const replaces = this.activeSkillName && this.activeSkillName !== name ? ` It replaces skill '${this.activeSkillName}' — stop following that one.` : "";
|
|
608
|
+
this.activeSkillBlock = `${skillHeader(name)}\nFollow these instructions for this task until skill_deactivate.${replaces}\n\n${capped}`;
|
|
608
609
|
this.activeSkillName = name;
|
|
610
|
+
this.skillNote = "";
|
|
611
|
+
return this.activeSkillBlock;
|
|
609
612
|
}
|
|
610
613
|
deactivateSkill() {
|
|
614
|
+
if (this.activeSkillName)
|
|
615
|
+
this.skillNote = `[Skill '${this.activeSkillName}' is no longer active — stop following its instructions.]`;
|
|
611
616
|
this.activeSkillBlock = "";
|
|
612
617
|
this.activeSkillName = "";
|
|
613
618
|
}
|
|
614
619
|
currentSkill() {
|
|
615
620
|
return this.activeSkillName || null;
|
|
616
621
|
}
|
|
622
|
+
/** The active skill's directive when the conversation no longer carries it (never delivered, or compacted
|
|
623
|
+
* away); undefined otherwise. */
|
|
624
|
+
pinnedSkill() {
|
|
625
|
+
if (!this.activeSkillBlock)
|
|
626
|
+
return undefined;
|
|
627
|
+
const header = skillHeader(this.activeSkillName);
|
|
628
|
+
const carried = this.convo.all.some((m) => typeof m.content === "string" && m.content.includes(header));
|
|
629
|
+
return carried ? undefined : this.activeSkillBlock;
|
|
630
|
+
}
|
|
617
631
|
/** Is the currently-selected endpoint reachable? Lets the shell fail clearly before a turn. */
|
|
618
632
|
health() {
|
|
619
633
|
return health(this.inner.base);
|
|
@@ -716,6 +730,7 @@ export class Session {
|
|
|
716
730
|
systemPrompt: this.sys(),
|
|
717
731
|
summarize: this.summarize,
|
|
718
732
|
preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
|
|
733
|
+
pinnedContext: this.activeSkillBlock || undefined,
|
|
719
734
|
minKeepTurns: 2,
|
|
720
735
|
tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
|
|
721
736
|
meter: globalTokenMeter,
|
|
@@ -748,7 +763,7 @@ export class Session {
|
|
|
748
763
|
// render-side and mechanical — the "instant" property is untouched (microseconds, zero calls).
|
|
749
764
|
const summaryMsg = {
|
|
750
765
|
role: "user",
|
|
751
|
-
content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}`,
|
|
766
|
+
content: `[Compacted summary (pre-written — instant)]:\n${prewritten}${renderAnchorIndex(evicted)}${verbatimUserTail(evicted)}${opts.pinnedContext ? `\n\n${opts.pinnedContext}` : ""}`,
|
|
752
767
|
};
|
|
753
768
|
const kept = this.convo.all.slice(cutIndex);
|
|
754
769
|
this.convo.replaceAll([summaryMsg, ...kept]);
|
|
@@ -1050,7 +1065,9 @@ export class Session {
|
|
|
1050
1065
|
this.mcpSchemas = this.hub.schemas();
|
|
1051
1066
|
// HV3-04: when the MCP surface is fat, its schemas stop riding every request — they move
|
|
1052
1067
|
// behind tool_search/describe/call meta-tools, loaded on demand.
|
|
1053
|
-
this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
|
|
1068
|
+
this.deferred = !this.nativeDeferred && deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
|
|
1069
|
+
if (this.nativeDeferred)
|
|
1070
|
+
setNativeCatalogMcp(this.nativeDeferred, this.mcpSchemas);
|
|
1054
1071
|
this.tools = this.buildTools(); // rebind again so the deferred layer wraps the permission stack
|
|
1055
1072
|
}
|
|
1056
1073
|
catch { /* gateway unreachable — stay local-only */ }
|
|
@@ -1078,7 +1095,9 @@ export class Session {
|
|
|
1078
1095
|
await this.hub.discover({ force: true });
|
|
1079
1096
|
this.tools = this.buildTools();
|
|
1080
1097
|
this.mcpSchemas = this.hub.schemas();
|
|
1081
|
-
this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
|
|
1098
|
+
this.deferred = !this.nativeDeferred && deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
|
|
1099
|
+
if (this.nativeDeferred)
|
|
1100
|
+
setNativeCatalogMcp(this.nativeDeferred, this.mcpSchemas);
|
|
1082
1101
|
this.tools = this.buildTools();
|
|
1083
1102
|
}
|
|
1084
1103
|
catch { /* stay local-only */ }
|
|
@@ -1087,6 +1106,8 @@ export class Session {
|
|
|
1087
1106
|
/** Local registry schemas plus any fleet MCP tool schemas discovered this session.
|
|
1088
1107
|
* Under HV3-04 deferral: locals + only the MCP tools described this session + the meta trio. */
|
|
1089
1108
|
allSchemas() {
|
|
1109
|
+
if (this.nativeDeferred)
|
|
1110
|
+
return this.nativeDeferred.request; // byte-identical every turn, MCP or not
|
|
1090
1111
|
if (this.deferred)
|
|
1091
1112
|
return deferredRequestSchemas(this.localSchemas, this.deferred);
|
|
1092
1113
|
return this.mcpSchemas.length ? [...this.localSchemas, ...this.mcpSchemas] : this.localSchemas;
|
|
@@ -1272,6 +1293,10 @@ export class Session {
|
|
|
1272
1293
|
// for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
|
|
1273
1294
|
// message itself, so everything from here on is this turn's.
|
|
1274
1295
|
const convoStart = this.convo.all.length;
|
|
1296
|
+
const carry = [this.skillNote, this.pinnedSkill()].filter(Boolean).join("\n\n");
|
|
1297
|
+
this.skillNote = "";
|
|
1298
|
+
if (carry)
|
|
1299
|
+
text = `${carry}\n\n${text}`;
|
|
1275
1300
|
try {
|
|
1276
1301
|
const res = await runTurn(text, this.convo, {
|
|
1277
1302
|
router,
|
|
@@ -1280,6 +1305,7 @@ export class Session {
|
|
|
1280
1305
|
spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
|
|
1281
1306
|
systemPrompt: sys,
|
|
1282
1307
|
summarize: this.summarize,
|
|
1308
|
+
pinnedContext: () => this.activeSkillBlock || undefined, // a summary is a rewrite anyway: the skill rides it
|
|
1283
1309
|
preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
|
|
1284
1310
|
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
1285
1311
|
liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
|
|
@@ -1305,7 +1331,9 @@ export class Session {
|
|
|
1305
1331
|
onToolBatch: h.onToolBatch,
|
|
1306
1332
|
onAutoContinue: h.onAutoContinue,
|
|
1307
1333
|
onCacheStats: h.onCacheStats,
|
|
1334
|
+
onServed: h.onServed,
|
|
1308
1335
|
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
1336
|
+
onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
|
|
1309
1337
|
// Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
|
|
1310
1338
|
// local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
|
|
1311
1339
|
// still goes to telemetry so dashboards can count incidents without reading content.
|
package/dist/tools/deferred.js
CHANGED
|
@@ -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
|
+
}
|