@0perator/operator 0.1.222 → 0.1.261
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/README.md +6 -5
- package/dashboard/server.mjs +1 -1
- package/dist/acp/agent.js +320 -53
- package/dist/acp/auth.js +44 -0
- package/dist/acp/config-options.js +34 -0
- package/dist/acp/prompt.js +41 -0
- package/dist/acp/run.js +116 -10
- package/dist/acp/tool-map.js +48 -0
- package/dist/auth/byo.js +125 -0
- package/dist/auth/client.js +12 -6
- package/dist/auth/commands.js +71 -3
- package/dist/auth/identity.js +136 -0
- package/dist/auth/store.js +7 -5
- package/dist/autonomy/board.js +3 -2
- package/dist/autonomy/cron.js +332 -0
- package/dist/autonomy/delegate.js +168 -0
- package/dist/autonomy/dream.js +1 -1
- package/dist/autonomy/index.js +16 -2
- package/dist/autonomy/media-robot.js +137 -0
- package/dist/autonomy/profile.js +77 -0
- package/dist/autonomy/routines.js +5 -4
- package/dist/autonomy/session-factory.js +19 -10
- package/dist/background/index.js +8 -1
- package/dist/browser/cdp.js +266 -0
- package/dist/browser/session.js +286 -0
- package/dist/cli.js +207 -106
- package/dist/compose/client.js +56 -0
- package/dist/config/brand.js +3 -3
- package/dist/config/home.js +70 -0
- package/dist/config/managed.js +230 -0
- package/dist/config/persona.js +243 -21
- package/dist/config/scaffold.js +142 -0
- package/dist/config/settings.js +87 -20
- package/dist/config/skills-index.js +175 -0
- package/dist/consolidation/scheduler.js +10 -7
- package/dist/consolidation/sleep.js +17 -3
- package/dist/engine/agent.js +231 -21
- package/dist/engine/aurora.js +79 -14
- package/dist/engine/batch-scheduler.js +128 -0
- package/dist/engine/compaction.js +129 -2
- package/dist/engine/computer-event.js +139 -0
- package/dist/engine/continuation.js +55 -0
- package/dist/engine/contract.js +3 -1
- package/dist/engine/grandmaster.js +13 -3
- package/dist/engine/json-repair.js +105 -0
- package/dist/engine/messages.js +52 -5
- package/dist/engine/redact.js +25 -0
- package/dist/engine/rolling-summary.js +28 -11
- package/dist/engine/router-adapter.js +2 -0
- package/dist/engine/unrestricted.js +51 -0
- package/dist/engine/verify-gate.js +6 -0
- package/dist/enterprise/cli.js +137 -0
- package/dist/flywheel/processor.js +30 -2
- package/dist/flywheel/secret-gate.js +123 -0
- package/dist/index.browser.js +4 -0
- package/dist/index.js +4 -0
- package/dist/mcp/index.js +18 -24
- package/dist/memory/index.js +0 -0
- package/dist/memory/session-index.js +324 -0
- package/dist/memory/session-rewind.js +92 -0
- package/dist/memory/state-maintenance.js +441 -0
- package/dist/observability/index.js +3 -3
- package/dist/permissions/audit.js +4 -1
- package/dist/permissions/index.js +24 -12
- package/dist/permissions/policy.js +4 -3
- package/dist/permissions/tier.js +31 -14
- package/dist/remote/host.js +9 -2
- package/dist/router/models.js +62 -2
- package/dist/selfimprove/index.js +9 -7
- package/dist/session.js +129 -42
- package/dist/skills/catalogue.js +167 -0
- package/dist/telemetry/audit-verify.js +94 -0
- package/dist/telemetry/events.js +92 -7
- package/dist/telemetry/lifecycle.js +18 -0
- package/dist/tools/computer.js +1 -1
- package/dist/tools/deferred.js +117 -0
- package/dist/tools/executor.js +27 -23
- package/dist/tools/memory.js +117 -0
- package/dist/tools/mutating.js +6 -0
- package/dist/tools/registry.js +1022 -46
- package/dist/tools/sandbox.js +63 -17
- package/dist/tools/searxng.js +2 -2
- package/dist/tools/shell-session.js +36 -1
- package/dist/tools/tool-output-spill.js +4 -4
- package/dist/ui/ActivitySpinner.js +17 -6
- package/dist/ui/App.js +36 -14
- package/dist/ui/ArtifactPicker.js +109 -0
- package/dist/ui/Composer.js +39 -8
- package/dist/ui/Markdown.js +5 -3
- package/dist/ui/MouseProvider.js +99 -19
- package/dist/ui/QuestionPrompt.js +24 -3
- package/dist/ui/ThinkingSpinner.js +9 -5
- package/dist/ui/ToolStep.js +17 -12
- package/dist/ui/Transcript.js +28 -9
- package/dist/ui/capabilities.js +0 -9
- package/dist/ui/listhit.js +23 -0
- package/dist/ui/mouse.js +22 -0
- package/dist/ui/osc.js +7 -4
- package/dist/ui/progressbar.js +46 -0
- package/dist/ui/shimmer.js +43 -0
- package/dist/ui/theme.js +2 -0
- package/dist/ui/tick.js +48 -0
- package/dist/ui/toolicons.js +69 -0
- package/dist/ui/useInputHistory.js +3 -3
- package/dist/util/slash.js +1 -0
- package/dist/vault/cli.js +48 -0
- package/dist/vault/store.js +157 -0
- package/dist/vault/tool.js +50 -0
- package/package.json +3 -5
- package/CHANGELOG.md +0 -1629
package/dist/engine/agent.js
CHANGED
|
@@ -3,12 +3,15 @@
|
|
|
3
3
|
// NOT implemented here — this file depends only on the two interfaces below, which the
|
|
4
4
|
// kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
|
|
5
5
|
import { chat } from "./aurora.js";
|
|
6
|
+
import { parseToolArgs } from "./json-repair.js";
|
|
6
7
|
import { buildMessages } from "./messages.js";
|
|
7
8
|
import { recoverToolCalls } from "./toolcalls.js";
|
|
8
9
|
import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens } from "./compaction.js";
|
|
9
10
|
import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
|
|
10
11
|
import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
|
|
11
12
|
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
|
|
13
|
+
import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
|
|
14
|
+
import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
|
|
12
15
|
const MAX_SELF_HEAL_PER_TURN = 3;
|
|
13
16
|
// A "loading" 503 (endpoint restarting/warming) is a KNOWN-recoverable WAIT, not a failure — a model reload
|
|
14
17
|
// is ~30-90s, far longer than the ≤8s exponential self-heal backoff, so it gets its own patient budget that
|
|
@@ -20,10 +23,16 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
|
|
|
20
23
|
// file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
|
|
21
24
|
// with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
|
|
22
25
|
// headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
|
|
23
|
-
import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a workspace edit ⇒ prior identical-call counts are stale
|
|
26
|
+
import { MUTATING_TOOLS, mutationLanded } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
|
|
27
|
+
import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, detectUnfinishedAction } from "./continuation.js";
|
|
24
28
|
// Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
|
|
25
29
|
// loop guard skips them entirely (agent_status polls sub-agents, bash_output polls a background job).
|
|
26
30
|
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]);
|
|
31
|
+
// Hard backstop: after this many identical (name+args) calls in a turn with NO intervening edit, the model is
|
|
32
|
+
// spinning on a poisoned call and ignoring every short-circuit warning — abort the turn cleanly instead of
|
|
33
|
+
// burning rounds to maxRoundsHard. An Aurora blip once drove the same blocked bash call 16× before the turn
|
|
34
|
+
// died: LOOP_GUARD_LIMIT only *short-circuits* the call, it never *stopped* the spin — this does.
|
|
35
|
+
const LOOP_GUARD_HARD = LOOP_GUARD_LIMIT * 2; // 10
|
|
27
36
|
const CONTENT_LOOP_LIMIT = 3; // whole round (prose + actions) repeats this many times ⇒ light NUDGE to pivot
|
|
28
37
|
const CONTENT_LOOP_REDIRECT = 6; // …and at this many, escalate to a FORCED REDIRECT: make the model diagnose the
|
|
29
38
|
// loop and decompose OR switch approach, then reset its runway and CONTINUE (enterprise loop-recovery — the
|
|
@@ -45,7 +54,23 @@ const NO_PROGRESS_LIMIT = 8; // consecutive tool batches that return NOTHING new
|
|
|
45
54
|
// only ever NUDGES once (NO_EDIT_NUDGE); it never stops a turn, so a genuine long read-only task is safe.
|
|
46
55
|
const SELF_LOOP_RE = /\b(stuck in a loop|going in circles|in an?(?: infinite)? loop|repeating (?:the same|myself|it)|same (?:code|thing|approach|command)(?: keeps| is| that)?(?: getting)? repeat|keep (?:repeating|doing the same|getting the same)|(?:try|take|need) (?:a |an )?(?:fresh|different|new|another) approach)\b/i;
|
|
47
56
|
const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file edit between) ⇒ graceful stop
|
|
57
|
+
// Converge-or-stop guard: the identical-call guards above can't catch a model that varies its args every round
|
|
58
|
+
// (a different path / pattern / comment each time) yet never answers and never changes a file. This many
|
|
59
|
+
// CONSECUTIVE tool rounds with NO new narration from the model and NO landed file change ⇒ it is not converging:
|
|
60
|
+
// STOP with an honest message. Reset by new assistant text or a mutation that landed; poll-only rounds
|
|
61
|
+
// (agent_status / bash_output) neither count nor reset. Above NO_EDIT_NUDGE (15) so a long silent read-only survey
|
|
62
|
+
// still gets its one soft nudge first. Paired with turn-continuation (continuation.ts): keep going on real work,
|
|
63
|
+
// stop on circles.
|
|
64
|
+
const NO_CONVERGE_LIMIT = 25;
|
|
48
65
|
const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
|
|
66
|
+
// Think-spiral latch: with /think ON, a reasoning model can spend round after round in heavy reasoning that
|
|
67
|
+
// keeps acting (a poll/read tool) but never edits a file or answers. The churn lives in the reasoning
|
|
68
|
+
// channel, so every content-based guard above misses it (and its phrasing varies enough to dodge the prose
|
|
69
|
+
// fingerprint); meanwhile it eats the shared token budget — the answer gets cut off — and floods the
|
|
70
|
+
// transcript. After THINK_SPIRAL_ROUNDS such rounds we latch native thinking OFF for the rest of the turn
|
|
71
|
+
// and push the model to act or answer. Reversible (per-turn), never a hard stop; a file edit clears it.
|
|
72
|
+
const THINK_SPIRAL_ROUNDS = 5; // consecutive heavy-reasoning, no-file-edit rounds (while /think on) ⇒ latch think OFF
|
|
73
|
+
const THINK_SPIRAL_MIN_REASON_CHARS = 400; // a round counts as "heavy reasoning" only past this much reasoning_content
|
|
49
74
|
const REHYDRATE_MAX_FILES = 5; // after a compaction, name up to this many recently-touched files for the model to re-read
|
|
50
75
|
const COMPACTION_FAIL_LIMIT = 3; // rounds still OVER the window after compaction ran ⇒ it can't free space (summarizer failing / un-evictable bulk); stop spinning into the same wall
|
|
51
76
|
const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated tool call surfaces honestly — a
|
|
@@ -150,8 +175,8 @@ function observeVerify(v, calls, toolMsgs) {
|
|
|
150
175
|
}
|
|
151
176
|
/** Thrown by runTurn when the turn is interrupted via AgentOpts.signal (SPEC §9). One type for hosts to catch. */
|
|
152
177
|
export class TurnAbortedError extends Error {
|
|
153
|
-
constructor() {
|
|
154
|
-
super("turn aborted");
|
|
178
|
+
constructor(reason) {
|
|
179
|
+
super(reason ?? "turn aborted");
|
|
155
180
|
this.name = "TurnAbortedError";
|
|
156
181
|
}
|
|
157
182
|
}
|
|
@@ -201,17 +226,11 @@ function stripScratchpad(content) {
|
|
|
201
226
|
.trim();
|
|
202
227
|
}
|
|
203
228
|
function parseArgs(raw) {
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
return { ok: true, args: parsed };
|
|
210
|
-
return { ok: false, error: "arguments did not parse to an object" };
|
|
211
|
-
}
|
|
212
|
-
catch (err) {
|
|
213
|
-
return { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
214
|
-
}
|
|
229
|
+
// json-repair: control chars inside strings get escaped (multi-line bash -c scripts survive), and
|
|
230
|
+
// truncation-vs-malformed is classified so the error the model sees is ACTIONABLE (the generic
|
|
231
|
+
// "Unterminated string" reply sent a live review session on a 69-tool-call hallucination spiral).
|
|
232
|
+
const r = parseToolArgs(raw);
|
|
233
|
+
return r.ok ? { ok: true, args: r.args } : { ok: false, error: r.error };
|
|
215
234
|
}
|
|
216
235
|
/**
|
|
217
236
|
* Runs tool_calls (structured or text-recovered) through the executor, honoring the loop
|
|
@@ -229,6 +248,7 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
|
|
|
229
248
|
const pending = [];
|
|
230
249
|
const preResolved = new Map(); // id -> result, for parse errors + loop-guarded calls
|
|
231
250
|
const parsedArgs = new Map();
|
|
251
|
+
let loopAbort; // set when a signature blows past LOOP_GUARD_HARD — the turn is aborted (below)
|
|
232
252
|
toolCalls.forEach((tc, batchIndex) => {
|
|
233
253
|
const parsed = parseArgs(tc.function.arguments);
|
|
234
254
|
if (!parsed.ok) {
|
|
@@ -249,12 +269,23 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
|
|
|
249
269
|
const count = (callCounts.get(sig) ?? 0) + 1;
|
|
250
270
|
callCounts.set(sig, count);
|
|
251
271
|
if (count >= LOOP_GUARD_LIMIT) { // SPEC §2: short-circuit the Nth identical call (matches executor's guard)
|
|
272
|
+
if (count >= LOOP_GUARD_HARD) {
|
|
273
|
+
// The model ignored LOOP_GUARD_HARD short-circuit warnings for this exact call with no intervening edit —
|
|
274
|
+
// it is not recovering. Flag it; the turn is aborted after this batch rather than spinning to the cap.
|
|
275
|
+
loopAbort = `"${tc.function.name}" was called ${count}× with identical arguments and no intervening ` +
|
|
276
|
+
`progress — the turn was stopped to avoid an unrecoverable loop (often an upstream/engine blip the ` +
|
|
277
|
+
`model kept retrying). Nothing was lost; re-run the request.`;
|
|
278
|
+
}
|
|
252
279
|
preResolved.set(tc.id, `Loop guard: "${tc.function.name}" has been called ${count} times this turn with identical ` +
|
|
253
280
|
`arguments. Try a different approach instead of repeating this call.`);
|
|
254
281
|
return;
|
|
255
282
|
}
|
|
256
283
|
pending.push({ id: tc.id, name: tc.function.name, args: parsed.args, batchId, batchSize, batchIndex });
|
|
257
284
|
});
|
|
285
|
+
// A signature blew past the hard loop ceiling: stop the turn cleanly rather than let the model spin to the
|
|
286
|
+
// round cap. TurnAbortedError is the engine's existing clean-stop path (identical to an esc interrupt).
|
|
287
|
+
if (loopAbort)
|
|
288
|
+
throw new TurnAbortedError(`Loop guard: ${loopAbort}`);
|
|
258
289
|
if (pending.length)
|
|
259
290
|
onToolStart?.(pending);
|
|
260
291
|
const started = performance.now();
|
|
@@ -264,11 +295,13 @@ async function runToolCalls(toolCalls, tools, callCounts, onToolBatch, onToolSta
|
|
|
264
295
|
const durationMs = performance.now() - started;
|
|
265
296
|
const resultById = new Map(preResolved);
|
|
266
297
|
pending.forEach((p, i) => resultById.set(p.id, executed[i]));
|
|
267
|
-
// A file edit this round changed the workspace, so every prior "identical call" count is stale — a
|
|
298
|
+
// A file edit that LANDED this round changed the workspace, so every prior "identical call" count is stale — a
|
|
268
299
|
// re-run of the same test/build/compose is now verify-after-fix progress, not a loop. Clear the counts so
|
|
269
300
|
// the next round's repeats start fresh; only a call repeated with NO intervening edit keeps accumulating
|
|
270
301
|
// toward LOOP_GUARD_LIMIT. This is what lets Operator iterate (edit → re-run → edit → re-run) unbounded.
|
|
271
|
-
|
|
302
|
+
// A FAILING edit ("error: old_string not found") changed nothing — it must not reset the count, or a model
|
|
303
|
+
// can alternate a failing edit with the same poisoned call forever (the guard could never stop it).
|
|
304
|
+
if (pending.some((p, i) => mutationLanded(p.name, executed[i])))
|
|
272
305
|
callCounts.clear();
|
|
273
306
|
if (onToolBatch) {
|
|
274
307
|
const events = toolCalls.map((tc, batchIndex) => ({
|
|
@@ -320,12 +353,15 @@ export function rehydrationNote(touched) {
|
|
|
320
353
|
export async function runTurn(userInput, conversation, opts) {
|
|
321
354
|
const softRounds = opts.maxRounds ?? 10;
|
|
322
355
|
const absCeiling = Math.max(softRounds + 1, opts.maxRoundsHard ?? 400); // absolute safety stop; progress-aware below
|
|
356
|
+
const turnStart = Date.now(); // for the per-turn wall-clock budget (opts.maxTurnWallClockMs) — the only bound on TIME
|
|
323
357
|
const callCounts = new Map();
|
|
324
358
|
const contentSigs = new Map(); // per-round prose fingerprints → the narration loop guard
|
|
325
359
|
let forcedRedirects = 0; // enterprise loop-recovery: forced redirects spent this turn (each resets a repeated round's runway; the turn hands back only after CONTENT_LOOP_REDIRECT_MAX of them fail to break the loop)
|
|
326
360
|
let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
|
|
327
361
|
let noProgressStreak = 0; // consecutive tool batches that returned nothing new; reset by any real progress
|
|
328
362
|
let selfLoopStreak = 0; // consecutive rounds the model admitted it's looping, uninterrupted by a file edit
|
|
363
|
+
let thinkSpiralStreak = 0; // consecutive heavy-reasoning, no-file-edit rounds while /think is on
|
|
364
|
+
let thinkLatched = false; // once a think-spiral is detected, force thinking:false for the rest of the turn
|
|
329
365
|
let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
|
|
330
366
|
let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
|
|
331
367
|
const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
|
|
@@ -338,6 +374,64 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
338
374
|
const verifyEnabled = opts.verifyGate?.enabled !== false;
|
|
339
375
|
const verifyMaxNudges = Math.max(0, opts.verifyGate?.maxNudges ?? 1);
|
|
340
376
|
let verifyNudges = 0;
|
|
377
|
+
const unrestrictedEnabled = opts.unrestricted !== false; // default on — owner's private system
|
|
378
|
+
// 0perator Computer feed (opt-in, additive): when the host wants a typed action stream, compose the two
|
|
379
|
+
// tool callbacks here so runToolCalls stays untouched. The tracker pushes normalized start/end events into
|
|
380
|
+
// a stream; subscribe(0) forwards each to the host's onComputerEvent. A throwing host callback can't break
|
|
381
|
+
// the turn (ComputerEventStream isolates subscribers). The composed callbacks fall back to the originals
|
|
382
|
+
// verbatim when no computer feed is wanted, so the common path is unchanged.
|
|
383
|
+
let onToolStartFx = opts.onToolStart;
|
|
384
|
+
let onToolResultFx = opts.onToolResult;
|
|
385
|
+
if (opts.onComputerEvent) {
|
|
386
|
+
const ceStream = new ComputerEventStream();
|
|
387
|
+
ceStream.subscribe(0, opts.onComputerEvent);
|
|
388
|
+
const ceTracker = new ComputerEventTracker(ceStream, opts.computerEnv ?? "sandbox");
|
|
389
|
+
const origStart = opts.onToolStart;
|
|
390
|
+
const origResult = opts.onToolResult;
|
|
391
|
+
onToolStartFx = (calls) => { origStart?.(calls); ceTracker.onToolStart(calls); };
|
|
392
|
+
onToolResultFx = (id, result, batchId) => { origResult?.(id, result, batchId); ceTracker.onToolResult(id, result); };
|
|
393
|
+
}
|
|
394
|
+
// Turn-continuation: nudge a model that ends on an unperformed action announcement to actually do it (bounded).
|
|
395
|
+
const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
|
|
396
|
+
const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
|
|
397
|
+
let announceNudges = 0;
|
|
398
|
+
// Spectre-parity (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
|
|
399
|
+
let truncationContinues = 0;
|
|
400
|
+
const TRUNCATION_CONTINUE_MAX = 3;
|
|
401
|
+
// Cortana think-on truncation fix (task #14): once a round this turn hits the output-token limit, native
|
|
402
|
+
// reasoning (/think) is the thing that ate the budget — a think-heavy model spends the window reasoning,
|
|
403
|
+
// then the tool-call JSON (or answer) is cut off mid-generation. Re-running the recovery round WITH think
|
|
404
|
+
// still on just re-truncates and burns all 3 continue slots. So after the first length-truncation this
|
|
405
|
+
// turn, force reasoning OFF for the remaining rounds: the cut-off tool call re-emits compactly and fits in
|
|
406
|
+
// ONE round. Sticky for the turn (the model proved it over-reasons here), resets next turn, and leaves the
|
|
407
|
+
// owner's /think preference untouched for turns that don't truncate. The flag is per-call (aurora.ts
|
|
408
|
+
// enable_thinking), so this is a pure round-local override, no server/config change.
|
|
409
|
+
let truncatedThisTurn = false;
|
|
410
|
+
// Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
|
|
411
|
+
let convergeStreak = 0;
|
|
412
|
+
const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
|
|
413
|
+
const stopTurn = (note, roundsRun) => {
|
|
414
|
+
conversation.assistant(note);
|
|
415
|
+
return { content: note, rounds: roundsRun, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
416
|
+
};
|
|
417
|
+
/** Feed one settled tool batch to the converge guard; true ⇒ the turn has stalled and must stop. */
|
|
418
|
+
const stalledNotConverging = (calls, toolMsgs, content) => {
|
|
419
|
+
if (calls.every((c) => LOOP_GUARD_EXEMPT.has(c.function?.name ?? "")))
|
|
420
|
+
return false; // pure polling: legit, neither counts nor resets
|
|
421
|
+
const sig = contentSignature(content);
|
|
422
|
+
const narrated = sig.length >= 12 && !narratedSigs.has(sig);
|
|
423
|
+
if (sig)
|
|
424
|
+
narratedSigs.add(sig);
|
|
425
|
+
const landed = calls.some((c, i) => mutationLanded(c.function?.name, toolMsgs[i]?.content ?? ""));
|
|
426
|
+
convergeStreak = narrated || landed ? 0 : convergeStreak + 1;
|
|
427
|
+
return convergeStreak >= NO_CONVERGE_LIMIT;
|
|
428
|
+
};
|
|
429
|
+
const notConvergingNote = (calls) => {
|
|
430
|
+
const last = calls[calls.length - 1]?.function?.name ?? "tool";
|
|
431
|
+
return `[stopped — not converging: ${convergeStreak} tool rounds in a row (last: ${last}) with no new explanation ` +
|
|
432
|
+
`from me and no file change that landed, so I'm handing back rather than burn more time. Nothing was lost — ` +
|
|
433
|
+
`tell me how you'd like to proceed, or ask me to continue and I'll pick up from here with a different approach.]`;
|
|
434
|
+
};
|
|
341
435
|
conversation.user(userInput);
|
|
342
436
|
let rounds = 0;
|
|
343
437
|
let toolCallTotal = 0;
|
|
@@ -358,7 +452,23 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
358
452
|
const spent = tokensTotal + promptTokensTotal;
|
|
359
453
|
const note = `[paused — this turn reached its token budget (${spent} ≥ ${opts.maxTurnTokens} tokens). ` +
|
|
360
454
|
`The work so far is above; continue with a fresh, focused request, or raise the budget ` +
|
|
361
|
-
`(
|
|
455
|
+
`(settings.maxTurnTokens).]`;
|
|
456
|
+
conversation.assistant(note);
|
|
457
|
+
return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
458
|
+
}
|
|
459
|
+
// Opt-in per-turn WALL-CLOCK ceiling: the only bound on TIME. Round/token budgets don't stop a turn whose
|
|
460
|
+
// decode has crawled (RAM pressure from a big model on the serving box, or very high context) to ~1 tok/s —
|
|
461
|
+
// such a turn can run an hour generating almost nothing. Wrap up gracefully at the round boundary instead
|
|
462
|
+
// (loop mode continues the objective next turn). "[paused —" (not "[stopped —") so the flywheel doesn't
|
|
463
|
+
// read a time cap as a failure-lesson.
|
|
464
|
+
if (opts.maxTurnWallClockMs && rounds > 0 && Date.now() - turnStart >= opts.maxTurnWallClockMs) {
|
|
465
|
+
const ranMin = Math.round((Date.now() - turnStart) / 60000);
|
|
466
|
+
const capMin = Math.round(opts.maxTurnWallClockMs / 60000);
|
|
467
|
+
const spent = tokensTotal + promptTokensTotal;
|
|
468
|
+
const tps = genMsTotal > 0 ? (tokensTotal / (genMsTotal / 1000)) : 0;
|
|
469
|
+
const crawl = tps > 0 && tps < 3 ? ` Decode was crawling (~${tps.toFixed(1)} tok/s) — likely RAM pressure (a large model loaded on the serving box) or very high context; avoid co-locating heavy model loads with the serving model.` : "";
|
|
470
|
+
const note = `[paused — this turn hit its ${capMin}-min wall-clock budget (ran ${ranMin} min, ${spent} tokens).${crawl} ` +
|
|
471
|
+
`The work so far is above; continue with a fresh, focused request (or raise it via settings.autonomy.maxTurnWallClockSec).]`;
|
|
362
472
|
conversation.assistant(note);
|
|
363
473
|
return { content: note, rounds, toolCalls: toolCallTotal, tokens: tokensTotal, genMs: genMsTotal, promptTokens: promptTokensTotal, promptMs: promptMsTotal };
|
|
364
474
|
}
|
|
@@ -432,15 +542,17 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
432
542
|
const messages = buildMessages(opts.systemPrompt, conversation.all);
|
|
433
543
|
// Clamp generation to the room left after the real prompt (incl. tool_calls args + schemas) so a
|
|
434
544
|
// deep-session request never overflows the window into a truncated reply. See clampMaxTokens.
|
|
435
|
-
const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ??
|
|
545
|
+
const maxTokens = clampMaxTokens(messages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192);
|
|
436
546
|
try {
|
|
437
547
|
response = await chat(messages, {
|
|
438
548
|
base: endpoint.base,
|
|
439
549
|
model: endpoint.model,
|
|
550
|
+
token: endpoint.token,
|
|
551
|
+
transport: endpoint.transport,
|
|
440
552
|
maxTokens,
|
|
441
553
|
temperature: opts.temperature,
|
|
442
554
|
tools: opts.toolSchemas,
|
|
443
|
-
thinking: opts.thinking,
|
|
555
|
+
thinking: (truncatedThisTurn || thinkLatched) ? false : opts.thinking, // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
|
|
444
556
|
signal: opts.signal,
|
|
445
557
|
background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
|
|
446
558
|
onDelta: opts.onDelta,
|
|
@@ -481,6 +593,12 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
481
593
|
// that still truncate, surface it honestly rather than loop. The failed round added nothing to the
|
|
482
594
|
// conversation (chat() threw before streaming), so a bare user-role nudge is safe here (no leak).
|
|
483
595
|
if (recovery === "truncated_tool_call") {
|
|
596
|
+
// Task #14 (second truncation path): the SERVER rejected a malformed/truncated tool call (not a
|
|
597
|
+
// local stopReason "length"). Same root cause — reasoning ate the per-round budget so the multi-line
|
|
598
|
+
// tool-call JSON came through cut off — so latch reasoning OFF for the retry rounds. Without this the
|
|
599
|
+
// nudge-and-retry below re-ran with /think still on and re-truncated until the hand-back (the exact
|
|
600
|
+
// mobile failure James hit). Mirrors the length-path latch; sticky for the turn, resets next turn.
|
|
601
|
+
truncatedThisTurn = true;
|
|
484
602
|
if (truncRetries >= MAX_TRUNC_RETRIES) {
|
|
485
603
|
// Enterprise-grade: NEVER leave the user frozen re-hitting the same malformed-tool-call 500.
|
|
486
604
|
// Once the nudges are spent, end the turn with a clean, actionable message (not a raw 500 throw)
|
|
@@ -564,6 +682,44 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
564
682
|
continue;
|
|
565
683
|
}
|
|
566
684
|
}
|
|
685
|
+
// Unrestricted mode (engine/unrestricted.ts, owner's private system): this round's `response` just came
|
|
686
|
+
// back clean (no self-heal error) — if it has no tool calls AND its text/stopReason reads as a
|
|
687
|
+
// POLICY/MORAL refusal (not a capability limit), re-issue the SAME request with an affirmative-prefill
|
|
688
|
+
// reminder appended and use that result in its place. Bounded per round by UNRESTRICTED_MAX_RETRIES so a
|
|
689
|
+
// model that keeps refusing can never loop forever; still refusing after that, `response` just keeps its
|
|
690
|
+
// original (unchanged) content and falls through to the normal round handling below. This never touches
|
|
691
|
+
// a tool-permission denial or the deniedReadAsync credential-path guard (tools/registry.ts) — those
|
|
692
|
+
// aren't chat() output, so detectRefusal never sees them; the two hard floors are untouched.
|
|
693
|
+
if (unrestrictedEnabled) {
|
|
694
|
+
let unrestrictedRetries = 0;
|
|
695
|
+
while (unrestrictedRetries < UNRESTRICTED_MAX_RETRIES &&
|
|
696
|
+
response.toolCalls.length === 0 &&
|
|
697
|
+
detectRefusal(response.content, response.stopReason)) {
|
|
698
|
+
unrestrictedRetries += 1;
|
|
699
|
+
opts.onSelfHeal?.("server_error", unrestrictedRetries); // footer ↻ — same self-heal signal other recovery paths use
|
|
700
|
+
const retryMessages = buildAffirmativeRetry(buildMessages(opts.systemPrompt, conversation.all));
|
|
701
|
+
response = await chat(retryMessages, {
|
|
702
|
+
base: endpoint.base,
|
|
703
|
+
model: endpoint.model,
|
|
704
|
+
token: endpoint.token,
|
|
705
|
+
transport: endpoint.transport,
|
|
706
|
+
maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
|
|
707
|
+
temperature: opts.temperature,
|
|
708
|
+
tools: opts.toolSchemas,
|
|
709
|
+
thinking: (truncatedThisTurn || thinkLatched) ? false : opts.thinking, // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
|
|
710
|
+
signal: opts.signal,
|
|
711
|
+
background: opts.background,
|
|
712
|
+
onDelta: opts.onDelta,
|
|
713
|
+
onReasoning: opts.onReasoning,
|
|
714
|
+
});
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
// Task #14: latch the think-off recovery the moment any round this turn is cut off by the output limit.
|
|
718
|
+
// Set here, after the response is settled for the round, so the NEXT round (the truncated-tool-call retry
|
|
719
|
+
// at the top, or the length-continue below) re-runs with reasoning off and fits. Covers both truncation
|
|
720
|
+
// paths — a cut-off tool call and a cut-off text answer both carry stopReason "length".
|
|
721
|
+
if (response.stopReason === "length")
|
|
722
|
+
truncatedThisTurn = true;
|
|
567
723
|
// Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
|
|
568
724
|
// actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
|
|
569
725
|
// round (prose + the calls it drives), NOT the prose alone: a model doing DIFFERENT work each round
|
|
@@ -628,6 +784,32 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
628
784
|
}
|
|
629
785
|
}
|
|
630
786
|
}
|
|
787
|
+
// Think-spiral latch (THINK_SPIRAL_* above): with /think ON, a reasoning model can burn round after
|
|
788
|
+
// round in heavy reasoning that keeps acting (a poll/read tool) but never edits a file or answers —
|
|
789
|
+
// invisible to the content guards, since the churn is in the reasoning channel and its wording varies
|
|
790
|
+
// enough to dodge the prose fingerprint. Only count rounds that keep ACTING (tool calls) and are NOT
|
|
791
|
+
// fixing (no file edit) and are reasoning HEAVILY — a round that answers or edits never counts. After
|
|
792
|
+
// THINK_SPIRAL_ROUNDS, latch native thinking OFF for the rest of the turn and push the model to act or
|
|
793
|
+
// answer. Reversible (per-turn), never a hard stop.
|
|
794
|
+
if (opts.thinking && !thinkLatched) {
|
|
795
|
+
const heavyReasoning = (response.reasoningContent?.length ?? 0) >= THINK_SPIRAL_MIN_REASON_CHARS;
|
|
796
|
+
const mutating = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
|
|
797
|
+
if (response.toolCalls.length > 0 && !mutating && heavyReasoning) {
|
|
798
|
+
thinkSpiralStreak += 1;
|
|
799
|
+
if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
|
|
800
|
+
thinkLatched = true;
|
|
801
|
+
opts.onSelfHeal?.("server_error", thinkSpiralStreak); // footer ↻ — breaking a reasoning spiral
|
|
802
|
+
conversation.user(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
|
|
803
|
+
`changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
|
|
804
|
+
`concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
|
|
805
|
+
`concisely. Extended thinking is now off for the rest of this turn.`);
|
|
806
|
+
continue; // re-prompt with thinking disabled; don't dispatch this spiral round's calls
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
else {
|
|
810
|
+
thinkSpiralStreak = 0; // a file edit, an answer, or a light-reasoning round broke the spiral
|
|
811
|
+
}
|
|
812
|
+
}
|
|
631
813
|
// Stuck-turn guard (SELF_LOOP_* above): the model's own admission it's looping is the one signal the
|
|
632
814
|
// signature guards miss. Only counts when the model wants to keep ACTING (has tool calls) and is NOT
|
|
633
815
|
// fixing (no file edit this round) — so a final answer that merely mentions "a different approach", and a
|
|
@@ -658,7 +840,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
658
840
|
conversation.assistant(response.content, response.toolCalls);
|
|
659
841
|
// Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
|
|
660
842
|
// the abandoned tool runs to its own timeout, but the turn is never wedged.
|
|
661
|
-
const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch,
|
|
843
|
+
const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
|
|
662
844
|
for (const tm of toolMsgs)
|
|
663
845
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
664
846
|
observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
@@ -667,6 +849,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
667
849
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
668
850
|
noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
669
851
|
trackTouchedFiles(response.toolCalls, touchedFiles);
|
|
852
|
+
if (stalledNotConverging(response.toolCalls, toolMsgs, response.content))
|
|
853
|
+
return stopTurn(notConvergingNote(response.toolCalls), rounds + 1);
|
|
670
854
|
continue;
|
|
671
855
|
}
|
|
672
856
|
// No structured tool_calls — check for text-encoded ones before treating this as final.
|
|
@@ -674,7 +858,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
674
858
|
if (recovered.calls.length > 0) {
|
|
675
859
|
throwIfAborted(opts.signal);
|
|
676
860
|
conversation.assistant(recovered.cleanedContent, recovered.calls);
|
|
677
|
-
const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch,
|
|
861
|
+
const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
|
|
678
862
|
for (const tm of toolMsgs)
|
|
679
863
|
conversation.tool(tm.tool_call_id, tm.content);
|
|
680
864
|
observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
|
|
@@ -683,6 +867,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
683
867
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
684
868
|
noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
685
869
|
trackTouchedFiles(recovered.calls, touchedFiles);
|
|
870
|
+
if (stalledNotConverging(recovered.calls, toolMsgs, recovered.cleanedContent))
|
|
871
|
+
return stopTurn(notConvergingNote(recovered.calls), rounds + 1);
|
|
686
872
|
continue;
|
|
687
873
|
}
|
|
688
874
|
const final = stripScratchpad(recovered.cleanedContent);
|
|
@@ -708,6 +894,30 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
708
894
|
continue;
|
|
709
895
|
}
|
|
710
896
|
}
|
|
897
|
+
// Turn-continuation: a text-only round whose tail is an unperformed action announcement ("Let me implement
|
|
898
|
+
// these now.") is NOT a finished turn — finalizing here would leave the work undone and make the owner type
|
|
899
|
+
// "continue". Record the model's text, nudge it (user role — real content + tool context exist, so it is
|
|
900
|
+
// answered as the instruction it is) to actually call the tool(s), and keep going. Bounded per turn
|
|
901
|
+
// (continuationMax) so it can never force an unbounded turn; the converge guard stops circling. A truncated
|
|
902
|
+
// reply ("length") has an unreliable tail, so it is left to the normal finalize path.
|
|
903
|
+
// Spectre-parity fix (b), verified by nova's loop trace + live screenshot: a round CUT OFF by the
|
|
904
|
+
// output limit that still produced non-empty text was finalizing the turn — the model was mid-work,
|
|
905
|
+
// the owner saw it stop halfway, and think-mode models hit this most (long reasoning eats the budget).
|
|
906
|
+
// Keep the partial artifact, demand an exact continuation, bounded (3/turn) so a pathological model
|
|
907
|
+
// cannot loiter on the tail. Deliberately NOT gated on continuationEnabled: long-form generations
|
|
908
|
+
// without tools need this just as badly. The announce-nudge below already excludes length rounds.
|
|
909
|
+
if (response.stopReason === "length" && final && final.trim().length > 0 && truncationContinues < TRUNCATION_CONTINUE_MAX) {
|
|
910
|
+
truncationContinues++;
|
|
911
|
+
conversation.assistant(final);
|
|
912
|
+
conversation.user("Your output hit the token limit and was CUT OFF mid-stream. Continue EXACTLY from where you stopped — no preamble, no re-analysis. If you were emitting a tool call, re-emit it complete and keep arguments short: for long scripts, file_write the script then bash the file.");
|
|
913
|
+
continue;
|
|
914
|
+
}
|
|
915
|
+
if (continuationEnabled && final && response.stopReason !== "length" && announceNudges < continuationMax && detectUnfinishedAction(final)) {
|
|
916
|
+
announceNudges++;
|
|
917
|
+
conversation.assistant(final);
|
|
918
|
+
conversation.user(ANNOUNCE_NUDGE);
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
711
921
|
// Verify-before-done gate: the model is finalizing (no more tool calls). If this turn CHANGED files
|
|
712
922
|
// but no passing check was observed, inject ONE reminder to run it and give the model another round.
|
|
713
923
|
// Record `final` as the model's own done-claim first, then a user-role reminder — the "user-role leak"
|
package/dist/engine/aurora.js
CHANGED
|
@@ -61,14 +61,42 @@ export function endpointGateStatus() {
|
|
|
61
61
|
function isRemoteBase(base) {
|
|
62
62
|
return !/^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(base);
|
|
63
63
|
}
|
|
64
|
+
// Owner-trusted fallback scope for the OPERATOR bearer: AXE's own hosts (api.axe.onl gateway) and
|
|
65
|
+
// private/LAN fleet nodes. A third-party BYO host (qwencloudapi.com, …) must NEVER receive the operator
|
|
66
|
+
// token — a BYO profile carries its own vendor key via Endpoint.token (AuroraOpts.token), and an
|
|
67
|
+
// endpoint with no explicit token gets NO auth on a public third-party host. This scope rule is the
|
|
68
|
+
// credential-leak guard for the BYO era.
|
|
69
|
+
function hostOf(base) {
|
|
70
|
+
try {
|
|
71
|
+
return new URL(base).hostname.toLowerCase();
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return "";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/** True when `base` is an AXE gateway host that fronts the model with operator-bearer auth (…axe.onl). LAN and
|
|
78
|
+
* loopback fleet nodes are trusted but unauthenticated, so they never need a signed-in identity. */
|
|
79
|
+
export function requiresOperatorToken(base) {
|
|
80
|
+
const h = hostOf(base ?? "");
|
|
81
|
+
return h === "axe.onl" || h.endsWith(".axe.onl");
|
|
82
|
+
}
|
|
83
|
+
function isOperatorTrustedHost(h) {
|
|
84
|
+
if (!h)
|
|
85
|
+
return false;
|
|
86
|
+
if (h === "axe.onl" || h.endsWith(".axe.onl"))
|
|
87
|
+
return true;
|
|
88
|
+
return /^(10\.|192\.168\.|127\.|localhost$|\[::1\]$)|^172\.(1[6-9]|2\d|3[01])\./.test(h) || h.endsWith(".local");
|
|
89
|
+
}
|
|
64
90
|
// One operator identity per process. The node CLI sets this at boot from the keychain
|
|
65
91
|
// (setOperatorToken); browser/JSCore hosts inject per-call via AuroraOpts.token or not at all.
|
|
66
92
|
// A local :8097 never receives it (isRemoteBase gate), so it is safe to set unconditionally.
|
|
67
93
|
let _operatorToken;
|
|
68
94
|
export function setOperatorToken(token) { _operatorToken = token || undefined; }
|
|
69
|
-
function authHeaders(o) {
|
|
70
|
-
|
|
71
|
-
|
|
95
|
+
export function authHeaders(o) {
|
|
96
|
+
if (!isRemoteBase(o.base))
|
|
97
|
+
return {}; // a local server never gets any bearer — vendor or operator
|
|
98
|
+
const token = o.token ?? (isOperatorTrustedHost(hostOf(o.base)) ? _operatorToken : undefined);
|
|
99
|
+
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
72
100
|
}
|
|
73
101
|
// ---------------------------------------------------------------------------
|
|
74
102
|
// Decode-time degeneration guard (SPEC §1). This is NOT a sampling penalty — it changes no
|
|
@@ -82,8 +110,8 @@ const LOOP_MIN_LINE_LEN = 12; // ignore short/structural lines (braces, bullets,
|
|
|
82
110
|
const LOOP_LINE_REPEATS = 6; // same substantial line seen this many times => degenerate
|
|
83
111
|
const LOOP_TAIL = 260; // chars of tail scanned for a back-to-back repeating cycle
|
|
84
112
|
const LOOP_CHECK_EVERY = 200; // only run the scan every ~N new chars (cheap amortization)
|
|
85
|
-
const RUNAWAY_CHARS =
|
|
86
|
-
//
|
|
113
|
+
const RUNAWAY_CHARS = 120_000; // a round is capped at max_tokens (~8k => ~33k chars); far past that is a
|
|
114
|
+
// decode loop or a stream/render duplication, never a real answer — hard stop.
|
|
87
115
|
function hasAlpha(s) {
|
|
88
116
|
return /[a-zA-Z]/.test(s);
|
|
89
117
|
}
|
|
@@ -165,33 +193,38 @@ export function trimLoop(text) {
|
|
|
165
193
|
return out.join("\n").trim();
|
|
166
194
|
}
|
|
167
195
|
function requestBody(messages, o, stream) {
|
|
196
|
+
// Transport dialect: llama.cpp-only fields ship ONLY to Aurora/fleet (default "llama"); a strict
|
|
197
|
+
// "openai" BYO gateway gets standard fields + its documented thinking knob. Third-party gateways
|
|
198
|
+
// can 400 on unknown keys — and silence on extras is not a contract we should bank on.
|
|
199
|
+
const llama = o.transport !== "openai";
|
|
168
200
|
return JSON.stringify({
|
|
169
201
|
model: o.model, messages, stream,
|
|
170
202
|
// Ask the server for an exact usage report on the final SSE chunk. Without this, llama.cpp omits
|
|
171
203
|
// `timings` on rounds that end in tool_calls (verified live), so the token meter under-counts a
|
|
172
204
|
// tool-heavy turn to near-zero and falls back to the chars/4 estimate. include_usage yields exact
|
|
173
|
-
// completion_tokens even on tool-call rounds (parsed via j.usage in streamDeltas).
|
|
205
|
+
// completion_tokens even on tool-call rounds (parsed via j.usage in streamDeltas). STANDARD field —
|
|
206
|
+
// ships on both dialects.
|
|
174
207
|
...(stream ? { stream_options: { include_usage: true } } : {}),
|
|
175
208
|
// Reuse the server-side KV cache across requests (llama.cpp): a coding turn re-sends a GROWING prefix
|
|
176
209
|
// (system + tools + history) every round, and cache-safe compaction re-sends the evicted span as an exact
|
|
177
210
|
// PREFIX of the last live request. Without cache_prompt the single-slot server RE-PREFILLS that whole
|
|
178
211
|
// prefix each time — the "compaction takes 4-5 min at 80k ctx" and "long sessions crawl" symptom. With it,
|
|
179
|
-
// the server prefix-matches and prefills only the new tail.
|
|
180
|
-
cache_prompt: true,
|
|
212
|
+
// the server prefix-matches and prefills only the new tail. llama dialect only.
|
|
213
|
+
...(llama ? { cache_prompt: true } : {}),
|
|
181
214
|
// GW-26 — ngram speculation is DEFAULT-ON in modern llama.cpp and a NET LOSS on the DeltaNet-hybrid
|
|
182
215
|
// Aurora at untuned draft params: measured live on :8097 (b11146, ctx 307K), acceptance 3-17% and
|
|
183
216
|
// 4-6 tok/s decode WITH it vs 20-25 tok/s WITHOUT — every rejected draft forces a multi-token
|
|
184
217
|
// re-verify + recache on the hybrid. Shape verified live: {"speculative":{"ngram":{"enabled":false}}}
|
|
185
218
|
// -> timings.draft_n drops to 0 and decode jumps 4x; a `{"type":"none"}` variant is silently IGNORED,
|
|
186
|
-
// so keep this exact shape.
|
|
187
|
-
//
|
|
188
|
-
...(o.enableSpeculation ? {
|
|
189
|
-
max_tokens: o.maxTokens ??
|
|
219
|
+
// so keep this exact shape. llama dialect only. Escape hatch when a retuned/high-acceptance bless
|
|
220
|
+
// lands: enableSpeculation: true.
|
|
221
|
+
...(llama && !o.enableSpeculation ? { speculative: { ngram: { enabled: false } } } : {}),
|
|
222
|
+
max_tokens: o.maxTokens ?? 8192, temperature: o.temperature ?? 0.7,
|
|
190
223
|
...(o.tools?.length ? { tools: o.tools, tool_choice: "auto", parallel_tool_calls: true } : {}),
|
|
191
224
|
// /think: re-enable the model's native reasoning for THIS request, overriding the server's
|
|
192
225
|
// enable_thinking:false default (set for speed). Verified this per-request override works on the
|
|
193
226
|
// Aurora build; reasoning arrives as reasoning_content and renders dimmed.
|
|
194
|
-
...(o.thinking ? { chat_template_kwargs: { enable_thinking: true } } : {}),
|
|
227
|
+
...(o.thinking ? (llama ? { chat_template_kwargs: { enable_thinking: true } } : { enable_thinking: true }) : {}),
|
|
195
228
|
// NO repeat/presence/frequency penalty knobs — SPEC §1: they break tool-calling.
|
|
196
229
|
});
|
|
197
230
|
}
|
|
@@ -260,10 +293,42 @@ async function* streamDeltas(messages, o) {
|
|
|
260
293
|
const reader = res.body.getReader();
|
|
261
294
|
const dec = new TextDecoder();
|
|
262
295
|
let buf = "";
|
|
296
|
+
// H1 (audit-engine §1, the CRITICAL): llama.cpp wedges — mid-decode a slot can stop emitting
|
|
297
|
+
// bytes FOREVER (observed shape of the 4-min-prompt incidents). No deadline here meant the turn
|
|
298
|
+
// hung esc-only while holding the process-wide endpoint slot: one wedged decode deadlocks every
|
|
299
|
+
// waiter behind it. Idle-gap catches the wedge fast (no bytes for idleMs => transient cancel —
|
|
300
|
+
// undefined status self-classifies as transient through the selfheal policy, so failover/backoff
|
|
301
|
+
// already own recovery); the wall-clock is the paranoia ceiling. KODE_STREAM_IDLE_MS=0 disables.
|
|
302
|
+
const idleMs = Number(process.env.KODE_STREAM_IDLE_MS ?? 90_000);
|
|
303
|
+
const wallMs = Number(process.env.KODE_REQUEST_TIMEOUT_MS ?? 30 * 60_000);
|
|
304
|
+
const startedAt = Date.now();
|
|
305
|
+
let lastByteAt = Date.now();
|
|
263
306
|
// finally: if a consumer breaks early (loop breaker, abort, first-answer), tear the socket down.
|
|
264
307
|
try {
|
|
265
308
|
for (;;) {
|
|
266
|
-
const
|
|
309
|
+
const idleLeft = idleMs > 0 ? idleMs - (Date.now() - lastByteAt) : Infinity;
|
|
310
|
+
const wallLeft = wallMs > 0 ? wallMs - (Date.now() - startedAt) : Infinity;
|
|
311
|
+
const budget = Math.min(idleLeft, wallLeft);
|
|
312
|
+
if (budget <= 0)
|
|
313
|
+
throw new Error("aurora stream stalled — deadline exceeded before read (decode wedged; transient)");
|
|
314
|
+
let timer;
|
|
315
|
+
let raced;
|
|
316
|
+
try {
|
|
317
|
+
raced = await Promise.race([
|
|
318
|
+
reader.read(),
|
|
319
|
+
new Promise((r) => { timer = setTimeout(() => r("timeout"), budget); }),
|
|
320
|
+
]);
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
if (timer)
|
|
324
|
+
clearTimeout(timer);
|
|
325
|
+
}
|
|
326
|
+
if (raced === "timeout") {
|
|
327
|
+
void reader.cancel().catch(() => { });
|
|
328
|
+
throw new Error(`aurora stream stalled — no bytes within ${Math.round(budget / 1000)}s (decode wedged; transient)`);
|
|
329
|
+
}
|
|
330
|
+
const { value, done } = raced;
|
|
331
|
+
lastByteAt = Date.now();
|
|
267
332
|
if (done)
|
|
268
333
|
break;
|
|
269
334
|
buf += dec.decode(value, { stream: true });
|