@0perator/operator 0.1.62 → 0.1.154
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 +1035 -0
- 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 +275 -20
- package/dist/background/worktree.js +62 -0
- package/dist/cli.js +518 -95
- 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 +1 -1
- 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 +239 -22
- package/dist/telemetry/events.js +9 -0
- package/dist/tools/executor.js +62 -24
- package/dist/tools/git-status.js +71 -0
- package/dist/tools/mutating.js +9 -0
- package/dist/tools/registry.js +247 -26
- package/dist/tools/result-cap.js +23 -0
- package/dist/tools/searxng.js +42 -2
- package/dist/tools/shell-context.js +17 -0
- 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 +6 -4
- 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 +11 -2
package/dist/session.js
CHANGED
|
@@ -4,17 +4,22 @@
|
|
|
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
|
-
import { toSchemas, registry } from "./tools/registry.js";
|
|
17
|
+
import { toSchemas, registry, disposeShellSessionKey } from "./tools/registry.js";
|
|
14
18
|
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
|
|
@@ -82,6 +190,7 @@ export class Session {
|
|
|
82
190
|
moaConfig;
|
|
83
191
|
modelId = DEFAULT_MODEL_ID; // active /model selection
|
|
84
192
|
executor;
|
|
193
|
+
shellKey; // this session's persistent-shell key (see disposeShell)
|
|
85
194
|
localSchemas;
|
|
86
195
|
hub;
|
|
87
196
|
tools;
|
|
@@ -96,6 +205,12 @@ export class Session {
|
|
|
96
205
|
wantMcp;
|
|
97
206
|
systemPrompt;
|
|
98
207
|
maxTokens;
|
|
208
|
+
maxTurnTokens;
|
|
209
|
+
maxRounds;
|
|
210
|
+
maxRoundsHard;
|
|
211
|
+
compactionThreshold;
|
|
212
|
+
compactionCeilingTokens;
|
|
213
|
+
background;
|
|
99
214
|
temperature;
|
|
100
215
|
ctrl = null;
|
|
101
216
|
memory;
|
|
@@ -110,14 +225,21 @@ export class Session {
|
|
|
110
225
|
// handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
|
|
111
226
|
// are built from the same map, so the tool is advertised iff it's runnable.
|
|
112
227
|
let reg = registry;
|
|
113
|
-
if (cfg.spawnAgent || cfg.askUser) {
|
|
228
|
+
if (cfg.spawnAgent || cfg.askUser || cfg.messageAgent || cfg.agentStatus || cfg.stopAgent) {
|
|
114
229
|
reg = new Map(registry);
|
|
115
230
|
if (cfg.spawnAgent)
|
|
116
231
|
reg.set("spawn_agent", makeSpawnTool(cfg.spawnAgent));
|
|
232
|
+
if (cfg.messageAgent)
|
|
233
|
+
reg.set("message_agent", makeMessageTool(cfg.messageAgent));
|
|
234
|
+
if (cfg.agentStatus)
|
|
235
|
+
reg.set("agent_status", makeStatusTool(cfg.agentStatus));
|
|
236
|
+
if (cfg.stopAgent)
|
|
237
|
+
reg.set("stop_agent", makeStopTool(cfg.stopAgent));
|
|
117
238
|
if (cfg.askUser)
|
|
118
239
|
reg.set("ask_user", makeAskTool(cfg.askUser));
|
|
119
240
|
}
|
|
120
|
-
this.executor = new Executor(reg);
|
|
241
|
+
this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
|
|
242
|
+
this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
|
|
121
243
|
this.localSchemas = toSchemas(reg);
|
|
122
244
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
123
245
|
this.router = engineRouter(this.inner);
|
|
@@ -131,6 +253,12 @@ export class Session {
|
|
|
131
253
|
}
|
|
132
254
|
this.systemPrompt = cfg.systemPrompt;
|
|
133
255
|
this.maxTokens = cfg.maxTokens ?? 2048;
|
|
256
|
+
this.maxTurnTokens = cfg.maxTurnTokens;
|
|
257
|
+
this.maxRounds = cfg.maxRounds;
|
|
258
|
+
this.maxRoundsHard = cfg.maxRoundsHard;
|
|
259
|
+
this.compactionThreshold = cfg.compactionThreshold;
|
|
260
|
+
this.compactionCeilingTokens = cfg.compactionCeilingTokens;
|
|
261
|
+
this.background = cfg.background ?? false;
|
|
134
262
|
this.temperature = cfg.temperature ?? 0.7;
|
|
135
263
|
this.memory = cfg.memory ?? new MemoryStore();
|
|
136
264
|
this.wantRecall = cfg.recall ?? true;
|
|
@@ -247,16 +375,23 @@ export class Session {
|
|
|
247
375
|
return this.inner.pin(name);
|
|
248
376
|
}
|
|
249
377
|
/** Force compaction now (for /compact). Returns how many messages were evicted. */
|
|
378
|
+
/** Manual /compact. Returns approx TOKENS freed. compact() force-evicts old turns (it ignores threshold
|
|
379
|
+
* and always evicts past minKeepTurns), but when the bulk is in the kept recent turns — one turn that
|
|
380
|
+
* dumped huge tool output, or a session stuck over a small failed-over window — eviction sheds nothing
|
|
381
|
+
* and /compact used to report "nothing to compact yet" while the session was clearly over budget. So we
|
|
382
|
+
* ALSO fitToWindow: elide the largest tool outputs in place until it fits the ACTIVE endpoint's (learned)
|
|
383
|
+
* window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
|
|
250
384
|
async compactNow() {
|
|
251
|
-
const
|
|
252
|
-
this.convo.replaceAll(await compact(this.convo.all, {
|
|
385
|
+
const opts = {
|
|
253
386
|
ctxWindow: this.inner.ctxLimit(),
|
|
254
387
|
systemPrompt: this.sys(),
|
|
255
388
|
summarize: this.summarize,
|
|
256
|
-
threshold: 0, // force
|
|
257
389
|
minKeepTurns: 2,
|
|
258
|
-
}
|
|
259
|
-
|
|
390
|
+
};
|
|
391
|
+
const chars = () => this.convo.all.reduce((n, m) => n + m.content.length, 0);
|
|
392
|
+
const before = chars();
|
|
393
|
+
this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
|
|
394
|
+
return Math.max(0, Math.ceil((before - chars()) / 4)); // approx tokens freed (chars/4)
|
|
260
395
|
}
|
|
261
396
|
/** Reset the conversation to empty (for /new). */
|
|
262
397
|
reset() {
|
|
@@ -312,15 +447,70 @@ export class Session {
|
|
|
312
447
|
return true;
|
|
313
448
|
}
|
|
314
449
|
/** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
|
|
450
|
+
// The EXACT effective system prompt the last live turn sent (execute() captures it). The cache-safe
|
|
451
|
+
// summarizer reuses it verbatim so [system + tools + span] byte-matches the prefix that turn cached —
|
|
452
|
+
// this.sys() alone can drift from what actually went out (a /think suffix, a MOA aggregator prompt).
|
|
453
|
+
lastSys;
|
|
454
|
+
// The EXACT endpoint the last live turn routed to (captured via onRoute in execute()). The summarizer must
|
|
455
|
+
// hit the SAME server/model that prefix-cached the conversation — reading this.inner blindly would send the
|
|
456
|
+
// summarize request to the DEFAULT endpoint even when the live turn FAILED OVER or is a MOA aggregator on a
|
|
457
|
+
// different endpoint, guaranteeing a full cache miss (and possibly a wrong-context-window 400).
|
|
458
|
+
lastBase;
|
|
459
|
+
lastModel;
|
|
315
460
|
summarize = async (span) => {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
461
|
+
// Cache-safe compaction (Anthropic's cache-safe forking). The evicted span is the OLDEST slice of the
|
|
462
|
+
// live conversation, so [system + tools + span] is an exact PREFIX of the request the live turn just
|
|
463
|
+
// sent — the server already has its KV cached. Reuse that IDENTICAL system prompt + tools and send the
|
|
464
|
+
// span as REAL messages (not a re-serialized user blob), appending the contract as the final user
|
|
465
|
+
// message. The server prefix-matches to the end of span and prefills only the instruction, instead of
|
|
466
|
+
// re-prefilling the whole span from scratch (the old system-less/tool-less summaryPrompt path did the
|
|
467
|
+
// latter — the documented cost trap). Empty content falls back to Aurora's reasoning channel.
|
|
468
|
+
const sys = this.lastSys ?? this.sys();
|
|
469
|
+
const messages = [
|
|
470
|
+
...(sys ? [{ role: "system", content: sys }] : []),
|
|
471
|
+
...stripTrailingOrphanToolCall(span),
|
|
472
|
+
{ role: "user", content: SUMMARY_INSTRUCTION },
|
|
473
|
+
];
|
|
474
|
+
const r = await chat(messages, {
|
|
475
|
+
base: this.lastBase ?? this.inner.base, // the endpoint the live turn actually used (failover/MOA-aware)
|
|
476
|
+
model: this.lastModel ?? this.inner.model,
|
|
477
|
+
tools: this.allSchemas(), // identical tools → the span prefix-matches the live turn's cached KV
|
|
319
478
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
320
479
|
temperature: 0,
|
|
480
|
+
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
321
481
|
});
|
|
322
|
-
|
|
482
|
+
// Return "" on a genuinely empty response so compact()'s empty-summary guard fires and PRESERVES history
|
|
483
|
+
// rather than replacing it with a useless placeholder — the old "(summary unavailable)" sentinel was
|
|
484
|
+
// non-empty, so it DEFEATED that guard and could silently destroy the evicted span. A summary is never
|
|
485
|
+
// re-derivable; a skipped compaction (caller retries, runTurn self-heals the over-budget request) is
|
|
486
|
+
// strictly safer than nuking real history.
|
|
487
|
+
const summary = (r.content?.trim()) || (r.reasoningContent?.trim()) || "";
|
|
488
|
+
if (summary)
|
|
489
|
+
this.persistHandoff(summary, span.length); // durability: compacted work survives on disk
|
|
490
|
+
return summary;
|
|
323
491
|
};
|
|
492
|
+
/** Append every AUTOMATIC-compaction summary to the per-working-directory handoff file — the SAME
|
|
493
|
+
* file cli.tsx auto-loads into the next session's system prompt (KODE_HANDOFF_FILE). This closes the
|
|
494
|
+
* loop WITHOUT relying on the model remembering to call the session_handoff tool: context fills →
|
|
495
|
+
* auto-compaction fires → the summary lands in the handoff → the next `operator` launch here resumes
|
|
496
|
+
* from it. Best-effort; a write failure never blocks compaction. Falls back to a per-session file when
|
|
497
|
+
* KODE_HANDOFF_FILE isn't set (tests, sub-agents — which must NOT touch the foreground cwd handoff). */
|
|
498
|
+
handoffFile;
|
|
499
|
+
persistHandoff(summary, evicted) {
|
|
500
|
+
try {
|
|
501
|
+
if (!this.handoffFile) {
|
|
502
|
+
const envFile = process.env.KODE_HANDOFF_FILE;
|
|
503
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
504
|
+
this.handoffFile = envFile && envFile.trim()
|
|
505
|
+
? envFile
|
|
506
|
+
: join(homedir(), ".axe", "operator", "handoff", `session-${stamp}.md`);
|
|
507
|
+
mkdirSync(dirname(this.handoffFile), { recursive: true });
|
|
508
|
+
}
|
|
509
|
+
const block = `\n## Auto-compaction @ ${new Date().toISOString()} (evicted ${evicted} msg)\n\n${summary}\n`;
|
|
510
|
+
appendFileSync(this.handoffFile, block, "utf8");
|
|
511
|
+
}
|
|
512
|
+
catch { /* handoff is a durability convenience, never a hard dependency */ }
|
|
513
|
+
}
|
|
324
514
|
/** First-turn setup, once only. (1) Recall memory relevant to what the user is asking (plus recent
|
|
325
515
|
* notes) and fold it into the system prompt for the session. (2) Discover fleet MCP tools and merge
|
|
326
516
|
* their schemas + dispatch. Both are best-effort — a failure degrades (local-only), never blocks. */
|
|
@@ -360,9 +550,17 @@ export class Session {
|
|
|
360
550
|
mcpServers() {
|
|
361
551
|
return this.hub?.serversWithTools() ?? [];
|
|
362
552
|
}
|
|
363
|
-
/** Tear down session resources (kills any spawned stdio MCP servers
|
|
553
|
+
/** Tear down session resources (kills any spawned stdio MCP servers + this session's persistent
|
|
554
|
+
* shell). Call on shell exit. */
|
|
364
555
|
shutdown() {
|
|
365
556
|
this.hub?.shutdown();
|
|
557
|
+
this.disposeShell();
|
|
558
|
+
}
|
|
559
|
+
/** Kill just this session's persistent shell — call when a background sub-agent finishes so its
|
|
560
|
+
* bash doesn't linger for the whole parent session. Safe to call more than once; a no-op if the
|
|
561
|
+
* shell was never started. Does NOT touch the shared MCP hub (a sub-agent may share it). */
|
|
562
|
+
disposeShell() {
|
|
563
|
+
disposeShellSessionKey(this.shellKey);
|
|
366
564
|
}
|
|
367
565
|
/** Store a durable memory note (for /remember and end-of-session capture). Best-effort. */
|
|
368
566
|
remember(text, tags) {
|
|
@@ -427,6 +625,7 @@ export class Session {
|
|
|
427
625
|
* and system prompt they pass in. */
|
|
428
626
|
async execute(text, h, router, sys, routeLabel) {
|
|
429
627
|
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
628
|
+
this.lastSys = sys; // remember the EXACT system prompt this turn sends, so cache-safe compaction reuses it verbatim
|
|
430
629
|
const controller = new AbortController();
|
|
431
630
|
this.ctrl = controller;
|
|
432
631
|
const _t0 = performance.now();
|
|
@@ -437,21 +636,39 @@ export class Session {
|
|
|
437
636
|
toolSchemas: this.allSchemas(),
|
|
438
637
|
systemPrompt: sys,
|
|
439
638
|
summarize: this.summarize,
|
|
639
|
+
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
440
640
|
maxTokens: this.maxTokens,
|
|
641
|
+
maxTurnTokens: this.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
642
|
+
maxRounds: this.maxRounds, // soft round budget from settings.maxRounds (undefined → runTurn default)
|
|
643
|
+
maxRoundsHard: this.maxRoundsHard, // absolute ceiling; undefined → runTurn default 400, tighter for bg sub-agents
|
|
644
|
+
compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
|
|
645
|
+
compactionCeilingTokens: this.compactionCeilingTokens, // settings.compaction.ceilingTokens; undefined → no absolute ceiling
|
|
441
646
|
temperature: this.temperature,
|
|
442
647
|
thinking: this.thinkMode !== "off", // /think, /ultrathink re-enable Aurora's native reasoning
|
|
443
648
|
signal: controller.signal,
|
|
444
649
|
onDelta: h.onDelta,
|
|
445
650
|
onReasoning: h.onReasoning,
|
|
651
|
+
onTokens: h.onTokens,
|
|
446
652
|
onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
|
|
447
653
|
onToolStart: h.onToolStart,
|
|
448
654
|
onToolResult: h.onToolResult,
|
|
449
655
|
onToolBatch: h.onToolBatch,
|
|
450
656
|
onAutoContinue: h.onAutoContinue,
|
|
451
657
|
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
658
|
+
// Verify-before-done: enabled unless KODE_VERIFY_GATE=0 (projected from settings.verifyGate). One
|
|
659
|
+
// reminder round when a turn changed files but ran no passing check. Every surface routes through
|
|
660
|
+
// here, so the gate is uniform across CLI, web/RC, headless, and loop turns.
|
|
661
|
+
verifyGate: { enabled: process.env.KODE_VERIFY_GATE !== "0", maxNudges: Number(process.env.KODE_VERIFY_GATE_MAX) || 1 },
|
|
452
662
|
});
|
|
453
663
|
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
664
|
this.sessionTokensTotal += (res.tokens ?? 0) + (res.promptTokens ?? 0); // cumulative session spend
|
|
665
|
+
// Self-improvement loop: capture this completed turn as a graded trajectory for the fleet flywheel
|
|
666
|
+
// (best-effort, never blocks). Gated by KODE_SELFIMPROVE (projected from settings.selfImprove).
|
|
667
|
+
void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY === "1" }, {
|
|
668
|
+
input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
|
|
669
|
+
tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
|
|
670
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
|
|
671
|
+
});
|
|
455
672
|
return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
|
|
456
673
|
}
|
|
457
674
|
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,83 @@
|
|
|
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
|
-
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const
|
|
27
|
-
|
|
13
|
+
import { shellKeyStore } from "./shell-context.js";
|
|
14
|
+
// Re-exported for back-compat (existing importers reach it via executor.js) — moved to its own
|
|
15
|
+
// file since it's a pure helper with no node deps; see result-cap.ts for why that separation matters.
|
|
16
|
+
import { capToolResult } from "./result-cap.js";
|
|
17
|
+
export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
|
|
18
|
+
// Command tools whose working directory should default to the executor root (they take an optional `cwd`).
|
|
19
|
+
const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
|
|
20
|
+
// Args that name a filesystem path the file tools read/write; a RELATIVE one is resolved under the root.
|
|
21
|
+
const PATH_ARGS = ["path", "file", "filename", "workspace"];
|
|
22
|
+
/** Reroot a tool call's args under `root` so a session's file/shell tools all act inside its own directory
|
|
23
|
+
* (e.g. a background agent's git worktree) instead of the shared process cwd. Pure: relative path args are
|
|
24
|
+
* joined under root; command tools default their cwd to root; absolute and ~ paths are left untouched
|
|
25
|
+
* (an explicit absolute path is the caller's intent). Exported for unit testing. */
|
|
26
|
+
export function rootArgs(name, args, root) {
|
|
27
|
+
const a = { ...args };
|
|
28
|
+
for (const k of PATH_ARGS) {
|
|
29
|
+
const v = a[k];
|
|
30
|
+
if (typeof v === "string" && v && !isAbsolute(v) && !v.startsWith("~"))
|
|
31
|
+
a[k] = join(root, v);
|
|
32
|
+
}
|
|
33
|
+
if (typeof a.cwd === "string" && a.cwd && !isAbsolute(a.cwd) && !a.cwd.startsWith("~"))
|
|
34
|
+
a.cwd = join(root, a.cwd);
|
|
35
|
+
else if (a.cwd == null && CWD_TOOLS.has(name))
|
|
36
|
+
a.cwd = root;
|
|
37
|
+
return a;
|
|
28
38
|
}
|
|
39
|
+
const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this secondary guard never fires first
|
|
40
|
+
import { MUTATING_TOOLS } from "./mutating.js"; // single source of truth (see tools/mutating.ts) — a workspace edit ⇒ prior identical-call counts are stale
|
|
41
|
+
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]); // poll/status tools — repeated calls are legit, never guarded
|
|
42
|
+
// Unique fallback id per Executor instance, so two sessions with no sessionId and no root (the
|
|
43
|
+
// foreground and a read-only sub-agent lane) still get DISTINCT shell keys. One Executor lives for
|
|
44
|
+
// its session's whole lifetime (the Session is constructed once and reused across turns), so this id
|
|
45
|
+
// is stable across a session's turns — the persistent shell survives, keyed per session, not shared.
|
|
46
|
+
let _execSeq = 0;
|
|
29
47
|
export class Executor {
|
|
30
48
|
reg;
|
|
31
|
-
|
|
49
|
+
root;
|
|
50
|
+
/** Stable per-session key for this Executor's persistent shell (see shell-context.ts). A caller-
|
|
51
|
+
* supplied id (the Session's sessionId) when present, else a unique per-instance fallback. */
|
|
52
|
+
shellKey;
|
|
53
|
+
/** @param root optional working directory to root every tool call under (a background agent's isolated
|
|
54
|
+
* worktree) — so its file/shell mutations never touch the shared process cwd. Undefined = shared cwd.
|
|
55
|
+
* @param shellKey stable session id used to key this session's persistent shell; falls back to a
|
|
56
|
+
* unique per-instance id so distinct sessions never share (and corrupt) one shell. */
|
|
57
|
+
constructor(reg = registry, root, shellKey) {
|
|
32
58
|
this.reg = reg;
|
|
59
|
+
this.root = root;
|
|
60
|
+
this.shellKey = shellKey || `exec-${++_execSeq}`;
|
|
33
61
|
}
|
|
34
62
|
seen = new Map();
|
|
35
63
|
resetTurn() {
|
|
36
64
|
this.seen.clear();
|
|
37
65
|
}
|
|
38
|
-
async execute(name,
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
66
|
+
async execute(name, rawArgs) {
|
|
67
|
+
const args = this.root ? rootArgs(name, rawArgs, this.root) : rawArgs;
|
|
68
|
+
if (!LOOP_GUARD_EXEMPT.has(name)) { // poll/status tools are never loop-guarded (repeated calls are legit)
|
|
69
|
+
const key = `${name} ${JSON.stringify(args)}`;
|
|
70
|
+
const count = (this.seen.get(key) ?? 0) + 1;
|
|
71
|
+
this.seen.set(key, count);
|
|
72
|
+
if (count >= LOOP_GUARD_THRESHOLD) {
|
|
73
|
+
return `loop guard: "${name}" called ${count}x with identical args this turn — stop repeating it, try a different approach or ask the user.`;
|
|
74
|
+
}
|
|
44
75
|
}
|
|
45
76
|
const tool = this.reg.get(name);
|
|
46
77
|
if (!tool)
|
|
47
78
|
return `error: unknown tool "${name}"`;
|
|
48
79
|
try {
|
|
49
|
-
|
|
80
|
+
// Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
|
|
81
|
+
// this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
|
|
82
|
+
const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)));
|
|
83
|
+
// A file edit changed the workspace, so prior identical-call counts are stale — re-running the same
|
|
84
|
+
// test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
|
|
85
|
+
if (MUTATING_TOOLS.has(name))
|
|
86
|
+
this.seen.clear();
|
|
87
|
+
return out;
|
|
50
88
|
}
|
|
51
89
|
catch (e) {
|
|
52
90
|
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 ?? "");
|