@0perator/operator 0.1.61 → 0.1.153
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/CHANGELOG.md +1037 -1
- package/LICENSE +19 -0
- package/dist/acp/agent.js +103 -0
- package/dist/acp/run.js +23 -0
- package/dist/auth/client.js +4 -1
- package/dist/auth/login-intent.js +12 -0
- package/dist/autonomy/board-run.js +65 -0
- package/dist/autonomy/board.js +83 -0
- package/dist/autonomy/dream.js +71 -0
- package/dist/autonomy/headless.js +70 -0
- package/dist/autonomy/index.js +260 -0
- package/dist/autonomy/keepawake.js +84 -0
- package/dist/autonomy/loop.js +82 -0
- package/dist/autonomy/reporter.js +54 -0
- package/dist/autonomy/routine-run.js +25 -0
- package/dist/autonomy/routines.js +173 -0
- package/dist/autonomy/session-factory.js +61 -0
- package/dist/background/index.js +269 -20
- package/dist/background/worktree.js +62 -0
- package/dist/cli.js +535 -112
- package/dist/config/brand.js +81 -0
- package/dist/config/operator-harness.js +86 -0
- package/dist/config/persona.js +174 -0
- package/dist/config/settings.js +98 -9
- package/dist/engine/agent.js +447 -51
- package/dist/engine/aurora.js +180 -64
- package/dist/engine/compaction.js +97 -5
- package/dist/engine/grandmaster.js +69 -10
- package/dist/engine/router-adapter.js +3 -0
- package/dist/engine/selfheal.js +35 -0
- package/dist/engine/verify-gate.js +81 -0
- package/dist/mcp/index.js +1 -1
- package/dist/permissions/index.js +13 -7
- package/dist/router/models.js +13 -4
- package/dist/router/router.js +46 -7
- package/dist/selfimprove/index.js +88 -0
- package/dist/services/preflight.js +42 -1
- package/dist/session.js +228 -21
- package/dist/telemetry/events.js +9 -0
- package/dist/tools/executor.js +48 -24
- package/dist/tools/git-status.js +71 -0
- package/dist/tools/mutating.js +9 -0
- package/dist/tools/registry.js +214 -11
- package/dist/tools/result-cap.js +23 -0
- package/dist/tools/searxng.js +42 -2
- package/dist/ui/ActivitySpinner.js +6 -5
- package/dist/ui/App.js +23 -5
- package/dist/ui/AuthScreen.js +1 -1
- package/dist/ui/BgPanel.js +60 -5
- package/dist/ui/Composer.js +135 -13
- package/dist/ui/Header.js +14 -6
- package/dist/ui/InputRule.js +2 -1
- package/dist/ui/Markdown.js +69 -10
- package/dist/ui/Masthead.js +6 -4
- package/dist/ui/PlanPane.js +23 -0
- package/dist/ui/QuestionPrompt.js +22 -8
- package/dist/ui/StatsCard.js +15 -0
- package/dist/ui/StatusRule.js +13 -4
- package/dist/ui/SummaryCard.js +18 -0
- package/dist/ui/Table.js +114 -0
- package/dist/ui/ThinkingSpinner.js +6 -4
- package/dist/ui/ToolBatch.js +12 -0
- package/dist/ui/ToolStep.js +12 -4
- package/dist/ui/Transcript.js +30 -6
- package/dist/ui/chart.js +34 -0
- package/dist/ui/editdiff.js +84 -0
- package/dist/ui/highlight.js +89 -0
- package/dist/ui/osc.js +32 -0
- package/dist/ui/planExit.js +26 -0
- package/dist/ui/term.js +16 -0
- package/dist/ui/theme.js +60 -0
- package/dist/ui/tree.js +71 -0
- package/dist/util/slash.js +15 -0
- package/dist/util/throttle.js +28 -0
- package/package.json +10 -1
package/dist/session.js
CHANGED
|
@@ -4,10 +4,14 @@
|
|
|
4
4
|
import { runTurn, TurnAbortedError } from "./engine/agent.js";
|
|
5
5
|
import { Conversation } from "./engine/messages.js";
|
|
6
6
|
import { chat, health } from "./engine/aurora.js";
|
|
7
|
-
import {
|
|
7
|
+
import { SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, compact, fitToWindow } from "./engine/compaction.js";
|
|
8
8
|
import { engineRouter } from "./engine/router-adapter.js";
|
|
9
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
10
|
+
import { join, dirname } from "node:path";
|
|
11
|
+
import { homedir } from "node:os";
|
|
9
12
|
import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
|
|
10
13
|
import { AuroraRouter } from "./router/router.js";
|
|
14
|
+
import { operatorAgentPersona } from "./config/operator-harness.js";
|
|
11
15
|
import { modelRegistry, findModel, selectModel, endpointBase, DEFAULT_MODEL_ID } from "./router/models.js";
|
|
12
16
|
import { Executor } from "./tools/executor.js";
|
|
13
17
|
import { toSchemas, registry } from "./tools/registry.js";
|
|
@@ -15,6 +19,7 @@ import { MemoryStore } from "./memory/index.js";
|
|
|
15
19
|
import { McpHub, withMcp } from "./mcp/index.js";
|
|
16
20
|
import { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
17
21
|
import { Telemetry } from "./observability/index.js";
|
|
22
|
+
import { runSelfImprove } from "./selfimprove/index.js";
|
|
18
23
|
// The `spawn_agent` tool — a thin pass-through to the shell's delegate handler. The handler owns the
|
|
19
24
|
// policy (cap) and the reply text; the tool just guards against an empty task. safe:false so it's an
|
|
20
25
|
// action (gated when permissions are on), never run speculatively in the safe-parallel batch.
|
|
@@ -22,25 +27,128 @@ function makeSpawnTool(handler) {
|
|
|
22
27
|
return {
|
|
23
28
|
name: "spawn_agent",
|
|
24
29
|
safe: false,
|
|
25
|
-
description: "Delegate a self-contained subtask to a background sub-agent running on the same Aurora
|
|
26
|
-
"Returns immediately with the sub-agent's id; it
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
30
|
+
description: "Delegate a self-contained subtask to a background sub-agent running on the same Aurora model. " +
|
|
31
|
+
"Returns immediately with the sub-agent's id (e.g. agent-1); it runs in the background and AUTOMATICALLY " +
|
|
32
|
+
"posts its result into THIS conversation when done. It shares your ONE model endpoint — an endpoint gate " +
|
|
33
|
+
"keeps YOUR turn first and runs sub-agents one at a time in the gaps, so a sub-agent never steals your " +
|
|
34
|
+
"slot (but spawning many does NOT make them finish sooner). NEVER sleep, poll, or otherwise block to WAIT " +
|
|
35
|
+
"for a sub-agent — you do not need to; its result arrives on its own (use agent_status only to CHECK a " +
|
|
36
|
+
"state, never as a wait loop, and never `sleep` to pass time). Use it for independent, " +
|
|
37
|
+
"parallelizable work — searching a large tree, drafting a file, a long build — so the foreground " +
|
|
38
|
+
"stays responsive. The sub-agent does NOT see this conversation, so make the task fully self-contained. " +
|
|
39
|
+
"The user watches each sub-agent's live tokens and elapsed time in the background panel. Don't spawn " +
|
|
40
|
+
"for trivial work you can do inline. " +
|
|
41
|
+
"CRITICAL: you and every sub-agent share ONE model endpoint, so spawning many does NOT run them " +
|
|
42
|
+
"faster — they contend for the same model and ALL run slower (a big fan-out can crawl for many " +
|
|
43
|
+
"minutes). Use spawn_agent ONLY for genuinely independent, long-running work, and at most 1-2 at a " +
|
|
44
|
+
"time. For a linear plan, or steps that build on each other, do them YOURSELF in sequence — that is " +
|
|
45
|
+
"faster and simpler than fanning out. Prefer sequential. " +
|
|
46
|
+
"NEVER re-spawn a task because you haven't seen its result yet or assume it was \"evicted\" — it is " +
|
|
47
|
+
"still working; call agent_status (no args) to see every sub-agent's real state before concluding " +
|
|
48
|
+
"otherwise. A sub-agent id is NOT a shell_background job id — never poll it with bash_output/bash_kill " +
|
|
49
|
+
"(those are for shell_background only and will just error); use agent_status to check on it, " +
|
|
50
|
+
"message_agent to nudge it, and stop_agent to actually halt it if the user asks you to stop/cancel it.",
|
|
31
51
|
parameters: {
|
|
32
52
|
type: "object",
|
|
33
|
-
properties: {
|
|
53
|
+
properties: {
|
|
54
|
+
task: { type: "string", description: "A complete, self-contained instruction for the sub-agent." },
|
|
55
|
+
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 the sub-agent." },
|
|
56
|
+
},
|
|
34
57
|
required: ["task"],
|
|
35
58
|
},
|
|
36
59
|
run: async (args) => {
|
|
37
60
|
const task = String(args.task ?? "").trim();
|
|
38
61
|
if (!task)
|
|
39
62
|
return "error: spawn_agent needs a non-empty task";
|
|
63
|
+
const agent = String(args.agent ?? "").trim();
|
|
64
|
+
if (agent) {
|
|
65
|
+
// A named repo-local persona: prepend it to the brief (the bg factory uses a fixed system prompt,
|
|
66
|
+
// so the persona rides in the task — a self-contained, low-risk way to specialize the sub-agent).
|
|
67
|
+
const persona = operatorAgentPersona(agent);
|
|
68
|
+
if (persona)
|
|
69
|
+
return handler(`You are acting as the "${agent}" sub-agent for this repo. Follow this persona:\n\n${persona}\n\n---\nYour task:\n${task}`);
|
|
70
|
+
return handler(`${task}\n\n(note: no .operator/agents/${agent}.md persona found — ran without it)`);
|
|
71
|
+
}
|
|
40
72
|
return handler(task);
|
|
41
73
|
},
|
|
42
74
|
};
|
|
43
75
|
}
|
|
76
|
+
// The `message_agent` tool — send a mid-run message to a RUNNING background sub-agent (the reverse of
|
|
77
|
+
// spawn_agent's one-way brief): steer it, add context it now needs, or answer a question it surfaced. The
|
|
78
|
+
// child picks the message up as a follow-up turn in its own conversation. safe:false (an action).
|
|
79
|
+
function makeMessageTool(handler) {
|
|
80
|
+
return {
|
|
81
|
+
name: "message_agent",
|
|
82
|
+
safe: false,
|
|
83
|
+
description: "Send a message to a background sub-agent that is STILL RUNNING (see the background panel, or " +
|
|
84
|
+
"agent_status, for ids like agent-1). It receives the message as a follow-up turn and continues — use " +
|
|
85
|
+
"it to steer, add context, or answer something it asked. No-op if the agent already finished. Pair " +
|
|
86
|
+
"with spawn_agent for two-way work.",
|
|
87
|
+
parameters: {
|
|
88
|
+
type: "object",
|
|
89
|
+
properties: {
|
|
90
|
+
id: { type: "string", description: "the sub-agent id, e.g. agent-1" },
|
|
91
|
+
text: { type: "string", description: "the message to deliver to that running sub-agent" },
|
|
92
|
+
},
|
|
93
|
+
required: ["id", "text"],
|
|
94
|
+
},
|
|
95
|
+
run: async (args) => {
|
|
96
|
+
const id = String(args.id ?? "").trim();
|
|
97
|
+
const text = String(args.text ?? "").trim();
|
|
98
|
+
if (!id || !text)
|
|
99
|
+
return "error: message_agent needs `id` and `text`";
|
|
100
|
+
return handler(id, text);
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
// The `agent_status` tool — the legit way to check on a sub-agent instead of guessing "it must have been
|
|
105
|
+
// evicted" and re-spawning a duplicate (the actual failure mode this tool exists to close off, seen live
|
|
106
|
+
// 09-26: bash_output on a sub-agent id errored "no background job", so the model assumed it was gone and
|
|
107
|
+
// re-spawned onto the one shared endpoint). safe:true — read-only, no side effect, fine to run speculatively.
|
|
108
|
+
function makeStatusTool(handler) {
|
|
109
|
+
return {
|
|
110
|
+
name: "agent_status",
|
|
111
|
+
safe: true,
|
|
112
|
+
description: "Check on background sub-agents WITHOUT re-spawning them. Omit `id` to list every sub-agent spawned " +
|
|
113
|
+
"this session with its real current status (queued/working/idle/stopped) — use this BEFORE concluding " +
|
|
114
|
+
"one was lost, evicted, or silently dropped; it almost certainly wasn't, and its result auto-posts to " +
|
|
115
|
+
"this conversation when it finishes. Pass `id` to check just that one. This is the only correct way to " +
|
|
116
|
+
"poll a sub-agent — never bash_output/bash_kill (those are for shell_background jobs, a different id " +
|
|
117
|
+
"space, and will just return an error for a sub-agent id). To actually HALT one (the user asked you to " +
|
|
118
|
+
"stop/cancel it), use stop_agent — checking status alone doesn't stop anything.",
|
|
119
|
+
parameters: {
|
|
120
|
+
type: "object",
|
|
121
|
+
properties: { id: { type: "string", description: "optional: a specific sub-agent id (e.g. agent-1); omit to list all" } },
|
|
122
|
+
},
|
|
123
|
+
run: async (args) => {
|
|
124
|
+
const id = String(args.id ?? "").trim();
|
|
125
|
+
return handler(id || undefined);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
// The `stop_agent` tool — cancel a running/queued sub-agent (or all of them) on the user's behalf. The only
|
|
130
|
+
// way to halt a sub-agent short of the user hitting ESC or restarting Operator entirely (seen live 09-26: a
|
|
131
|
+
// sub-agent ran to round 18 / ~1100s with no way to stop it). Closes the loop opened by
|
|
132
|
+
// spawn_agent/message_agent/agent_status. safe:false — a real action, not a speculative read.
|
|
133
|
+
function makeStopTool(handler) {
|
|
134
|
+
return {
|
|
135
|
+
name: "stop_agent",
|
|
136
|
+
safe: false,
|
|
137
|
+
description: "Stop a background sub-agent — use this whenever the user asks you to stop, cancel, or kill a " +
|
|
138
|
+
"sub-agent (or all of them); never just acknowledge it and let it keep running unseen. Pass `id` (e.g. " +
|
|
139
|
+
"agent-1) to stop just that one; omit `id` (or pass \"all\") to stop EVERY running/queued sub-agent at " +
|
|
140
|
+
"once. Its turn is interrupted immediately and a \"[stopped by user]\" note replaces whatever result it " +
|
|
141
|
+
"would have posted, so it's clear it was cancelled, not lost.",
|
|
142
|
+
parameters: {
|
|
143
|
+
type: "object",
|
|
144
|
+
properties: { id: { type: "string", description: "a sub-agent id (e.g. agent-1); omit or pass \"all\" to stop every running/queued sub-agent" } },
|
|
145
|
+
},
|
|
146
|
+
run: async (args) => {
|
|
147
|
+
const id = String(args.id ?? "").trim();
|
|
148
|
+
return handler(id && id.toLowerCase() !== "all" ? id : undefined);
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
44
152
|
// The `ask_user` tool — the model pauses to ask the owner a structured multiple-choice question and gets
|
|
45
153
|
// the chosen option back as the tool result. safe:false (an interaction, not a speculative read). The
|
|
46
154
|
// handler (the shell) renders the prompt and blocks until the owner answers.
|
|
@@ -73,7 +181,7 @@ function makeAskTool(handler) {
|
|
|
73
181
|
},
|
|
74
182
|
};
|
|
75
183
|
}
|
|
76
|
-
const SUMMARY_MAX_TOKENS =
|
|
184
|
+
const SUMMARY_MAX_TOKENS = 1800; // room for Aurora's reasoning AND the 9-section contract before content lands
|
|
77
185
|
export class Session {
|
|
78
186
|
convo = new Conversation();
|
|
79
187
|
inner; // was readonly — /model rebuilds it for a "single" profile switch
|
|
@@ -96,6 +204,12 @@ export class Session {
|
|
|
96
204
|
wantMcp;
|
|
97
205
|
systemPrompt;
|
|
98
206
|
maxTokens;
|
|
207
|
+
maxTurnTokens;
|
|
208
|
+
maxRounds;
|
|
209
|
+
maxRoundsHard;
|
|
210
|
+
compactionThreshold;
|
|
211
|
+
compactionCeilingTokens;
|
|
212
|
+
background;
|
|
99
213
|
temperature;
|
|
100
214
|
ctrl = null;
|
|
101
215
|
memory;
|
|
@@ -110,14 +224,20 @@ export class Session {
|
|
|
110
224
|
// handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
|
|
111
225
|
// are built from the same map, so the tool is advertised iff it's runnable.
|
|
112
226
|
let reg = registry;
|
|
113
|
-
if (cfg.spawnAgent || cfg.askUser) {
|
|
227
|
+
if (cfg.spawnAgent || cfg.askUser || cfg.messageAgent || cfg.agentStatus || cfg.stopAgent) {
|
|
114
228
|
reg = new Map(registry);
|
|
115
229
|
if (cfg.spawnAgent)
|
|
116
230
|
reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
|
|
231
|
+
if (cfg.messageAgent)
|
|
232
|
+
reg.set("message_agent", makeMessageTool(cfg.messageAgent));
|
|
233
|
+
if (cfg.agentStatus)
|
|
234
|
+
reg.set("agent_status", makeStatusTool(cfg.agentStatus));
|
|
235
|
+
if (cfg.stopAgent)
|
|
236
|
+
reg.set("stop_agent", makeStopTool(cfg.stopAgent));
|
|
117
237
|
if (cfg.askUser)
|
|
118
238
|
reg.set("ask_user", makeAskTool(cfg.askUser));
|
|
119
239
|
}
|
|
120
|
-
this.executor = new Executor(reg);
|
|
240
|
+
this.executor = new Executor(reg, cfg.cwd);
|
|
121
241
|
this.localSchemas = toSchemas(reg);
|
|
122
242
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
123
243
|
this.router = engineRouter(this.inner);
|
|
@@ -131,6 +251,12 @@ export class Session {
|
|
|
131
251
|
}
|
|
132
252
|
this.systemPrompt = cfg.systemPrompt;
|
|
133
253
|
this.maxTokens = cfg.maxTokens ?? 2048;
|
|
254
|
+
this.maxTurnTokens = cfg.maxTurnTokens;
|
|
255
|
+
this.maxRounds = cfg.maxRounds;
|
|
256
|
+
this.maxRoundsHard = cfg.maxRoundsHard;
|
|
257
|
+
this.compactionThreshold = cfg.compactionThreshold;
|
|
258
|
+
this.compactionCeilingTokens = cfg.compactionCeilingTokens;
|
|
259
|
+
this.background = cfg.background ?? false;
|
|
134
260
|
this.temperature = cfg.temperature ?? 0.7;
|
|
135
261
|
this.memory = cfg.memory ?? new MemoryStore();
|
|
136
262
|
this.wantRecall = cfg.recall ?? true;
|
|
@@ -247,16 +373,23 @@ export class Session {
|
|
|
247
373
|
return this.inner.pin(name);
|
|
248
374
|
}
|
|
249
375
|
/** Force compaction now (for /compact). Returns how many messages were evicted. */
|
|
376
|
+
/** Manual /compact. Returns approx TOKENS freed. compact() force-evicts old turns (it ignores threshold
|
|
377
|
+
* and always evicts past minKeepTurns), but when the bulk is in the kept recent turns — one turn that
|
|
378
|
+
* dumped huge tool output, or a session stuck over a small failed-over window — eviction sheds nothing
|
|
379
|
+
* and /compact used to report "nothing to compact yet" while the session was clearly over budget. So we
|
|
380
|
+
* ALSO fitToWindow: elide the largest tool outputs in place until it fits the ACTIVE endpoint's (learned)
|
|
381
|
+
* window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
|
|
250
382
|
async compactNow() {
|
|
251
|
-
const
|
|
252
|
-
this.convo.replaceAll(await compact(this.convo.all, {
|
|
383
|
+
const opts = {
|
|
253
384
|
ctxWindow: this.inner.ctxLimit(),
|
|
254
385
|
systemPrompt: this.sys(),
|
|
255
386
|
summarize: this.summarize,
|
|
256
|
-
threshold: 0, // force
|
|
257
387
|
minKeepTurns: 2,
|
|
258
|
-
}
|
|
259
|
-
|
|
388
|
+
};
|
|
389
|
+
const chars = () => this.convo.all.reduce((n, m) => n + m.content.length, 0);
|
|
390
|
+
const before = chars();
|
|
391
|
+
this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
|
|
392
|
+
return Math.max(0, Math.ceil((before - chars()) / 4)); // approx tokens freed (chars/4)
|
|
260
393
|
}
|
|
261
394
|
/** Reset the conversation to empty (for /new). */
|
|
262
395
|
reset() {
|
|
@@ -312,15 +445,70 @@ export class Session {
|
|
|
312
445
|
return true;
|
|
313
446
|
}
|
|
314
447
|
/** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
|
|
448
|
+
// The EXACT effective system prompt the last live turn sent (execute() captures it). The cache-safe
|
|
449
|
+
// summarizer reuses it verbatim so [system + tools + span] byte-matches the prefix that turn cached —
|
|
450
|
+
// this.sys() alone can drift from what actually went out (a /think suffix, a MOA aggregator prompt).
|
|
451
|
+
lastSys;
|
|
452
|
+
// The EXACT endpoint the last live turn routed to (captured via onRoute in execute()). The summarizer must
|
|
453
|
+
// hit the SAME server/model that prefix-cached the conversation — reading this.inner blindly would send the
|
|
454
|
+
// summarize request to the DEFAULT endpoint even when the live turn FAILED OVER or is a MOA aggregator on a
|
|
455
|
+
// different endpoint, guaranteeing a full cache miss (and possibly a wrong-context-window 400).
|
|
456
|
+
lastBase;
|
|
457
|
+
lastModel;
|
|
315
458
|
summarize = async (span) => {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
459
|
+
// Cache-safe compaction (Anthropic's cache-safe forking). The evicted span is the OLDEST slice of the
|
|
460
|
+
// live conversation, so [system + tools + span] is an exact PREFIX of the request the live turn just
|
|
461
|
+
// sent — the server already has its KV cached. Reuse that IDENTICAL system prompt + tools and send the
|
|
462
|
+
// span as REAL messages (not a re-serialized user blob), appending the contract as the final user
|
|
463
|
+
// message. The server prefix-matches to the end of span and prefills only the instruction, instead of
|
|
464
|
+
// re-prefilling the whole span from scratch (the old system-less/tool-less summaryPrompt path did the
|
|
465
|
+
// latter — the documented cost trap). Empty content falls back to Aurora's reasoning channel.
|
|
466
|
+
const sys = this.lastSys ?? this.sys();
|
|
467
|
+
const messages = [
|
|
468
|
+
...(sys ? [{ role: "system", content: sys }] : []),
|
|
469
|
+
...stripTrailingOrphanToolCall(span),
|
|
470
|
+
{ role: "user", content: SUMMARY_INSTRUCTION },
|
|
471
|
+
];
|
|
472
|
+
const r = await chat(messages, {
|
|
473
|
+
base: this.lastBase ?? this.inner.base, // the endpoint the live turn actually used (failover/MOA-aware)
|
|
474
|
+
model: this.lastModel ?? this.inner.model,
|
|
475
|
+
tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
|
|
319
476
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
320
477
|
temperature: 0,
|
|
478
|
+
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
321
479
|
});
|
|
322
|
-
|
|
480
|
+
// Return "" on a genuinely empty response so compact()'s empty-summary guard fires and PRESERVES history
|
|
481
|
+
// rather than replacing it with a useless placeholder — the old "(summary unavailable)" sentinel was
|
|
482
|
+
// non-empty, so it DEFEATED that guard and could silently destroy the evicted span. A summary is never
|
|
483
|
+
// re-derivable; a skipped compaction (caller retries, runTurn self-heals the over-budget request) is
|
|
484
|
+
// strictly safer than nuking real history.
|
|
485
|
+
const summary = (r.content?.trim()) || (r.reasoningContent?.trim()) || "";
|
|
486
|
+
if (summary)
|
|
487
|
+
this.persistHandoff(summary, span.length); // durability: compacted work survives on disk
|
|
488
|
+
return summary;
|
|
323
489
|
};
|
|
490
|
+
/** Append every AUTOMATIC-compaction summary to the per-working-directory handoff file — the SAME
|
|
491
|
+
* file cli.tsx auto-loads into the next session's system prompt (KODE_HANDOFF_FILE). This closes the
|
|
492
|
+
* loop WITHOUT relying on the model remembering to call the session_handoff tool: context fills →
|
|
493
|
+
* auto-compaction fires → the summary lands in the handoff → the next `operator` launch here resumes
|
|
494
|
+
* from it. Best-effort; a write failure never blocks compaction. Falls back to a per-session file when
|
|
495
|
+
* KODE_HANDOFF_FILE isn't set (tests, sub-agents — which must NOT touch the foreground cwd handoff). */
|
|
496
|
+
handoffFile;
|
|
497
|
+
persistHandoff(summary, evicted) {
|
|
498
|
+
try {
|
|
499
|
+
if (!this.handoffFile) {
|
|
500
|
+
const envFile = process.env.KODE_HANDOFF_FILE;
|
|
501
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
502
|
+
this.handoffFile = envFile && envFile.trim()
|
|
503
|
+
? envFile
|
|
504
|
+
: join(homedir(), ".axe", "operator", "handoff", `session-${stamp}.md`);
|
|
505
|
+
mkdirSync(dirname(this.handoffFile), { recursive: true });
|
|
506
|
+
}
|
|
507
|
+
const block = `\n## Auto-compaction @ ${new Date().toISOString()} (evicted ${evicted} msg)\n\n${summary}\n`;
|
|
508
|
+
appendFileSync(this.handoffFile, block, "utf8");
|
|
509
|
+
}
|
|
510
|
+
catch { /* handoff is a durability convenience, never a hard dependency */ }
|
|
511
|
+
}
|
|
324
512
|
/** First-turn setup, once only. (1) Recall memory relevant to what the user is asking (plus recent
|
|
325
513
|
* notes) and fold it into the system prompt for the session. (2) Discover fleet MCP tools and merge
|
|
326
514
|
* their schemas + dispatch. Both are best-effort — a failure degrades (local-only), never blocks. */
|
|
@@ -410,7 +598,7 @@ export class Session {
|
|
|
410
598
|
if (!survivors.length) {
|
|
411
599
|
h.onRoute?.(active.id, this.ctxPct());
|
|
412
600
|
this.modelId = DEFAULT_MODEL_ID; // fall back for this and future turns until /model moa retries
|
|
413
|
-
const note = "MOA: every proposer failed or timed out — falling back to
|
|
601
|
+
const note = "MOA: every proposer failed or timed out — falling back to operator-1m for this reply.\n\n";
|
|
414
602
|
h.onDelta?.(note);
|
|
415
603
|
const res = await this.execute(text, h, this.router, this.sysWithThink());
|
|
416
604
|
return { ...res, content: note + res.content };
|
|
@@ -427,6 +615,7 @@ export class Session {
|
|
|
427
615
|
* and system prompt they pass in. */
|
|
428
616
|
async execute(text, h, router, sys, routeLabel) {
|
|
429
617
|
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
618
|
+
this.lastSys = sys; // remember the EXACT system prompt this turn sends, so cache-safe compaction reuses it verbatim
|
|
430
619
|
const controller = new AbortController();
|
|
431
620
|
this.ctrl = controller;
|
|
432
621
|
const _t0 = performance.now();
|
|
@@ -437,21 +626,39 @@ export class Session {
|
|
|
437
626
|
toolSchemas: this.allSchemas(),
|
|
438
627
|
systemPrompt: sys,
|
|
439
628
|
summarize: this.summarize,
|
|
629
|
+
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
440
630
|
maxTokens: this.maxTokens,
|
|
631
|
+
maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
632
|
+
maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
|
|
633
|
+
maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
|
|
634
|
+
compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
|
|
635
|
+
compactionCeilingTokens: this.compactionCeilingTokens, // settings.compaction.ceilingTokens; undefined → no absolute ceiling
|
|
441
636
|
temperature: this.temperature,
|
|
442
637
|
thinking: this.thinkMode !== "off", // /think, /ultrathink re-enable Aurora's native reasoning
|
|
443
638
|
signal: controller.signal,
|
|
444
639
|
onDelta: h.onDelta,
|
|
445
640
|
onReasoning: h.onReasoning,
|
|
641
|
+
onTokens: h.onTokens,
|
|
446
642
|
onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
|
|
447
643
|
onToolStart: h.onToolStart,
|
|
448
644
|
onToolResult: h.onToolResult,
|
|
449
645
|
onToolBatch: h.onToolBatch,
|
|
450
646
|
onAutoContinue: h.onAutoContinue,
|
|
451
647
|
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
648
|
+
// Verify-before-done: enabled unless KODE_VERIFY_GATE=0 (projected from settings.verifyGate). One
|
|
649
|
+
// reminder round when a turn changed files but ran no passing check. Every surface routes through
|
|
650
|
+
// here, so the gate is uniform across CLI, web/RC, headless, and loop turns.
|
|
651
|
+
verifyGate: { enabled: process.env.KODE_VERIFY_GATE !== "0", maxNudges: Number(process.env.KODE_VERIFY_GATE_MAX) || 1 },
|
|
452
652
|
});
|
|
453
653
|
this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
|
|
454
654
|
this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
|
|
655
|
+
// Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
|
|
656
|
+
// (best-effort, never blocks). Gated by KODE_SELFIMPROVE (projected from settings.selfImprove).
|
|
657
|
+
void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY === "1" }, {
|
|
658
|
+
input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
|
|
659
|
+
tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
|
|
660
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
|
|
661
|
+
});
|
|
455
662
|
return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
|
|
456
663
|
}
|
|
457
664
|
catch (e) {
|
package/dist/telemetry/events.js
CHANGED
|
@@ -16,6 +16,7 @@ export class EventSink {
|
|
|
16
16
|
file;
|
|
17
17
|
url;
|
|
18
18
|
onEvent;
|
|
19
|
+
subscribers = new Set();
|
|
19
20
|
lastWrite = Promise.resolve(); // chained so appends land in emit order (an audit log must be ordered)
|
|
20
21
|
constructor(opts = {}) {
|
|
21
22
|
this.file = opts.file ?? process.env.KODE_EVENTS_FILE ?? process.env.KODE_AUDIT_FILE ?? "~/.axe/operator/events.jsonl";
|
|
@@ -25,6 +26,8 @@ export class EventSink {
|
|
|
25
26
|
// this to marshal each event into its own store and render the control-plane surface.
|
|
26
27
|
this.onEvent = opts.onEvent;
|
|
27
28
|
}
|
|
29
|
+
subscribe(fn) { this.subscribers.add(fn); }
|
|
30
|
+
unsubscribe(fn) { this.subscribers.delete(fn); }
|
|
28
31
|
/** Fill in envelope boilerplate and dispatch. Callers pass kind + the matching payload + actor. */
|
|
29
32
|
emit(e) {
|
|
30
33
|
const full = { v: EVENT_V, ts: new Date().toISOString(), ...e };
|
|
@@ -34,6 +37,12 @@ export class EventSink {
|
|
|
34
37
|
this.onEvent?.(full);
|
|
35
38
|
}
|
|
36
39
|
catch { /* a host listener must never break a turn */ }
|
|
40
|
+
for (const fn of this.subscribers) {
|
|
41
|
+
try {
|
|
42
|
+
fn(full);
|
|
43
|
+
}
|
|
44
|
+
catch { /* subscriber must never break a turn */ }
|
|
45
|
+
}
|
|
37
46
|
this.lastWrite = this.lastWrite.then(() => this.write(full)); // serialized: ordered append, awaitable via flushed()
|
|
38
47
|
void this.post(full);
|
|
39
48
|
}
|
package/dist/tools/executor.js
CHANGED
|
@@ -8,45 +8,69 @@
|
|
|
8
8
|
// new user turn (not required by SPEC §3's
|
|
9
9
|
// round loop itself, but needed so the guard
|
|
10
10
|
// doesn't bleed across turns)
|
|
11
|
+
import { isAbsolute, join } from "node:path";
|
|
11
12
|
import { registry } from "./registry.js";
|
|
12
|
-
|
|
13
|
-
//
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
//
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const
|
|
26
|
-
const
|
|
27
|
-
|
|
13
|
+
// Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
|
|
14
|
+
// file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
|
|
15
|
+
import { capToolResult } from "./result-cap.js";
|
|
16
|
+
export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
|
|
17
|
+
// Command tools whose working directory should default to the executor root (they take an optional `cwd`).
|
|
18
|
+
const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
|
|
19
|
+
// Args that name a filesystem path the file tools read/write; a RELATIVE one is resolved under the root.
|
|
20
|
+
const PATH_ARGS = ["path", "file", "filename", "workspace"];
|
|
21
|
+
/** Reroot a tool call's args under `root` so a session's file/shell tools all act inside its own directory
|
|
22
|
+
* (e.g. a background agent's git worktree) instead of the shared process cwd. Pure: relative path args are
|
|
23
|
+
* joined under root; command tools default their cwd to root; absolute and ~ paths are left untouched
|
|
24
|
+
* (an explicit absolute path is the caller's intent). Exported for unit testing. */
|
|
25
|
+
export function rootArgs(name, args, root) {
|
|
26
|
+
const a = { ...args };
|
|
27
|
+
for (const k of PATH_ARGS) {
|
|
28
|
+
const v = a[k];
|
|
29
|
+
if (typeof v === "string" && v && !isAbsolute(v) && !v.startsWith("~"))
|
|
30
|
+
a[k] = join(root, v);
|
|
31
|
+
}
|
|
32
|
+
if (typeof a.cwd === "string" && a.cwd && !isAbsolute(a.cwd) && !a.cwd.startsWith("~"))
|
|
33
|
+
a.cwd = join(root, a.cwd);
|
|
34
|
+
else if (a.cwd == null && CWD_TOOLS.has(name))
|
|
35
|
+
a.cwd = root;
|
|
36
|
+
return a;
|
|
28
37
|
}
|
|
38
|
+
const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this secondary guard never fires first
|
|
39
|
+
import { MUTATING_TOOLS } from "./mutating.js"; // single source of truth (see tools/mutating.ts) — a workspace edit ⇒ prior identical-call counts are stale
|
|
40
|
+
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]); // poll/status tools — repeated calls are legit, never guarded
|
|
29
41
|
export class Executor {
|
|
30
42
|
reg;
|
|
31
|
-
|
|
43
|
+
root;
|
|
44
|
+
/** @param root optional working directory to root every tool call under (a background agent's isolated
|
|
45
|
+
* worktree) — so its file/shell mutations never touch the shared process cwd. Undefined = shared cwd. */
|
|
46
|
+
constructor(reg = registry, root) {
|
|
32
47
|
this.reg = reg;
|
|
48
|
+
this.root = root;
|
|
33
49
|
}
|
|
34
50
|
seen = new Map();
|
|
35
51
|
resetTurn() {
|
|
36
52
|
this.seen.clear();
|
|
37
53
|
}
|
|
38
|
-
async execute(name,
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
54
|
+
async execute(name, rawArgs) {
|
|
55
|
+
const args = this.root ? rootArgs(name, rawArgs, this.root) : rawArgs;
|
|
56
|
+
if (!LOOP_GUARD_EXEMPT.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
|
|
57
|
+
const key = `${name} ${JSON.stringify(args)}`;
|
|
58
|
+
const count = (this.seen.get(key) ?? 0) + 1;
|
|
59
|
+
this.seen.set(key, count);
|
|
60
|
+
if (count >= LOOP_GUARD_THRESHOLD) {
|
|
61
|
+
return `loop guard: "${name}" called ${count}x with identical args this turn — stop repeating it, try a different approach or ask the user.`;
|
|
62
|
+
}
|
|
44
63
|
}
|
|
45
64
|
const tool = this.reg.get(name);
|
|
46
65
|
if (!tool)
|
|
47
66
|
return `error: unknown tool "${name}"`;
|
|
48
67
|
try {
|
|
49
|
-
|
|
68
|
+
const out = capToolResult(await tool.run(args));
|
|
69
|
+
// A file edit changed the workspace, so prior identical-call counts are stale — re-running the same
|
|
70
|
+
// test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
|
|
71
|
+
if (MUTATING_TOOLS.has(name))
|
|
72
|
+
this.seen.clear();
|
|
73
|
+
return out;
|
|
50
74
|
}
|
|
51
75
|
catch (e) {
|
|
52
76
|
return `error running ${name}: ${e?.message ?? e}`;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Structured, model-friendly git state. Operator kept flailing on raw `bash(git status/add/diff)` —
|
|
2
|
+
// re-running the same commands, misreading porcelain, and confused when an already-committed tree showed
|
|
3
|
+
// "nothing to add" — until the loop guard cut it off. This returns ONE clean read the weak model can act
|
|
4
|
+
// on: branch, ahead/behind vs upstream, and staged/unstaged/untracked lists, with a clean tree stated
|
|
5
|
+
// plainly as SUCCESS ("nothing to commit") so the model stops spelunking. `formatGitStatus` is pure
|
|
6
|
+
// (parses `git status --porcelain=v1 --branch` output) so it is unit-testable without a repo.
|
|
7
|
+
const CAP = 20;
|
|
8
|
+
function capList(arr) {
|
|
9
|
+
return arr.length > CAP ? arr.slice(0, CAP).join(", ") + `, …(+${arr.length - CAP} more)` : arr.join(", ");
|
|
10
|
+
}
|
|
11
|
+
/** Turn `git status --porcelain=v1 --branch` output into a compact, unambiguous summary. */
|
|
12
|
+
export function formatGitStatus(porcelain) {
|
|
13
|
+
const lines = porcelain.split("\n").filter((l) => l.length > 0);
|
|
14
|
+
let branch = "(detached)";
|
|
15
|
+
let upstream = "";
|
|
16
|
+
let ahead = 0;
|
|
17
|
+
let behind = 0;
|
|
18
|
+
const staged = [];
|
|
19
|
+
const unstaged = [];
|
|
20
|
+
const untracked = [];
|
|
21
|
+
for (const line of lines) {
|
|
22
|
+
if (line.startsWith("## ")) {
|
|
23
|
+
const b = line.slice(3);
|
|
24
|
+
const m = b.match(/^([^ .]+)(?:\.\.\.(\S+))?(?: \[(.+)\])?/);
|
|
25
|
+
if (m) {
|
|
26
|
+
branch = m[1];
|
|
27
|
+
upstream = m[2] ?? "";
|
|
28
|
+
const info = m[3] ?? "";
|
|
29
|
+
const am = info.match(/ahead (\d+)/);
|
|
30
|
+
const bm = info.match(/behind (\d+)/);
|
|
31
|
+
if (am)
|
|
32
|
+
ahead = Number(am[1]);
|
|
33
|
+
if (bm)
|
|
34
|
+
behind = Number(bm[1]);
|
|
35
|
+
}
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const xy = line.slice(0, 2);
|
|
39
|
+
const path = line.slice(3);
|
|
40
|
+
if (xy === "??") {
|
|
41
|
+
untracked.push(path);
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (xy[0] !== " " && xy[0] !== "?")
|
|
45
|
+
staged.push(path); // index (staged) change
|
|
46
|
+
if (xy[1] !== " " && xy[1] !== "?")
|
|
47
|
+
unstaged.push(path); // worktree (unstaged) change
|
|
48
|
+
}
|
|
49
|
+
let head = `branch: ${branch}`;
|
|
50
|
+
if (upstream) {
|
|
51
|
+
if (!ahead && !behind)
|
|
52
|
+
head += ` (up to date with ${upstream})`;
|
|
53
|
+
else
|
|
54
|
+
head += ` (${[ahead ? `ahead ${ahead}` : "", behind ? `behind ${behind}` : ""].filter(Boolean).join(", ")} vs ${upstream})`;
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
head += " (no upstream)";
|
|
58
|
+
}
|
|
59
|
+
const out = [head];
|
|
60
|
+
if (!staged.length && !unstaged.length && !untracked.length) {
|
|
61
|
+
out.push("working tree clean — nothing to commit");
|
|
62
|
+
return out.join("\n");
|
|
63
|
+
}
|
|
64
|
+
if (staged.length)
|
|
65
|
+
out.push(`staged (${staged.length}): ${capList(staged)}`);
|
|
66
|
+
if (unstaged.length)
|
|
67
|
+
out.push(`unstaged (${unstaged.length}): ${capList(unstaged)}`);
|
|
68
|
+
if (untracked.length)
|
|
69
|
+
out.push(`untracked (${untracked.length}): ${capList(untracked)}`);
|
|
70
|
+
return out.join("\n");
|
|
71
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Single source of truth for "which tools mutate the workspace". A workspace edit resets the loop-guard
|
|
2
|
+
// call counts (re-running the SAME test/build after an edit is verify-after-fix iteration, not a spin), marks
|
|
3
|
+
// a turn as having changed files (verify-before-done), keeps the no-edit streak from ticking (the stuck-turn
|
|
4
|
+
// guard), and is the trigger for a checkpoint snapshot. Kept in a DEPENDENCY-FREE leaf module so both the
|
|
5
|
+
// engine (agent.ts, verify-gate.ts) and the tool layer (executor.ts) — and the coming checkpoints module —
|
|
6
|
+
// import ONE definition instead of three copies that could drift apart.
|
|
7
|
+
export const MUTATING_TOOLS = new Set(["file_write", "file_edit"]);
|
|
8
|
+
/** True when a tool call's name is a workspace mutation. Tolerates undefined (a malformed/partial call). */
|
|
9
|
+
export const isMutatingTool = (name) => MUTATING_TOOLS.has(name ?? "");
|