@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/engine/aurora.js
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
// selfheal.js only type-imports from here (erased at runtime), so importing its values back is not a
|
|
2
2
|
// runtime cycle. Reused to retry a transient transport drop at the fetch layer (see fetchChat).
|
|
3
3
|
import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
|
|
4
|
+
const _endpointGates = new Map();
|
|
5
|
+
function endpointSlots(_base) {
|
|
6
|
+
// One knob for now (the fleet runs one single-slot Aurora); keyed by base so a future per-endpoint override
|
|
7
|
+
// slots in without touching callers. Any value < 1 is coerced to 1 — a gate must admit at least one request.
|
|
8
|
+
return Math.max(1, Number(process.env.KODE_ENDPOINT_SLOTS) || 1);
|
|
9
|
+
}
|
|
10
|
+
function endpointGate(base) {
|
|
11
|
+
let g = _endpointGates.get(base);
|
|
12
|
+
if (!g) {
|
|
13
|
+
g = { inUse: 0, queue: [] };
|
|
14
|
+
_endpointGates.set(base, g);
|
|
15
|
+
}
|
|
16
|
+
return g;
|
|
17
|
+
}
|
|
18
|
+
/** Reserve a request slot on `base`. Interactive (main-turn) requests are served ahead of background
|
|
19
|
+
* (sub-agent) ones: an interactive caller inserts before the first queued background caller, and a
|
|
20
|
+
* background caller never claims a free slot while any interactive caller is waiting. Resolves when the
|
|
21
|
+
* slot is granted; the caller MUST releaseEndpoint(base) exactly once when its request+stream is done. */
|
|
22
|
+
export function acquireEndpoint(base, background) {
|
|
23
|
+
const g = endpointGate(base);
|
|
24
|
+
const interactiveWaiting = g.queue.some((w) => !w.background);
|
|
25
|
+
if (g.inUse < endpointSlots(base) && !(background && interactiveWaiting)) {
|
|
26
|
+
g.inUse++;
|
|
27
|
+
return Promise.resolve();
|
|
28
|
+
}
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
const entry = { background, resolve };
|
|
31
|
+
if (background) {
|
|
32
|
+
g.queue.push(entry);
|
|
33
|
+
return;
|
|
34
|
+
} // background always at the back
|
|
35
|
+
const i = g.queue.findIndex((w) => w.background); // interactive: ahead of the first background, behind other interactives (FIFO)
|
|
36
|
+
if (i === -1)
|
|
37
|
+
g.queue.push(entry);
|
|
38
|
+
else
|
|
39
|
+
g.queue.splice(i, 0, entry);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** Release a slot on `base` and wake the highest-priority waiter (first interactive, else the front). */
|
|
43
|
+
export function releaseEndpoint(base) {
|
|
44
|
+
const g = endpointGate(base);
|
|
45
|
+
g.inUse = Math.max(0, g.inUse - 1);
|
|
46
|
+
if (g.inUse >= endpointSlots(base) || g.queue.length === 0)
|
|
47
|
+
return;
|
|
48
|
+
const i = g.queue.findIndex((w) => !w.background);
|
|
49
|
+
const [next] = g.queue.splice(i === -1 ? 0 : i, 1);
|
|
50
|
+
g.inUse++;
|
|
51
|
+
next.resolve();
|
|
52
|
+
}
|
|
53
|
+
/** Snapshot of every endpoint gate (for tests + a live status surface). */
|
|
54
|
+
export function endpointGateStatus() {
|
|
55
|
+
return [..._endpointGates.entries()].map(([base, g]) => ({ base, inUse: g.inUse, queued: g.queue.length, slots: endpointSlots(base) }));
|
|
56
|
+
}
|
|
4
57
|
// A remote engine (api.axe.onl) fronts the model with gateway auth; a local :8097 does not. Only a
|
|
5
58
|
// non-loopback base needs (and should ever receive) the operator bearer, so a token is never sent to
|
|
6
59
|
// a local llama-server and the header is omitted entirely when there is nothing to send.
|
|
@@ -28,32 +81,69 @@ const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets,
|
|
|
28
81
|
const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
|
|
29
82
|
const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
|
|
30
83
|
const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
|
|
84
|
+
const RUNAWAY_CHARS = 120_000; // a round is capped at max_tokens (~8k => ~33k chars); far past that is a
|
|
85
|
+
// decode loop or a stream/render duplication, never a real answer — hard stop.
|
|
31
86
|
function hasAlpha(s) {
|
|
32
87
|
return /[a-zA-Z]/.test(s);
|
|
33
88
|
}
|
|
34
|
-
/**
|
|
89
|
+
/** Fuzzy-normalize for loop detection: lowercase, non-alphanumerics → single spaces. Makes near-identical,
|
|
90
|
+
* garbled or re-interleaved repeats (e.g. "lookeYou'You're You'rYou'r…") compare equal, which exact
|
|
91
|
+
* matching misses — that was the class of loop that slipped the guard on a stuck turn. */
|
|
92
|
+
function normLoop(s) {
|
|
93
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
|
|
94
|
+
}
|
|
95
|
+
/** True once the accumulated text is provably looping — a repeated substantial line (exact OR normalized),
|
|
96
|
+
* a short cycle repeated in the tail (raw OR normalized), or a runaway past any sane single-round length. */
|
|
35
97
|
export function isDegenerate(text) {
|
|
36
98
|
if (text.length < LOOP_MIN_LINE_LEN * 3)
|
|
37
99
|
return false;
|
|
38
|
-
// (
|
|
39
|
-
|
|
100
|
+
// (d) runaway backstop — one round can't legitimately exceed ~33k chars; anything far beyond is a loop
|
|
101
|
+
// or a render/stream duplication. Catches the class even when the repeat isn't a clean line/cycle.
|
|
102
|
+
if (text.length > RUNAWAY_CHARS)
|
|
103
|
+
return true;
|
|
104
|
+
// (a) a substantial line repeated many times — counted both exact and fuzzy-normalized.
|
|
105
|
+
const exact = new Map();
|
|
106
|
+
const norm = new Map();
|
|
40
107
|
for (const raw of text.split("\n")) {
|
|
41
108
|
const line = raw.trim();
|
|
42
109
|
if (line.length < LOOP_MIN_LINE_LEN || !hasAlpha(line))
|
|
43
110
|
continue;
|
|
44
|
-
const
|
|
45
|
-
if (
|
|
111
|
+
const ne = (exact.get(line) ?? 0) + 1;
|
|
112
|
+
if (ne >= LOOP_LINE_REPEATS)
|
|
46
113
|
return true;
|
|
47
|
-
|
|
114
|
+
exact.set(line, ne);
|
|
115
|
+
const nl = normLoop(line);
|
|
116
|
+
if (nl.length >= LOOP_MIN_LINE_LEN) {
|
|
117
|
+
const nn = (norm.get(nl) ?? 0) + 1;
|
|
118
|
+
if (nn >= LOOP_LINE_REPEATS)
|
|
119
|
+
return true;
|
|
120
|
+
norm.set(nl, nn);
|
|
121
|
+
}
|
|
48
122
|
}
|
|
49
|
-
// (
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
123
|
+
// (c) a normalized word n-gram repeated many times ANYWHERE — catches a run-together / garbled loop
|
|
124
|
+
// that is one long line with trailing junk, so it's neither line- nor tail-aligned.
|
|
125
|
+
const words = normLoop(text).split(" ").filter(Boolean);
|
|
126
|
+
const N = 8;
|
|
127
|
+
if (words.length >= N * LOOP_LINE_REPEATS) {
|
|
128
|
+
const grams = new Map();
|
|
129
|
+
for (let i = 0; i + N <= words.length; i++) {
|
|
130
|
+
const g = words.slice(i, i + N).join(" ");
|
|
131
|
+
const c = (grams.get(g) ?? 0) + 1;
|
|
132
|
+
if (c >= LOOP_LINE_REPEATS)
|
|
133
|
+
return true;
|
|
134
|
+
grams.set(g, c);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// (b) the tail is one short cycle repeated back-to-back — check raw tail (token loop, no newlines) AND
|
|
138
|
+
// the normalized tail (garbled/interleaved repeat that isn't byte-exact).
|
|
139
|
+
for (const tail of [text.slice(-LOOP_TAIL * 3), normLoop(text.slice(-LOOP_TAIL * 4))]) {
|
|
140
|
+
for (let cyc = 6; cyc <= LOOP_TAIL; cyc++) {
|
|
141
|
+
if (tail.length < cyc * 3)
|
|
142
|
+
break;
|
|
143
|
+
const a = tail.slice(-cyc);
|
|
144
|
+
if (a === tail.slice(-2 * cyc, -cyc) && a === tail.slice(-3 * cyc, -2 * cyc) && hasAlpha(a))
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
57
147
|
}
|
|
58
148
|
return false;
|
|
59
149
|
}
|
|
@@ -76,8 +166,19 @@ export function trimLoop(text) {
|
|
|
76
166
|
function requestBody(messages, o, stream) {
|
|
77
167
|
return JSON.stringify({
|
|
78
168
|
model: o.model, messages, stream,
|
|
169
|
+
// Ask the server for an exact usage report on the final SSE chunk. Without this, llama.cpp omits
|
|
170
|
+
// `timings` on rounds that end in tool_calls (verified live), so the token meter under-counts a
|
|
171
|
+
// tool-heavy turn to near-zero and falls back to the chars/4 estimate. include_usage yields exact
|
|
172
|
+
// completion_tokens even on tool-call rounds (parsed via j.usage in streamDeltas).
|
|
173
|
+
...(stream ? { stream_options: { include_usage: true } } : {}),
|
|
174
|
+
// Reuse the server-side KV cache across requests (llama.cpp): a coding turn re-sends a GROWING prefix
|
|
175
|
+
// (system + tools + history) every round, and cache-safe compaction re-sends the evicted span as an exact
|
|
176
|
+
// PREFIX of the last live request. Without cache_prompt the single-slot server RE-PREFILLS that whole
|
|
177
|
+
// prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
|
|
178
|
+
// the server prefix-matches and prefills only the new tail. Harmless on servers that ignore the field.
|
|
179
|
+
cache_prompt: true,
|
|
79
180
|
max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
|
|
80
|
-
...(o.tools?.length ? { tools: o.tools, tool_choice: "auto" } : {}),
|
|
181
|
+
...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
|
|
81
182
|
// /think: re-enable the model's native reasoning for THIS request, overriding the server's
|
|
82
183
|
// enable_thinking:false default (set for speed). Verified this per-request override works on the
|
|
83
184
|
// Aurora build; reasoning arrives as reasoning_content and renders dimmed.
|
|
@@ -120,62 +221,77 @@ async function fetchChat(o, body) {
|
|
|
120
221
|
}
|
|
121
222
|
/** Shared SSE parse loop. Yields each `data:` line's `choices[0].delta`, raw. */
|
|
122
223
|
async function* streamDeltas(messages, o) {
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
err.status = res.status;
|
|
134
|
-
const ra = res.headers.get("retry-after");
|
|
135
|
-
if (ra)
|
|
136
|
-
err.retryAfterMs = /^\d+$/.test(ra.trim()) ? Number(ra) * 1000 : Math.max(0, Date.parse(ra) - Date.now());
|
|
137
|
-
throw err;
|
|
138
|
-
}
|
|
139
|
-
const reader = res.body.getReader();
|
|
140
|
-
const dec = new TextDecoder();
|
|
141
|
-
let buf = "";
|
|
142
|
-
// finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
|
|
224
|
+
// Hold this endpoint's slot for the WHOLE request+stream lifetime — the one decode slot is busy the entire
|
|
225
|
+
// time it streams — releasing on completion, early break (loop breaker / first-answer), error, or abort.
|
|
226
|
+
// Interactive turns preempt the queue ahead of background sub-agents (see acquireEndpoint). A single call is
|
|
227
|
+
// never re-entrant, so acquire/release balance exactly once.
|
|
228
|
+
await acquireEndpoint(o.base, o.background === true);
|
|
229
|
+
let _slotReleased = false;
|
|
230
|
+
const _releaseSlot = () => { if (!_slotReleased) {
|
|
231
|
+
_slotReleased = true;
|
|
232
|
+
releaseEndpoint(o.base);
|
|
233
|
+
} };
|
|
143
234
|
try {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
235
|
+
const res = await fetchChat(o, requestBody(messages, o, true));
|
|
236
|
+
if (!res.ok || !res.body) {
|
|
237
|
+
let detail = "";
|
|
238
|
+
try {
|
|
239
|
+
detail = (await res.text()).slice(0, 500);
|
|
240
|
+
}
|
|
241
|
+
catch { /* body already consumed / unreadable */ }
|
|
242
|
+
// Carry the status + body so the self-heal policy can classify WHY (context vs shape vs busy),
|
|
243
|
+
// not just guess from the number. `retryAfterMs` honors a Retry-After header on 429/503.
|
|
244
|
+
const err = new Error(`aurora /v1 ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
245
|
+
err.status = res.status;
|
|
246
|
+
const ra = res.headers.get("retry-after");
|
|
247
|
+
if (ra)
|
|
248
|
+
err.retryAfterMs = /^\d+$/.test(ra.trim()) ? Number(ra) * 1000 : Math.max(0, Date.parse(ra) - Date.now());
|
|
249
|
+
throw err;
|
|
250
|
+
}
|
|
251
|
+
const reader = res.body.getReader();
|
|
252
|
+
const dec = new TextDecoder();
|
|
253
|
+
let buf = "";
|
|
254
|
+
// finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
|
|
255
|
+
try {
|
|
256
|
+
for (;;) {
|
|
257
|
+
const { value, done } = await reader.read();
|
|
258
|
+
if (done)
|
|
259
|
+
break;
|
|
260
|
+
buf += dec.decode(value, { stream: true });
|
|
261
|
+
for (const line of buf.split("\n")) {
|
|
262
|
+
const t = line.trim();
|
|
263
|
+
if (!t.startsWith("data:"))
|
|
264
|
+
continue;
|
|
265
|
+
const d = t.slice(5).trim();
|
|
266
|
+
if (d === "[DONE]")
|
|
267
|
+
return;
|
|
268
|
+
try {
|
|
269
|
+
const j = JSON.parse(d);
|
|
270
|
+
// llama.cpp sends a final chunk carrying `timings` (predicted_n/_ms); OpenAI servers send `usage`.
|
|
271
|
+
if (j.timings || j.usage)
|
|
272
|
+
o.onMeta?.({ tokens: j.timings?.predicted_n ?? j.usage?.completion_tokens, genMs: j.timings?.predicted_ms, promptTokens: j.timings?.prompt_n ?? j.usage?.prompt_tokens, promptMs: j.timings?.prompt_ms });
|
|
273
|
+
const choice = j.choices?.[0];
|
|
274
|
+
// finish_reason is a sibling of delta (often on a final chunk whose delta is {} or absent).
|
|
275
|
+
// Attach it to the yielded delta, and still yield a bare {finish_reason} when there's no delta,
|
|
276
|
+
// so the consumer always sees WHY generation ended.
|
|
277
|
+
const delta = choice?.delta ?? (choice?.finish_reason ? {} : undefined);
|
|
278
|
+
if (delta) {
|
|
279
|
+
if (choice?.finish_reason)
|
|
280
|
+
delta.finish_reason = choice.finish_reason;
|
|
281
|
+
yield delta;
|
|
282
|
+
}
|
|
170
283
|
}
|
|
284
|
+
catch { }
|
|
171
285
|
}
|
|
172
|
-
|
|
286
|
+
buf = buf.slice(buf.lastIndexOf("\n") + 1);
|
|
173
287
|
}
|
|
174
|
-
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
await reader.cancel().catch(() => { });
|
|
175
291
|
}
|
|
176
292
|
}
|
|
177
293
|
finally {
|
|
178
|
-
|
|
294
|
+
_releaseSlot(); // free the endpoint slot for the next (interactive-first) waiter
|
|
179
295
|
}
|
|
180
296
|
}
|
|
181
297
|
/** Streaming content-only view (existing consumers keep working unchanged). */
|
|
@@ -28,6 +28,48 @@ export function summaryPrompt(span) {
|
|
|
28
28
|
"No preamble, no closing remarks.\n\n" +
|
|
29
29
|
transcript);
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* The structured summary CONTRACT, as a TRAILING instruction — the cache-safe summarizer (session.ts) sends
|
|
33
|
+
* the evicted span as REAL messages and appends this as the final user message, so the model reads the actual
|
|
34
|
+
* conversation above rather than a re-serialized copy. Nine sections (Anthropic's compaction contract) so a
|
|
35
|
+
* post-compaction resume is lossless: intent, concepts, files+snippets, errors+fixes, approaches, VERBATIM
|
|
36
|
+
* user messages, pending, current, next-step — a far richer note than the old FACTS/STATE pair, which dropped
|
|
37
|
+
* the user's own asks and the "why" behind rejected approaches. The global verbatim-value rule is unchanged
|
|
38
|
+
* (the load-bearing part). The evicted span, being the OLDEST slice, IS a prefix of the live turn's cached
|
|
39
|
+
* [system + tools + history], so reusing it verbatim lets the server prefix-match the KV cache; "call no tool"
|
|
40
|
+
* because the identical tools are attached only to make that prefix match, never for the summarizer to use.
|
|
41
|
+
*/
|
|
42
|
+
export const SUMMARY_INSTRUCTION = "The conversation ABOVE is being compacted to free context. Write a structured note a later turn can fully " +
|
|
43
|
+
"rely on to resume with zero loss. PRESERVE VERBATIM every specific value that appears above — identifiers, " +
|
|
44
|
+
"codes, tokens, numbers, versions, file paths, function/class/variable names, URLs, endpoints, config keys " +
|
|
45
|
+
"and values, commands, and error text. Copy each EXACTLY; never paraphrase, round, or omit a concrete value. " +
|
|
46
|
+
"Terseness applies to prose, NEVER to specifics. Omit ephemeral thinking/scratchpad — keep only durable " +
|
|
47
|
+
"facts a later turn needs. If the conversation above already begins with a '[Compacted summary …]' note, it " +
|
|
48
|
+
"holds facts from even earlier — carry ALL of its concrete values forward into your summary; never drop a " +
|
|
49
|
+
"value because it predates the current task.\n" +
|
|
50
|
+
"Use EXACTLY these sections, each a heading followed by terse bullets (write \"- none\" if a section is empty):\n" +
|
|
51
|
+
"1. INTENT — the user's overall goal and the current task, in their own framing.\n" +
|
|
52
|
+
"2. CONCEPTS — key technical concepts, architecture, and decisions in play.\n" +
|
|
53
|
+
"3. FILES & SNIPPETS — files/dirs central to the work, with the specific functions/symbols and any critical code signatures or snippets, verbatim.\n" +
|
|
54
|
+
"4. ERRORS & FIXES — failures hit and exactly how each was resolved, so they are not repeated.\n" +
|
|
55
|
+
"5. APPROACHES — strategies tried, chosen, and rejected, each with the why.\n" +
|
|
56
|
+
"6. USER MESSAGES — the user's own requests and instructions, quoted VERBATIM (NOT this compaction instruction itself).\n" +
|
|
57
|
+
"7. PENDING — everything still open or unfinished.\n" +
|
|
58
|
+
"8. CURRENT — what is done and verified right now versus in progress.\n" +
|
|
59
|
+
"9. NEXT STEP — the single most immediate next action to resume with.\n" +
|
|
60
|
+
"Do NOT call any tool; output ONLY the summary as plain text. No preamble, no closing remarks.";
|
|
61
|
+
/** A cache-safe summarize request appends a user instruction after the evicted span. If the span's LAST
|
|
62
|
+
* message is an assistant with tool_calls that has no following tool result IN the span (an unanswered
|
|
63
|
+
* call), a user message after it is an invalid sequence for the server. compact() cuts on turn boundaries so
|
|
64
|
+
* the last evicted message is normally an assistant's final answer, making this rare — but guard it anyway:
|
|
65
|
+
* drop a trailing unanswered assistant(tool_calls). Returns a new array; the input is never mutated. */
|
|
66
|
+
export function stripTrailingOrphanToolCall(span) {
|
|
67
|
+
const out = [...span];
|
|
68
|
+
const last = out[out.length - 1];
|
|
69
|
+
if (last && last.role === "assistant" && last.tool_calls?.length)
|
|
70
|
+
out.pop();
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
31
73
|
/** chars/4 ≈ tokens. Crude but dependency-free; swap in a real tokenizer via estimateTokens. */
|
|
32
74
|
export function estimateTokensHeuristic(messages) {
|
|
33
75
|
let chars = 0;
|
|
@@ -50,14 +92,52 @@ export function usageRatio(conversation, opts) {
|
|
|
50
92
|
return fullRequestEstimate(conversation, opts) / opts.ctxWindow;
|
|
51
93
|
}
|
|
52
94
|
export function needsCompaction(conversation, opts) {
|
|
53
|
-
return usageRatio(conversation, opts) >= (opts.threshold ?? 0.
|
|
95
|
+
return usageRatio(conversation, opts) >= (opts.threshold ?? 0.7);
|
|
96
|
+
}
|
|
97
|
+
/** Proactive-compaction trigger for the harness gate: fire on the window-fraction threshold OR the absolute
|
|
98
|
+
* `ceilingTokens` (whichever hits first). Kept SEPARATE from needsCompaction so the over-window circuit
|
|
99
|
+
* breaker keeps testing only the real window — a soft speed ceiling must never be able to "stop" a turn. */
|
|
100
|
+
export function shouldProactivelyCompact(conversation, opts) {
|
|
101
|
+
if (needsCompaction(conversation, opts))
|
|
102
|
+
return true;
|
|
103
|
+
const ceiling = opts.ceilingTokens;
|
|
104
|
+
return !!ceiling && ceiling > 0 && fullRequestEstimate(conversation, opts) >= ceiling;
|
|
105
|
+
}
|
|
106
|
+
/** Last-resort shrink that GUARANTEES a request fits a known-real window. compact() evicts OLD turns; when
|
|
107
|
+
* the over-budget bulk lives INSIDE the kept turns — one turn that dumped tens of KB of tool output (a
|
|
108
|
+
* trace, a big file read, a `dis` dump) — eviction can't shed it and the request 400s again on a small
|
|
109
|
+
* endpoint. This shrinks WITHIN the kept span: it replaces the biggest `tool` messages' content with a
|
|
110
|
+
* short stub, largest first, until the full-request estimate drops under `threshold * ctxWindow`. Tool
|
|
111
|
+
* outputs are the safely-elidable bulk — the assistant already acted on them and their verbatim bytes
|
|
112
|
+
* rarely need re-reading — and the tool_call_id pairing is preserved so the message sequence stays valid.
|
|
113
|
+
* Returns a new array; the input is never mutated. If eliding every tool output still won't fit (huge
|
|
114
|
+
* user/assistant prose), it returns the maximally-elided array so the caller still sends the SMALLEST
|
|
115
|
+
* possible request rather than a guaranteed-fatal one. */
|
|
116
|
+
export function fitToWindow(conversation, opts) {
|
|
117
|
+
if (usageRatio(conversation, opts) < (opts.threshold ?? 0.7))
|
|
118
|
+
return [...conversation];
|
|
119
|
+
const out = conversation.map((m) => ({ ...m }));
|
|
120
|
+
// Tool messages, largest content first — elide the worst offenders until it fits.
|
|
121
|
+
const byLargest = out
|
|
122
|
+
.map((m, i) => ({ i, len: m.role === "tool" ? m.content.length : 0 }))
|
|
123
|
+
.filter((x) => x.len > 0)
|
|
124
|
+
.sort((a, b) => b.len - a.len);
|
|
125
|
+
for (const { i } of byLargest) {
|
|
126
|
+
if (usageRatio(out, opts) < (opts.threshold ?? 0.7))
|
|
127
|
+
break;
|
|
128
|
+
const was = out[i].content.length;
|
|
129
|
+
out[i] = { ...out[i], content: `[large tool output elided to fit the ${opts.ctxWindow.toLocaleString()}-token context — was ${was.toLocaleString()} chars]` };
|
|
130
|
+
}
|
|
131
|
+
return out;
|
|
54
132
|
}
|
|
55
133
|
/** Clamp generation length so prompt + output never exceeds the window. A static max_tokens plus a
|
|
56
134
|
* deep-session prompt otherwise gets the model squeezed to a truncated reply (parity with the Python
|
|
57
135
|
* core's _predict_budget). `built` already includes the system message, so pass systemPrompt:undefined
|
|
58
|
-
* to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored so a
|
|
59
|
-
*
|
|
60
|
-
|
|
136
|
+
* to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored (≥1024) so a
|
|
137
|
+
* tool-calling round keeps room to emit a full tool call's arguments instead of truncating mid-JSON — a
|
|
138
|
+
* cut-off call is unparseable (see selfheal's truncated_tool_call). If even the floor won't fit, the
|
|
139
|
+
* prompt is over budget and the caller's compaction handles it. */
|
|
140
|
+
export function clampMaxTokens(built, opts, want, min = 1024) {
|
|
61
141
|
const promptEst = fullRequestEstimate(built, { ...opts, systemPrompt: undefined });
|
|
62
142
|
const room = opts.ctxWindow - promptEst - 256; // margin for chat-template/role tokens the estimate omits
|
|
63
143
|
return Math.max(min, Math.min(want, room));
|
|
@@ -96,7 +176,19 @@ export async function compact(conversation, opts) {
|
|
|
96
176
|
const kept = dropLeadingOrphanTools(conversation.slice(cutIndex));
|
|
97
177
|
if (!evicted.length)
|
|
98
178
|
return kept;
|
|
99
|
-
|
|
179
|
+
// The summarizer is a network round-trip (it hits the model). If it THROWS — a transient 5xx, a timeout, a
|
|
180
|
+
// failed-over endpoint that's momentarily down — SKIP this compaction instead of letting the error escape
|
|
181
|
+
// and kill the whole turn. compaction fires exactly when the session is stressed (near the ctx ceiling, or
|
|
182
|
+
// mid-failover), so this path is real, not theoretical. The caller retries; runTurn's own self-heal handles
|
|
183
|
+
// the still-over-budget request. Nothing is lost — a summary is never re-derivable, so a skipped compaction
|
|
184
|
+
// is strictly safer than a dead turn.
|
|
185
|
+
let summaryText;
|
|
186
|
+
try {
|
|
187
|
+
summaryText = (await opts.summarize(evicted)).trim();
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return [...conversation];
|
|
191
|
+
}
|
|
100
192
|
// Never destroy the evicted span behind an EMPTY summary. If the summarizer produced nothing (e.g.
|
|
101
193
|
// a model that spent its whole token budget on reasoning and returned empty content — hosts should
|
|
102
194
|
// pass content||reasoningContent, but guard here regardless), SKIP this compaction rather than replace
|
|
@@ -4,11 +4,14 @@
|
|
|
4
4
|
// 1. Structured briefs — a self-contained brief the child can act on without the parent conversation.
|
|
5
5
|
// 2. Schema-enforced final_answer + ONE repair round — validate the child's JSON; on failure feed the
|
|
6
6
|
// error back once and re-run just the final step. The biggest Aurora-specific win.
|
|
7
|
-
// 3. Verify-before-"done" — a result isn't complete until a task-type verify passes
|
|
8
|
-
//
|
|
7
|
+
// 3. Verify-before-"done" — a result isn't complete until a task-type verify passes: the claimed files
|
|
8
|
+
// exist (read-after-write) AND the declared verify_command is actually RUN, with `verified` gated on
|
|
9
|
+
// its real exit code (not the child's self-report). This is the harness owning the truth.
|
|
9
10
|
// 4. Size-routed spawn — a heuristic picks the lane (reasoning = full 1M | fast = small/bounded) so
|
|
10
11
|
// mechanical children don't pin the single 1M slot.
|
|
11
|
-
// Pure + framework-agnostic; node builtins (fs for verify) load lazily so the neutral bundle
|
|
12
|
+
// Pure + framework-agnostic; node builtins (fs/child_process for verify) load lazily so the neutral bundle
|
|
13
|
+
// is unaffected. The verify predicate (isVerifyCmd/ranButFailed) is shared with the main-loop verify gate.
|
|
14
|
+
import { isVerifyCmd, ranButFailed } from "./verify-gate.js";
|
|
12
15
|
const nodeImport = (m) => import(m);
|
|
13
16
|
// Infer the task type from a free-form objective when the caller didn't declare one — keeps the tool
|
|
14
17
|
// usable with just a task string while still selecting the right schema + verify + lane.
|
|
@@ -58,7 +61,7 @@ export function buildBrief(input, cwd) {
|
|
|
58
61
|
input.deliverable?.trim() || "Achieve the objective, then report concisely what you did and where.",
|
|
59
62
|
"",
|
|
60
63
|
"## Definition of done",
|
|
61
|
-
input.done?.trim() || "The objective is achieved AND verified — the changed files exist and your verify_command (tests/build/grep) passes. Do not claim done on the strength of your own say-so; run the check.",
|
|
64
|
+
input.done?.trim() || "The objective is achieved AND verified — the changed files exist and your verify_command (tests/build/grep) passes. Do not claim done on the strength of your own say-so; run the check. A test that only checks a file/path exists proves nothing about behavior — assert on the real output, value, or state, the way a skeptical reviewer would.",
|
|
62
65
|
"",
|
|
63
66
|
"## Final answer (required)",
|
|
64
67
|
"When finished, your LAST output must be ONLY a fenced ```json block matching this schema — no prose after it:",
|
|
@@ -123,10 +126,30 @@ export function repairPrompt(errors, type) {
|
|
|
123
126
|
"```",
|
|
124
127
|
].join("\n");
|
|
125
128
|
}
|
|
129
|
+
// A changed test file whose only assertion-shaped calls are existence checks proves nothing about
|
|
130
|
+
// behavior — the exact incident this harness was built against (docs/verify-before-done.md): a sub-agent
|
|
131
|
+
// reported "37/37, engine works" when the CLI didn't parse; the 37 "tests" were file-exists checks.
|
|
132
|
+
// isVerifyCmd/ranButFailed already prove the declared command really ran and exited 0 — that's a fact
|
|
133
|
+
// about the COMMAND. This is the separate, narrower fact about the TEST ITSELF: flag it only when the
|
|
134
|
+
// whole file has zero calls that compare to an expected value, so a file with one real assertion (even
|
|
135
|
+
// alongside an existence check) clears it. Heuristic and intentionally narrow — a false negative here
|
|
136
|
+
// still leaves the harness's other facts (files exist, command exited 0) standing; a false positive is
|
|
137
|
+
// a missed rubber-stamp, not a broken build.
|
|
138
|
+
const EXISTENCE_CHECK = /\b(?:existsSync|fs\.access|pathExists|fs\.stat|statSync)\s*\(/;
|
|
139
|
+
const VALUE_ASSERTION = /\b(?:assertEqual|assert\.equal|assert\.strictEqual|assert\.deepEqual|toEqual|toBe\(|toContain|toMatch|toHaveLength|expect\.arrayContaining)\s*\(/;
|
|
140
|
+
/** Null when `content` isn't a test file, or looks like a real one; else a one-line reason it's shallow. */
|
|
141
|
+
export function detectShallowTest(path, content) {
|
|
142
|
+
if (!/\.(test|spec)\.[jt]sx?$/.test(path))
|
|
143
|
+
return null;
|
|
144
|
+
if (EXISTENCE_CHECK.test(content) && !VALUE_ASSERTION.test(content)) {
|
|
145
|
+
return `${path} only checks file/path existence — no assertion compares an actual value`;
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
126
149
|
/** Verify the child's claim WITHOUT trusting its say-so (mechanism 3). Orchestrator-side, cheap + real:
|
|
127
|
-
* a code-edit's claimed files_changed must actually exist on disk (read-after-write)
|
|
128
|
-
* verify_command
|
|
129
|
-
*
|
|
150
|
+
* a code-edit's claimed files_changed must actually exist on disk (read-after-write), the declared
|
|
151
|
+
* verify_command must actually be RUN with a real passing exit code (never the child's self-report), and
|
|
152
|
+
* any changed test file must not be hollow (detectShallowTest). Non-code tasks pass structurally. */
|
|
130
153
|
export async function verifyFinalAnswer(value, type, cwd) {
|
|
131
154
|
if (type !== "code-edit")
|
|
132
155
|
return { verified: true, detail: "no file-level verify for this task type" };
|
|
@@ -134,7 +157,7 @@ export async function verifyFinalAnswer(value, type, cwd) {
|
|
|
134
157
|
if (files.length === 0)
|
|
135
158
|
return { verified: false, detail: "code-edit reported no files_changed" };
|
|
136
159
|
try {
|
|
137
|
-
const { stat } = await nodeImport("node:fs/promises");
|
|
160
|
+
const { stat, readFile } = await nodeImport("node:fs/promises");
|
|
138
161
|
const { isAbsolute, join } = await nodeImport("node:path");
|
|
139
162
|
const missing = [];
|
|
140
163
|
for (const f of files) {
|
|
@@ -148,8 +171,44 @@ export async function verifyFinalAnswer(value, type, cwd) {
|
|
|
148
171
|
}
|
|
149
172
|
if (missing.length)
|
|
150
173
|
return { verified: false, detail: `claimed files do not exist: ${missing.join(", ")}` };
|
|
151
|
-
|
|
152
|
-
|
|
174
|
+
// Actually RUN the declared verify command and gate `verified` on its real exit code — this is what
|
|
175
|
+
// turns a sub-agent's "verified" from a self-report into a harness fact (the fix for the hollow verify
|
|
176
|
+
// this file's callers depend on). Only run recognized test/build/run commands (isVerifyCmd allowlist),
|
|
177
|
+
// so a trivial/absent command counts as unverified rather than a rubber stamp.
|
|
178
|
+
const vc = typeof value.verify_command === "string" ? value.verify_command.trim() : "";
|
|
179
|
+
if (!vc)
|
|
180
|
+
return { verified: false, detail: `${files.length} file(s) exist, but no verify_command was declared — not verified` };
|
|
181
|
+
if (!isVerifyCmd(vc))
|
|
182
|
+
return { verified: false, detail: `verify_command is not a recognized test/build/run ("${vc.slice(0, 60)}") — not verified` };
|
|
183
|
+
try {
|
|
184
|
+
const { execFile } = await nodeImport("node:child_process");
|
|
185
|
+
const { promisify } = await nodeImport("node:util");
|
|
186
|
+
const out = await promisify(execFile)("bash", ["-lc", vc], { cwd, timeout: 180_000, maxBuffer: 10 * 1024 * 1024 });
|
|
187
|
+
const text = String(out.stdout ?? "") + String(out.stderr ?? "");
|
|
188
|
+
if (ranButFailed(text))
|
|
189
|
+
return { verified: false, detail: `verify_command reported failure: ${vc.slice(0, 60)}` };
|
|
190
|
+
// The command really ran and exited 0 (a fact). Before trusting it, check whether any changed test
|
|
191
|
+
// file is itself hollow (the "green tests hid data loss" pattern) — downgrade rather than rubber-stamp,
|
|
192
|
+
// so a shallow pass surfaces as unverified instead of a silent "done".
|
|
193
|
+
for (const f of files) {
|
|
194
|
+
const p = isAbsolute(f) ? f : join(cwd, f);
|
|
195
|
+
let src;
|
|
196
|
+
try {
|
|
197
|
+
src = await readFile(p, "utf8");
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
continue;
|
|
201
|
+
} // unreadable — don't block on it
|
|
202
|
+
const shallow = detectShallowTest(f, src);
|
|
203
|
+
if (shallow)
|
|
204
|
+
return { verified: false, detail: `verify_command passed, but ${shallow} — assert on real output/state, not just presence` };
|
|
205
|
+
}
|
|
206
|
+
return { verified: true, detail: `verify_command passed (exit 0): ${vc.slice(0, 60)}` };
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
const code = e?.code;
|
|
210
|
+
return { verified: false, detail: `verify_command FAILED (${code ?? "error"}): ${vc.slice(0, 60)}` };
|
|
211
|
+
}
|
|
153
212
|
}
|
|
154
213
|
catch (e) {
|
|
155
214
|
return { verified: false, detail: `verify error: ${e instanceof Error ? e.message : String(e)}` };
|
|
@@ -25,5 +25,8 @@ export function engineRouter(inner = new AuroraRouter()) {
|
|
|
25
25
|
// If the router hands back the same endpoint, there's nowhere further to go → exhausted.
|
|
26
26
|
return next.base === failed.base ? null : toRE(next);
|
|
27
27
|
},
|
|
28
|
+
observeContext(endpoint, servedCtx) {
|
|
29
|
+
inner.observeContextLimit(endpoint.base, servedCtx); // clamp the roster's optimistic ctxLimit to the served truth
|
|
30
|
+
},
|
|
28
31
|
};
|
|
29
32
|
}
|
package/dist/engine/selfheal.js
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
|
+
// A 503/5xx whose body says the endpoint is (re)starting — llama.cpp returns {"message":"Loading model",
|
|
2
|
+
// "type":"unavailable_error","code":503} while a model reloads (seen live 09-26 after a JL2 aurora restart
|
|
3
|
+
// to change ctx). Unlike a generic 5xx this WILL become ready, but a model load is ~30-90s — far longer
|
|
4
|
+
// than the exponential self-heal backoff — so it gets its own class: wait patiently and retry the SAME
|
|
5
|
+
// endpoint until it's up, rather than fail fast. Kept narrow (loading/warming/starting, NOT bare
|
|
6
|
+
// "unavailable"/"service unavailable") so a genuinely down backend still fails over as transient.
|
|
7
|
+
const LOADING_RE = /loading|warming|starting up|not ready|being loaded/i;
|
|
1
8
|
// A 400/413/500 whose body mentions any of these is really a context/memory-pressure failure, so the
|
|
2
9
|
// fix is a bigger window or compaction — not a blind resend.
|
|
3
10
|
const CTX_RE = /context|n_ctx|exceed|too long|too many tokens|maximum context|out of memory|kv cache/i;
|
|
11
|
+
// A 4xx/5xx whose body says the server couldn't parse the model's OWN tool-call arguments as JSON: the
|
|
12
|
+
// model tried to emit one over-long call (a whole-file write in a single new_string) and the output was
|
|
13
|
+
// cut off mid-string at the token limit, leaving unterminated JSON the server rejects. Seen live: aurora
|
|
14
|
+
// /v1 500 "Failed to parse tool call arguments as JSON: missing closing quote" / "Unterminated string in
|
|
15
|
+
// JSON at position …". This is NOT a busy backend — failing over just truncates the same write on the
|
|
16
|
+
// next endpoint — so it gets its own class: nudge the model to chunk the write and retry in place.
|
|
17
|
+
const TRUNC_TOOL_RE = /parse tool call arguments|unterminated string|missing closing quote/i;
|
|
18
|
+
// When an endpoint rejects a request for exceeding its window, its error body carries the REAL window it
|
|
19
|
+
// enforces — aurora /v1 returns {"type":"exceed_context_size_error","n_ctx":65536,...} plus the human
|
|
20
|
+
// "exceeds the available context size (65536 tokens)". The configured ctxWindow is often optimistic (a
|
|
21
|
+
// node's llama.cpp `-c` is smaller than the roster claims — 09-26: JL2 served 64K while configured 256K),
|
|
22
|
+
// so we LEARN the served size from the error and clamp the endpoint to it rather than overflow it again.
|
|
23
|
+
// Returns the served n_ctx in tokens, or undefined when the body names none.
|
|
24
|
+
const SERVED_CTX_RE = /"n_ctx"\s*:\s*(\d+)|(?:available )?context size \((\d+)\s*tokens?\)/i;
|
|
25
|
+
export function servedContextLimit(err) {
|
|
26
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
27
|
+
const m = SERVED_CTX_RE.exec(msg);
|
|
28
|
+
if (!m)
|
|
29
|
+
return undefined;
|
|
30
|
+
const n = Number(m[1] ?? m[2]);
|
|
31
|
+
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
32
|
+
}
|
|
4
33
|
function statusOf(err) {
|
|
5
34
|
const s = err?.status;
|
|
6
35
|
if (typeof s === "number" && Number.isFinite(s))
|
|
@@ -15,10 +44,16 @@ export function classifyFailure(err) {
|
|
|
15
44
|
const msg = err instanceof Error ? err.message : String(err);
|
|
16
45
|
if (s === 401 || s === 403)
|
|
17
46
|
return "auth"; // credentials — resending never helps
|
|
47
|
+
// The model's own tool-call JSON was truncated mid-arguments → server can't parse it. Recover by
|
|
48
|
+
// chunking the write (agent loop), never by failover (the next endpoint truncates the same write).
|
|
49
|
+
if (s !== undefined && s >= 400 && TRUNC_TOOL_RE.test(msg))
|
|
50
|
+
return "truncated_tool_call";
|
|
18
51
|
if (s === 413)
|
|
19
52
|
return "context"; // payload too large == context pressure
|
|
20
53
|
if (s === 400)
|
|
21
54
|
return CTX_RE.test(msg) ? "context" : "bad_request"; // the 400 body decides
|
|
55
|
+
if (s !== undefined && s >= 500 && LOADING_RE.test(msg))
|
|
56
|
+
return "loading"; // endpoint (re)starting — wait it out, don't fail fast
|
|
22
57
|
if (s === 429 || (s !== undefined && s >= 500))
|
|
23
58
|
return "transient"; // rate-limit / server — back off + retry
|
|
24
59
|
if (s === undefined)
|