@0perator/operator 0.1.333 → 0.1.334
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/auth/commands.js +1 -1
- package/dist/cli.js +1 -0
- package/dist/config/persona.js +42 -7
- package/dist/config/settings.js +23 -2
- package/dist/engine/agent.js +57 -4
- package/dist/engine/anthropic-chat.js +4 -4
- package/dist/engine/aurora.js +8 -1
- package/dist/engine/compaction.js +4 -2
- package/dist/engine/decision-points.js +78 -0
- package/dist/engine/moa.js +4 -1
- package/dist/engine/router-adapter.js +2 -0
- package/dist/engine/selfheal.js +41 -0
- package/dist/router/models.js +11 -6
- package/dist/session.js +25 -13
- package/dist/tools/doc-text.js +129 -0
- package/dist/tools/paths.js +13 -1
- package/dist/tools/registry.js +117 -44
- package/dist/tools/vision-gateway.js +55 -0
- package/dist/ui/QuestionPrompt.js +4 -3
- package/package.json +1 -1
package/dist/auth/commands.js
CHANGED
|
@@ -269,7 +269,7 @@ async function byoModel(rest) {
|
|
|
269
269
|
console.error(` presets: ${Object.keys(BYO_PRESETS).join(", ")}`);
|
|
270
270
|
return 1;
|
|
271
271
|
}
|
|
272
|
-
const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect, ...(preset?.chatPath && base === preset.endpoint ? { chatPath: preset.chatPath } : {}) };
|
|
272
|
+
const profile = { id, label: label ?? id, kind: "single", desc: `BYO ${label ?? id} — your key`, endpoint: base, model, ctx, byo: account, transport: dialect, ...(preset?.chatPath && base === preset.endpoint ? { chatPath: preset.chatPath } : {}), ...(preset?.maxOutput && model === preset.model ? { maxOutput: preset.maxOutput } : {}) };
|
|
273
273
|
const existing = loadSettings().models ?? [];
|
|
274
274
|
const models = [...existing.filter((m) => m.id !== id), profile];
|
|
275
275
|
saveSettings({ models });
|
package/dist/cli.js
CHANGED
|
@@ -665,6 +665,7 @@ function Root() {
|
|
|
665
665
|
permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
|
|
666
666
|
approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
|
|
667
667
|
askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
|
|
668
|
+
decisionPoints: settings.decisionPoints, // a build turn's first change waits for the owner's choice (ask_user); false / KODE_DECISION_POINTS=0 = off
|
|
668
669
|
telemetry: settings.telemetry, // local-only metrics by default
|
|
669
670
|
eventSink, eventActor: EVENT_ACTOR, sessionId: SESSION_ID, // frozen event stream (tool/control audit)
|
|
670
671
|
// Foreground only: lets Aurora delegate via spawn_agent. The bg factory below OMITS this, so a
|
package/dist/config/persona.js
CHANGED
|
@@ -9,6 +9,7 @@ import { scratchDirFor } from "./scratch.js";
|
|
|
9
9
|
import { renderHarnessContext } from "./operator-harness.js";
|
|
10
10
|
import { renderToolCatalogue } from "../tools/registry.js";
|
|
11
11
|
import { renderSkillsIndex } from "./skills-index.js";
|
|
12
|
+
import { decisionPointsEnabled } from "../engine/decision-points.js";
|
|
12
13
|
// Project context: auto-load a per-repo instructions file from `cwd` and append it to the system prompt, so
|
|
13
14
|
// Operator picks up house rules, conventions and build commands the way modern coding agents do. First match
|
|
14
15
|
// wins, so the ORDER is the brand precedence: our own `.operator/AGENTS.md`, then the vendor-neutral open
|
|
@@ -170,8 +171,9 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
|
|
|
170
171
|
? `. But not every message is a task, and not every turn needs a tool: when the owner asks a question, or ` +
|
|
171
172
|
`the request is conversational, meta ("what can you do?"), or genuinely under-specified, just ANSWER in ` +
|
|
172
173
|
`prose — or ask ONE short clarifying question — instead of reaching for a tool to avoid answering`
|
|
173
|
-
: ` — bias to doing over asking: when you can do the work and verify it yourself, do it
|
|
174
|
-
`the owner to confirm
|
|
174
|
+
: ` — bias to doing over asking for ROUTINE work: when you can do the work and verify it yourself, do it ` +
|
|
175
|
+
`rather than asking the owner to confirm (the direction of a new build is the exception — see Decision ` +
|
|
176
|
+
`points). Answer a question, or a conversational or meta ("what can you do?") turn, in prose ` +
|
|
175
177
|
`without reaching for a tool`) +
|
|
176
178
|
`. Never call self_status, list a directory, or run any tool merely to fill a turn or to decide what to do ` +
|
|
177
179
|
`next; if you already know the answer, give it. The ONLY floor is fleet integrity — never leak secrets into ` +
|
|
@@ -186,6 +188,7 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
|
|
|
186
188
|
`unfixed — that risks leaving them unfixed forever. Bring back to the user ONLY genuine judgment calls: ` +
|
|
187
189
|
`design decisions, real tradeoffs, or destructive/irreversible actions — never routine fixes. When in ` +
|
|
188
190
|
`doubt on a low-risk fix, make it and note what you did.` +
|
|
191
|
+
decisionPointsSection(opts) +
|
|
189
192
|
`\n## Verify by running before you claim done\nNever report that something works, passes, or is ` +
|
|
190
193
|
`complete on the strength of your own reasoning — RUN it and read the result first. Execute the actual ` +
|
|
191
194
|
`command, CLI, or code path you are claiming works; a task is done only when the check that proves it ` +
|
|
@@ -263,10 +266,10 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
|
|
|
263
266
|
`model you don't have. It also accepts \`reference\`+\`strength\`, passed through to the broker. (b) VIDEO ` +
|
|
264
267
|
`— \`video_generate\` → LTX-Video-0.9.5 on the video broker, with \`expand\` and \`reference_image\` ` +
|
|
265
268
|
`(IMAGE-TO-VIDEO): pass an image and LTX conditions on it as the FIRST FRAME, so the subject in the clip ` +
|
|
266
|
-
`IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` →
|
|
267
|
-
`
|
|
268
|
-
`
|
|
269
|
-
`auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
|
|
269
|
+
`IS that image, in motion. (c) VISION — \`image_analyze\` / \`video_analyze\` → the 0perator gateway's \`vision\` ` +
|
|
270
|
+
`route (REAL vision, not guessing from a filename); the gateway owns failover across the fleet's VL workers. ` +
|
|
271
|
+
`A DOCUMENT (PDF, DOCX, XLSX, PPTX, RTF, HTML) is read as TEXT, every page (also via \`file_read\`) — only a ` +
|
|
272
|
+
`scanned page with no text is rendered for vision. Large images are auto-downscaled before the model sees them. To match a reference, \`image_analyze\` it FIRST, then write ` +
|
|
270
273
|
`your generate prompt from what you actually SAW.` +
|
|
271
274
|
`\n**Likeness is LIVE — this is how you "generate HER".** To make a SPECIFIC person, pass their FACE photo ` +
|
|
272
275
|
`as \`reference\` to \`image_generate\`: it routes to the identity broker (RealVisXL + IP-Adapter-FaceID) ` +
|
|
@@ -430,6 +433,33 @@ export function basePersona(cwd = process.cwd(), opts = {}) {
|
|
|
430
433
|
: ""));
|
|
431
434
|
}
|
|
432
435
|
const LEAN_NOTE = "\n\n(Lean harness: long-term memory + handoff omitted to fit this model's smaller context — answer from the live conversation; do not recite stored notes.)";
|
|
436
|
+
// Decision points (0.1.334): 0 ask_user calls in 96 recorded sessions — the persona only ever said "don't ask",
|
|
437
|
+
// never WHEN options are wanted. Routine fixes still never ask (Fix what you find); the direction of a build does.
|
|
438
|
+
// Interactive sessions have ask_user; a headless run / sub-agent has no approver, so it states its assumption.
|
|
439
|
+
function decisionPointsSection(opts) {
|
|
440
|
+
if (!decisionPointsEnabled(opts.decisionPoints))
|
|
441
|
+
return "";
|
|
442
|
+
if (!opts.interactive) {
|
|
443
|
+
return `\n## Decision points\nNo one is here to choose for you: where a build has genuinely different approaches, ` +
|
|
444
|
+
`pick the most conventional one, state that assumption in one line, and proceed.`;
|
|
445
|
+
}
|
|
446
|
+
if (opts.lean) {
|
|
447
|
+
return `\n## Decision points — give the owner options\nAt the START of a new build, feature or refactor, or when ` +
|
|
448
|
+
`there are 2+ genuinely different approaches or an irreversible step: before your first change, give a short ` +
|
|
449
|
+
`plan and call ask_user with 2-4 options, the recommended one FIRST marked "(recommended)". Then do what they ` +
|
|
450
|
+
`chose. Routine fixes, small edits, questions and checks: never ask.`;
|
|
451
|
+
}
|
|
452
|
+
return `\n## Decision points — give the owner options\nThe owner wants to steer direction, not approve chores. ` +
|
|
453
|
+
`Call ask_user BEFORE your first change when: (1) the request is a new build, feature, integration or refactor ` +
|
|
454
|
+
`spanning several steps or files — reply with a short numbered plan, then ask "Go with this plan ` +
|
|
455
|
+
`(recommended)" / "Adjust scope: …" / "Different approach: …"; (2) there are 2+ genuinely different ` +
|
|
456
|
+
`approaches, scopes or tradeoffs (library A vs B, quick patch vs proper fix); or (3) the next step is ` +
|
|
457
|
+
`destructive or irreversible. Give 2-4 concrete options, the recommended one FIRST labelled "(recommended)", ` +
|
|
458
|
+
`each a short line saying what happens. Read what you need first (read-only), then ask; once the owner ` +
|
|
459
|
+
`answers, proceed with their choice without asking again this turn. Do NOT ask for routine work — a typo, a ` +
|
|
460
|
+
`small clear edit, a rename, a bug you found, running tests, or a question you can answer. In plan mode, the ` +
|
|
461
|
+
`plan you present IS the decision point.`;
|
|
462
|
+
}
|
|
433
463
|
// Embodiment guidance, appended only to an interactive session with computer control on. It steers the
|
|
434
464
|
// model to READ the screen with chauffeur's textual accessibility tree instead of hand-rolling osascript —
|
|
435
465
|
// the exact loop that failed on Slack (AppleScript can't read Electron UIs). `chauffeurReady` = chauffeur is
|
|
@@ -472,7 +502,12 @@ export function composeSystemPrompt(o) {
|
|
|
472
502
|
const cwd = o.cwd ?? process.cwd();
|
|
473
503
|
const lean = o.lean === true;
|
|
474
504
|
const interactive = o.interactive === true;
|
|
475
|
-
const
|
|
505
|
+
const custom = o.settings.systemPrompt ?? loadSoul();
|
|
506
|
+
// A SOUL.md / settings.systemPrompt REPLACES basePersona (JL2 runs one), so the decision-points rule — harness
|
|
507
|
+
// behavior, not identity — is appended to it here; basePersona already carries it inline.
|
|
508
|
+
const identity = custom
|
|
509
|
+
? custom + decisionPointsSection({ interactive, lean, decisionPoints: o.settings.decisionPoints })
|
|
510
|
+
: basePersona(cwd, { ctxTokens: o.ctxTokens, interactive, lean, decisionPoints: o.settings.decisionPoints });
|
|
476
511
|
// Local-skills index (name: trigger, 4k cap) — the model must KNOW skills exist without spending a
|
|
477
512
|
// skill_list call; bodies stay pull-on-demand via skill_fetch. Skipped in lean (small-ctx) mode like
|
|
478
513
|
// the other heavy sections. Appended exactly like renderToolCatalogue, right before it.
|
package/dist/config/settings.js
CHANGED
|
@@ -7,7 +7,7 @@ import { totalmem } from "node:os";
|
|
|
7
7
|
import { dirname } from "node:path";
|
|
8
8
|
import { operatorPath } from "./home.js";
|
|
9
9
|
import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
|
|
10
|
-
import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID } from "../router/models.js";
|
|
10
|
+
import { MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, GATEWAY_BASE } from "../router/models.js";
|
|
11
11
|
import { LEGACY_API_HOST, PRODUCT_API_HOST } from "./product-hosts.js";
|
|
12
12
|
/** Resolve an endpoint's bearer from config/env/secret-file (first hit wins); undefined when none set
|
|
13
13
|
* (a local/un-gated endpoint). Keeps the raw key out of settings when `apiKeyEnv`/`apiKeyFile` are used. */
|
|
@@ -75,6 +75,15 @@ const DEFAULTS = {
|
|
|
75
75
|
vision: { autostart: false, launchdLabel: "co.0perator.vision", plistPath: "~/Library/LaunchAgents/co.0perator.vision.plist", legacyLabels: ["axe.vision-bot"], url: "http://127.0.0.1:7788", remoteUrl: "http://192.168.1.103:8095" },
|
|
76
76
|
stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
|
|
77
77
|
},
|
|
78
|
+
// MOA (2026-10-28, James): Dolphin 7B + Cortana propose, Cortana aggregates — both on JL1, reached through the
|
|
79
|
+
// 0perator gateway so every signed-in Operator has the same team. settings.moa replaces it wholesale.
|
|
80
|
+
moa: {
|
|
81
|
+
proposers: [
|
|
82
|
+
{ id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
|
|
83
|
+
{ id: "dolphin-7b", endpoint: GATEWAY_BASE, model: "dolphin-7b" },
|
|
84
|
+
],
|
|
85
|
+
aggregator: { id: "cortana", endpoint: GATEWAY_BASE, model: "cortana" },
|
|
86
|
+
},
|
|
78
87
|
activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
|
|
79
88
|
// Autonomy: everything conservative. keepAwake off; dream OFF and read-mostly with a board-only
|
|
80
89
|
// allowlist. An interactive owner never touches any of this until they run an autonomy subcommand.
|
|
@@ -194,6 +203,16 @@ function applyEnv(s) {
|
|
|
194
203
|
vision: { ...out.services.vision, autostart: false },
|
|
195
204
|
};
|
|
196
205
|
}
|
|
206
|
+
if (process.env.KODE_VISION_GATEWAY || process.env.KODE_VISION_MODEL) {
|
|
207
|
+
out.services = {
|
|
208
|
+
...out.services,
|
|
209
|
+
vision: {
|
|
210
|
+
...out.services.vision,
|
|
211
|
+
...(process.env.KODE_VISION_GATEWAY ? { gateway: process.env.KODE_VISION_GATEWAY } : {}),
|
|
212
|
+
...(process.env.KODE_VISION_MODEL ? { model: process.env.KODE_VISION_MODEL } : {}),
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
}
|
|
197
216
|
if (process.env.KODE_STOP_SEARXNG_ON_EXIT === "0") {
|
|
198
217
|
out.services = { ...out.services, stopOnExit: { ...out.services.stopOnExit, searxng: false } };
|
|
199
218
|
}
|
|
@@ -420,7 +439,9 @@ export function loadSettings() {
|
|
|
420
439
|
const flywheelPinned = (isPlainObject(file) && isPlainObject(file.selfImprove) && typeof file.selfImprove.flywheel === "boolean") ||
|
|
421
440
|
process.env.KODE_SELFIMPROVE !== undefined ||
|
|
422
441
|
typeof managed.policy?.selfImprove?.flywheel === "boolean";
|
|
423
|
-
|
|
442
|
+
const fv = isPlainObject(file) && isPlainObject(file.services) && isPlainObject(file.services.vision) ? file.services.vision : undefined;
|
|
443
|
+
const visionUrlPinned = !!fv && (typeof fv.url === "string" || typeof fv.remoteUrl === "string");
|
|
444
|
+
let out = applyManagedPolicy({ ...merged, explicit: { flywheel: flywheelPinned, visionUrl: visionUrlPinned } }, managed);
|
|
424
445
|
if (managed.info.status === "invalid" && !warnedManaged) {
|
|
425
446
|
warnedManaged = true;
|
|
426
447
|
process.stderr.write(`[operator] managed policy ${managed.info.path} is not usable (${managed.info.errors.join("; ")}) — running locked down (read-only) until it is fixed\n`);
|
package/dist/engine/agent.js
CHANGED
|
@@ -8,7 +8,7 @@ import { buildMessages } from "./messages.js";
|
|
|
8
8
|
import { recoverToolCalls, cleanAssistantProse } from "./toolcalls.js";
|
|
9
9
|
import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens, outputRoom, headroomTargetRatio, TOOL_CALL_HEADROOM_TOKENS } from "./compaction.js";
|
|
10
10
|
import { globalTokenMeter, endpointKey, requestChars } from "./token-meter.js";
|
|
11
|
-
import { classifyFailure, servedContextLimit, backoffMs, sleep } from "./selfheal.js";
|
|
11
|
+
import { classifyFailure, servedContextLimit, outputCeilingLimit, learnOutputCeiling, learnedOutputCeiling, backoffMs, sleep } from "./selfheal.js";
|
|
12
12
|
import { TaskVerification, VERIFY_REMINDER, NOT_VERIFIED_BANNER } from "./verify-gate.js";
|
|
13
13
|
import { detectRefusal, buildAffirmativeRetry, UNRESTRICTED_MAX_RETRIES } from "./unrestricted.js";
|
|
14
14
|
import { ComputerEventStream, ComputerEventTracker } from "./computer-event.js";
|
|
@@ -25,6 +25,7 @@ const LOOP_GUARD_LIMIT = 5; // identical (name+args) calls in a turn before shor
|
|
|
25
25
|
// file is verify-after-fix iteration, not a spin, so it must be unbounded. Only a genuinely repeated call
|
|
26
26
|
// with NO intervening edit (a true no-progress loop) trips this. Raised 3→5 so even a no-edit re-run has
|
|
27
27
|
// headroom before the guard fires. The narration/no-progress stalls below are the separate progress-gated stops.
|
|
28
|
+
import { DECISION_POINT_NUDGE, isBuildRequest, shouldHoldForDecision } from "./decision-points.js";
|
|
28
29
|
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
|
|
29
30
|
import { ANNOUNCE_NUDGE, ANNOUNCE_NUDGE_MAX, DELEGATION_NUDGE, detectAnnouncedDelegation, detectUnfinishedAction, engineNote, detectSelfDialogue, SELF_DIALOGUE_NUDGE, SELF_DIALOGUE_NUDGE_MAX, needsClosingSteer, CLOSING_NUDGE, CLOSING_NUDGE_UNATTENDED, EMPTY_REPLY_NUDGE, emptyReplyStatus, closeStopNote, stripEngineEcho, isEngineFinal } from "./continuation.js";
|
|
30
31
|
// Poll/status tools are meant to be called repeatedly while waiting on async work — NEVER a spin, so the
|
|
@@ -139,6 +140,14 @@ const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated
|
|
|
139
140
|
// standing directive. A user role (not a 2nd system message, which 400s the endpoint — SPEC §1).
|
|
140
141
|
const TRUNC_POS_RE = /at (?:column|position) (\d+)/i;
|
|
141
142
|
const TRUNC_LARGE_BODY_CHARS = 300; // past this, "cut off at column/position N" means a big body, not a quoted command
|
|
143
|
+
/** The endpoint's output ceiling: the tighter of its profile's maxOutput and any ceiling a vendor 400 stated this
|
|
144
|
+
* process (selfheal.learnOutputCeiling). Undefined = no cap — the local llama-server fleet, unknown vendors. */
|
|
145
|
+
export function outputCeilingFor(ep) {
|
|
146
|
+
const learned = learnedOutputCeiling(endpointKey(ep.base, ep.model));
|
|
147
|
+
if (ep.maxOutput === undefined)
|
|
148
|
+
return learned;
|
|
149
|
+
return learned === undefined ? ep.maxOutput : Math.min(ep.maxOutput, learned);
|
|
150
|
+
}
|
|
142
151
|
function truncatedToolPos(message) {
|
|
143
152
|
const m = TRUNC_POS_RE.exec(message);
|
|
144
153
|
return m ? Number(m[1]) : undefined;
|
|
@@ -590,6 +599,11 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
590
599
|
let selfDialogueNudges = 0; // owner-facing: replies that react to a speaker who did not speak (continuation.ts)
|
|
591
600
|
let closingNudged = false; // owner-facing: one nudge to close with status + a steering question instead of a bare stop
|
|
592
601
|
let lastReasoning = ""; // the reasoning channel of an empty round — a model that answers there still answered
|
|
602
|
+
const hasAskTool = (opts.toolSchemas ?? []).some((s) => s?.function?.name === "ask_user");
|
|
603
|
+
const decisionGate = opts.decisionPoints?.enabled === true && hasAskTool;
|
|
604
|
+
const buildTurn = decisionGate && isBuildRequest(userInput);
|
|
605
|
+
let askedThisTurn = false; // ask_user ran this turn — the owner already chose a direction
|
|
606
|
+
let decisionNudged = false; // the decision-point hold fires at most once per turn
|
|
593
607
|
let repliesSinceOwner = 0; // non-empty model replies since the owner last spoke (turn start, or an ask_user answer) — the first is never self-dialogue
|
|
594
608
|
let emptyNudged = false; // the reframe nudge goes in on the FIRST genuine empty, whatever the retry counter says
|
|
595
609
|
let malformedCallNudges = 0; // bounded re-prompts for an unparseable text tool call
|
|
@@ -707,6 +721,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
707
721
|
// failover below can swap endpoints mid-round and each has its own ctx_window.
|
|
708
722
|
const compactionOptsFor = (ep) => ({
|
|
709
723
|
ctxWindow: ep.ctxWindow,
|
|
724
|
+
outputCeiling: outputCeilingFor(ep),
|
|
710
725
|
systemPrompt: opts.systemPrompt,
|
|
711
726
|
tools: opts.toolSchemas,
|
|
712
727
|
summarize: opts.summarize,
|
|
@@ -720,6 +735,7 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
720
735
|
});
|
|
721
736
|
let response;
|
|
722
737
|
let lastMaxTokens; // the clamp actually sent this round — black-box evidence
|
|
738
|
+
let ceilingRetried = false; // one output-ceiling retry per round — never a loop
|
|
723
739
|
for (;;) {
|
|
724
740
|
// Harness-layer compaction gate — the single choke point every request passes through, on the
|
|
725
741
|
// INITIAL attempt AND after any self-heal failover/route switch below (which `continue`s back
|
|
@@ -775,6 +791,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
775
791
|
response = await chat(messages, {
|
|
776
792
|
base: endpoint.base,
|
|
777
793
|
model: endpoint.model,
|
|
794
|
+
label: endpoint.label,
|
|
795
|
+
provider: endpoint.provider,
|
|
778
796
|
token: endpoint.token,
|
|
779
797
|
loopbackAuth: endpoint.loopbackAuth,
|
|
780
798
|
transport: endpoint.transport,
|
|
@@ -871,6 +889,19 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
871
889
|
await sleep(opts.loadingBackoffMs ?? DEFAULT_LOADING_BACKOFF_MS, opts.signal, () => new TurnAbortedError());
|
|
872
890
|
continue;
|
|
873
891
|
}
|
|
892
|
+
// The vendor's 400 stated its OUTPUT ceiling (max_tokens over what it accepts — QwenCloud's "Range of
|
|
893
|
+
// max_tokens should be [1, 131072]"): learn it for this endpoint, so every later clamp honours it, and
|
|
894
|
+
// retry this round ONCE. Not a context problem (compaction/failover can't help) and no self-heal
|
|
895
|
+
// budget spent. A ceiling no lower than what we sent, or a second hit this round, is surfaced as-is.
|
|
896
|
+
if (recovery === "output_ceiling") {
|
|
897
|
+
const cap = outputCeilingLimit(err);
|
|
898
|
+
if (ceilingRetried || cap === undefined || (lastMaxTokens !== undefined && cap >= lastMaxTokens))
|
|
899
|
+
throw err;
|
|
900
|
+
ceilingRetried = true;
|
|
901
|
+
learnOutputCeiling(endpointKey(endpoint.base, endpoint.model), cap);
|
|
902
|
+
opts.onSelfHeal?.("server_error", 1); // footer ↻ — a recovery is in flight
|
|
903
|
+
continue;
|
|
904
|
+
}
|
|
874
905
|
// Non-retryable: a malformed request (a bad tool call) or bad credentials won't be fixed by
|
|
875
906
|
// resending — fail fast rather than spin (that futile-retry storm is what burned minutes).
|
|
876
907
|
if (recovery === "bad_request" || recovery === "auth" || selfHealBudget <= 0)
|
|
@@ -945,6 +976,8 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
945
976
|
response = await chat(retryMessages, {
|
|
946
977
|
base: endpoint.base,
|
|
947
978
|
model: endpoint.model,
|
|
979
|
+
label: endpoint.label,
|
|
980
|
+
provider: endpoint.provider,
|
|
948
981
|
token: endpoint.token,
|
|
949
982
|
loopbackAuth: endpoint.loopbackAuth,
|
|
950
983
|
transport: endpoint.transport,
|
|
@@ -1134,6 +1167,15 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1134
1167
|
}
|
|
1135
1168
|
selfLoopStreak = 0; // a round that fixes, doesn't act, or doesn't admit looping clears the streak
|
|
1136
1169
|
}
|
|
1170
|
+
// Decision points: a build turn's first change, with no direction chosen yet, is held back once so the owner
|
|
1171
|
+
// gets a plan + options (ask_user) instead of a silently picked approach. This round's calls are not dispatched.
|
|
1172
|
+
if (response.toolCalls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: response.toolCalls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
|
|
1173
|
+
decisionNudged = true;
|
|
1174
|
+
if (response.content.trim())
|
|
1175
|
+
conversation.assistant(cleanAssistantProse(response.content));
|
|
1176
|
+
engineUser(DECISION_POINT_NUDGE);
|
|
1177
|
+
continue;
|
|
1178
|
+
}
|
|
1137
1179
|
if (response.toolCalls.length > 0) {
|
|
1138
1180
|
throwIfAborted(opts.signal); // don't dispatch a tool batch for a turn the user already cancelled
|
|
1139
1181
|
// Strip any leaked tool-call/thinking delimiter tags the model emitted into content ALONGSIDE the
|
|
@@ -1158,8 +1200,10 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1158
1200
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1159
1201
|
noEditStreak = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
1160
1202
|
trackTouchedFiles(response.toolCalls, touchedFiles);
|
|
1161
|
-
if (response.toolCalls.some((c) => c.function?.name === "ask_user"))
|
|
1162
|
-
repliesSinceOwner = -1;
|
|
1203
|
+
if (response.toolCalls.some((c) => c.function?.name === "ask_user")) {
|
|
1204
|
+
repliesSinceOwner = -1;
|
|
1205
|
+
askedThisTurn = true;
|
|
1206
|
+
} // the answer lands as a tool result: the next reply answers the OWNER
|
|
1163
1207
|
// Owner-facing: narration that answers a speaker who did not speak ("You're right — …" to an engine note) is
|
|
1164
1208
|
// redirected into a status for the owner. The round's calls already ran; the note rides into the next round.
|
|
1165
1209
|
if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(response.content, repliesSinceOwner)) {
|
|
@@ -1224,6 +1268,13 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1224
1268
|
if (fromReasoning.calls.length > 0)
|
|
1225
1269
|
recovered = { ...recovered, calls: fromReasoning.calls };
|
|
1226
1270
|
}
|
|
1271
|
+
if (recovered.calls.length > 0 && shouldHoldForDecision({ enabled: decisionGate, buildTurn, askedThisTurn, nudged: decisionNudged, calls: recovered.calls.map((c) => ({ name: c.function?.name, args: c.function?.arguments })) })) {
|
|
1272
|
+
decisionNudged = true;
|
|
1273
|
+
if (recovered.cleanedContent.trim())
|
|
1274
|
+
conversation.assistant(recovered.cleanedContent);
|
|
1275
|
+
engineUser(DECISION_POINT_NUDGE);
|
|
1276
|
+
continue;
|
|
1277
|
+
}
|
|
1227
1278
|
if (recovered.calls.length > 0) {
|
|
1228
1279
|
throwIfAborted(opts.signal);
|
|
1229
1280
|
conversation.assistant(recovered.cleanedContent, recovered.calls);
|
|
@@ -1238,8 +1289,10 @@ export async function runTurn(userInput, conversation, opts) {
|
|
|
1238
1289
|
noProgressStreak = progressed ? 0 : noProgressStreak + 1; // reset the stall counter on any real progress
|
|
1239
1290
|
noEditStreak = recovered.calls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? "")) ? 0 : noEditStreak + 1;
|
|
1240
1291
|
trackTouchedFiles(recovered.calls, touchedFiles);
|
|
1241
|
-
if (recovered.calls.some((c) => c.function?.name === "ask_user"))
|
|
1292
|
+
if (recovered.calls.some((c) => c.function?.name === "ask_user")) {
|
|
1242
1293
|
repliesSinceOwner = -1;
|
|
1294
|
+
askedThisTurn = true;
|
|
1295
|
+
}
|
|
1243
1296
|
if (selfDialogueNudges < SELF_DIALOGUE_NUDGE_MAX && detectSelfDialogue(recovered.cleanedContent, repliesSinceOwner)) {
|
|
1244
1297
|
selfDialogueNudges++;
|
|
1245
1298
|
engineUser(SELF_DIALOGUE_NUDGE);
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop } from "./aurora.js";
|
|
1
|
+
import { acquireEndpoint, releaseEndpoint, isDegenerate, trimLoop, httpErrorLabel } from "./aurora.js";
|
|
2
2
|
import { anthropicKey } from "./anthropic.js";
|
|
3
3
|
import { classifyFailure, backoffMs, sleep } from "./selfheal.js";
|
|
4
|
+
import { ANTHROPIC_MAX_OUTPUT } from "../router/models.js"; // the same ceiling the Claude rows' maxOutput carries — the wire keeps it for callers that skip the turn-loop clamp
|
|
4
5
|
const ANTHROPIC_VERSION = "2023-06-01";
|
|
5
|
-
const MAX_OUTPUT_TOKENS = 128_000; // the vendor's output ceiling for the current Claude family — a larger max_tokens is a 400
|
|
6
6
|
const FETCH_TRIES = 3; // same pre-response transient retry budget as aurora.fetchChat (no bytes streamed yet → safe)
|
|
7
7
|
/** OpenAI tool-call `arguments` is a JSON STRING; Anthropic `input` is an OBJECT. Parse defensively — a
|
|
8
8
|
* malformed/empty string becomes `{}` (messages.ts already sanitizes history, but a live round may not). */
|
|
@@ -94,7 +94,7 @@ export function anthropicRequestBody(messages, o, stream) {
|
|
|
94
94
|
const tools = toAnthropicTools(o.tools);
|
|
95
95
|
return JSON.stringify({
|
|
96
96
|
model: o.model,
|
|
97
|
-
max_tokens: Math.min(o.maxTokens ?? 8192,
|
|
97
|
+
max_tokens: Math.min(o.maxTokens ?? 8192, ANTHROPIC_MAX_OUTPUT),
|
|
98
98
|
...(system ? { system } : {}),
|
|
99
99
|
messages: amsgs,
|
|
100
100
|
...(tools ? { tools } : {}),
|
|
@@ -167,7 +167,7 @@ async function* anthropicDeltas(messages, o) {
|
|
|
167
167
|
detail = (await res.text()).slice(0, 500);
|
|
168
168
|
}
|
|
169
169
|
catch { /* body consumed / unreadable */ }
|
|
170
|
-
const err = new Error(
|
|
170
|
+
const err = new Error(`${o.label ? httpErrorLabel(o) : "anthropic /v1/messages"} ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
171
171
|
err.status = res.status;
|
|
172
172
|
const ra = res.headers.get("retry-after");
|
|
173
173
|
if (ra)
|
package/dist/engine/aurora.js
CHANGED
|
@@ -278,6 +278,13 @@ const FETCH_TRIES = 3; // a transient network drop ("fetch failed") gets a coupl
|
|
|
278
278
|
export function chatUrl(base, chatPath) {
|
|
279
279
|
return `${base}${chatPath ?? "/v1/chat/completions"}`;
|
|
280
280
|
}
|
|
281
|
+
/** Who answered an HTTP error, for the owner: the profile id + provider box when the turn loop passed them
|
|
282
|
+
* ("qwen3.8-flash (QwenCloud)"), else the legacy "aurora /v1" — every OpenAI-dialect call used to read as Aurora. */
|
|
283
|
+
export function httpErrorLabel(o) {
|
|
284
|
+
if (!o.label)
|
|
285
|
+
return "aurora /v1";
|
|
286
|
+
return o.provider ? `${o.label} (${o.provider})` : o.label;
|
|
287
|
+
}
|
|
281
288
|
async function fetchChat(o, body) {
|
|
282
289
|
let lastErr;
|
|
283
290
|
for (let attempt = 0; attempt < FETCH_TRIES; attempt++) {
|
|
@@ -374,7 +381,7 @@ async function* streamDeltas(messages, o) {
|
|
|
374
381
|
catch { /* body already consumed / unreadable */ }
|
|
375
382
|
// Carry the status + body so the self-heal policy can classify WHY (context vs shape vs busy),
|
|
376
383
|
// not just guess from the number. `retryAfterMs` honors a Retry-After header on 429/503.
|
|
377
|
-
const err = new Error(
|
|
384
|
+
const err = new Error(`${httpErrorLabel(o)} ${res.status}${detail ? `: ${detail}` : ""}`);
|
|
378
385
|
err.status = res.status;
|
|
379
386
|
const ra = res.headers.get("retry-after");
|
|
380
387
|
if (ra)
|
|
@@ -141,7 +141,8 @@ export function fitToWindow(conversation, opts, targetRatio) {
|
|
|
141
141
|
}
|
|
142
142
|
return out;
|
|
143
143
|
}
|
|
144
|
-
/** Clamp generation length so prompt + output never exceeds the window
|
|
144
|
+
/** Clamp generation length so prompt + output never exceeds the window, nor the endpoint's output ceiling
|
|
145
|
+
* (opts.outputCeiling — a vendor 400s on a larger max_tokens). A static max_tokens plus a
|
|
145
146
|
* deep-session prompt otherwise gets the model squeezed to a truncated reply (matching the Python
|
|
146
147
|
* core's _predict_budget). `built` already includes the system message, so pass systemPrompt:undefined
|
|
147
148
|
* to avoid double-counting it; tool-schema tokens still come from opts.tools. Floored (≥1024) so a
|
|
@@ -149,7 +150,8 @@ export function fitToWindow(conversation, opts, targetRatio) {
|
|
|
149
150
|
* cut-off call is unparseable (see selfheal's truncated_tool_call). If even the floor won't fit, the
|
|
150
151
|
* prompt is over budget and the caller's compaction handles it. */
|
|
151
152
|
export function clampMaxTokens(built, opts, want, min = 1024) {
|
|
152
|
-
|
|
153
|
+
const clamped = Math.max(min, Math.min(want, outputRoom(built, opts)));
|
|
154
|
+
return opts.outputCeiling && opts.outputCeiling > 0 ? Math.min(clamped, opts.outputCeiling) : clamped;
|
|
153
155
|
}
|
|
154
156
|
/** The generation room a request leaves: window − prompt estimate − the 256-token chat-template/role margin.
|
|
155
157
|
* The SAME basis clampMaxTokens clamps to (factored out so the turn loop's headroom guard and the clamp can
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Decision points (0.1.334): the owner gets a short list of options at the start of a real build instead of the
|
|
2
|
+
// model silently picking a direction. Across 96 recorded sessions the local model called ask_user ZERO times
|
|
3
|
+
// (vs 3,132 bash calls) — the persona told it to bias to doing, and nothing said WHEN options are wanted. The
|
|
4
|
+
// persona + ask_user description now say when; this module is the small engine backstop: on a build-shaped
|
|
5
|
+
// owner turn, the FIRST mutating call before any ask_user is held back once and the model is told to offer a
|
|
6
|
+
// plan + options first. Pure and dependency-free so the gate's trigger logic is unit-testable.
|
|
7
|
+
import { isMutatingTool } from "../tools/mutating.js";
|
|
8
|
+
const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background", "shell_task_start"]);
|
|
9
|
+
// Shell commands that change the workspace or the machine. Read-only probes (ls, cat, grep, git status, a test
|
|
10
|
+
// run) are NOT here — the gate must never hold back investigation, only the first change.
|
|
11
|
+
const MUTATING_SHELL_RE = new RegExp([
|
|
12
|
+
String.raw `(?:^|[;&|]\s*|\s)(?:mkdir|touch|rm|rmdir|mv|cp|ln|chmod|tee|install|truncate)\s`,
|
|
13
|
+
String.raw `\bsed\s+-i`,
|
|
14
|
+
String.raw `\b(?:npm|pnpm|yarn|bun)\s+(?:init|install|i|add|create|remove|uninstall)\b`,
|
|
15
|
+
String.raw `\bnpx\s+(?:create-|degit|tsc\s+--init)`,
|
|
16
|
+
String.raw `\b(?:cargo\s+(?:new|init|add)|pip3?\s+install|uv\s+(?:init|add|pip\s+install)|poetry\s+(?:new|init|add)|go\s+mod\s+init)\b`,
|
|
17
|
+
String.raw `\bgit\s+(?:init|add|commit|checkout|switch|apply|reset|merge|rebase|stash|mv|rm)\b`,
|
|
18
|
+
String.raw `(?:^|[^<>&0-9])>{1,2}\s*(?!&|/dev/null)[^\s>]`,
|
|
19
|
+
].join("|"));
|
|
20
|
+
/** True when a tool call changes the workspace: a file write/edit, a mutating shell command, or a git write. */
|
|
21
|
+
export function isMutatingCall(name, rawArgs) {
|
|
22
|
+
if (isMutatingTool(name))
|
|
23
|
+
return true;
|
|
24
|
+
if (name === "checkpoint")
|
|
25
|
+
return true;
|
|
26
|
+
let args = {};
|
|
27
|
+
try {
|
|
28
|
+
args = JSON.parse(rawArgs || "{}");
|
|
29
|
+
}
|
|
30
|
+
catch { /* partial args: treat as text */ }
|
|
31
|
+
if (name === "git_command") {
|
|
32
|
+
const cmd = String(args.command ?? args.args ?? rawArgs ?? "");
|
|
33
|
+
return !/^\s*(?:git\s+)?(?:status|log|diff|show|branch|remote|rev-parse|blame|ls-files)\b/.test(cmd);
|
|
34
|
+
}
|
|
35
|
+
if (!SHELL_TOOLS.has(name ?? ""))
|
|
36
|
+
return false;
|
|
37
|
+
const cmd = String(args.command ?? args.cmd ?? rawArgs ?? "");
|
|
38
|
+
return MUTATING_SHELL_RE.test(cmd);
|
|
39
|
+
}
|
|
40
|
+
// A build-shaped owner turn: a construction verb aimed at something bigger than a one-line edit. Routine asks
|
|
41
|
+
// ("fix the typo", "what does X do", "run the tests", "rename tmp to result") deliberately do not match.
|
|
42
|
+
const BUILD_VERB_RE = /\b(?:build|create|implement|scaffold|set\s*up|setup|make|write|add|introduce|design|refactor|restructure|rewrite|redesign|migrate|port|convert|overhaul|integrate)\b/i;
|
|
43
|
+
const BUILD_OBJECT_RE = /\b(?:app|application|cli|tool|service|server|api|endpoint|feature|auth\w*|login|sign[- ]?in|oauth|cach\w*|database|db|schema|module|package|library|lib|plugin|extension|dashboard|page|site|website|ui|frontend|backend|pipeline|workflow|system|integration|bot|agent|engine|layer|architecture|structure|framework|tests?|test suite|project|component|support)\b/i;
|
|
44
|
+
const ROUTINE_RE = /\b(?:typo|spelling|whitespace|indent\w*|lint|format(?:ting)?|comment|docstring|rename|bump|version|log line|print)\b/i;
|
|
45
|
+
/** True when the owner's message reads like a multi-step build/feature/refactor request. */
|
|
46
|
+
export function isBuildRequest(text) {
|
|
47
|
+
const t = text.trim();
|
|
48
|
+
if (!t || t.length > 4000)
|
|
49
|
+
return false; // a pasted spec/log is not a fresh build brief to re-scope
|
|
50
|
+
if (/^\s*(?:what|why|how|where|when|who|which|explain|describe|summari[sz]e|show|tell|is|are|does|do|can|could)\b/i.test(t) && /\?\s*$/.test(t))
|
|
51
|
+
return false;
|
|
52
|
+
if (ROUTINE_RE.test(t) && t.length < 160)
|
|
53
|
+
return false;
|
|
54
|
+
return BUILD_VERB_RE.test(t) && BUILD_OBJECT_RE.test(t);
|
|
55
|
+
}
|
|
56
|
+
/** Engine note when the model reached for its first change on a build turn without offering a direction. */
|
|
57
|
+
export const DECISION_POINT_NUDGE = "Before changing anything: this is a multi-step build, and the owner wants to choose its direction. Do NOT make " +
|
|
58
|
+
"the change yet. Reply with a short numbered plan (3-6 steps), then call ask_user with 2-4 concrete options — " +
|
|
59
|
+
"the recommended one FIRST and labelled \"(recommended)\", each a short line saying what happens (e.g. \"Go with " +
|
|
60
|
+
"this plan (recommended)\", \"Smaller scope: …\", \"Different approach: …\"). After the owner answers, proceed " +
|
|
61
|
+
"with their choice without asking again.";
|
|
62
|
+
/** Resolve whether decision points are on: settings.decisionPoints (default true), overridden off by
|
|
63
|
+
* KODE_DECISION_POINTS=0. */
|
|
64
|
+
export function decisionPointsEnabled(setting, env = process.env) {
|
|
65
|
+
if (env.KODE_DECISION_POINTS === "0" || env.KODE_DECISION_POINTS === "false")
|
|
66
|
+
return false;
|
|
67
|
+
if (env.KODE_DECISION_POINTS === "1")
|
|
68
|
+
return true;
|
|
69
|
+
return setting !== false;
|
|
70
|
+
}
|
|
71
|
+
/** The gate's per-turn decision: hold back this round's calls once and nudge, or let them run. */
|
|
72
|
+
export function shouldHoldForDecision(s) {
|
|
73
|
+
if (!s.enabled || !s.buildTurn || s.askedThisTurn || s.nudged)
|
|
74
|
+
return false;
|
|
75
|
+
if (s.calls.some((c) => c.name === "ask_user"))
|
|
76
|
+
return false;
|
|
77
|
+
return s.calls.some((c) => isMutatingCall(c.name, c.args));
|
|
78
|
+
}
|
package/dist/engine/moa.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { authHeaders } from "./aurora.js";
|
|
1
2
|
// Fan-out budget per proposer. 60s default: generous for a draft, hard enough that a contended
|
|
2
3
|
// JL1 slot times out gracefully instead of stalling the aggregator (measured 2026-10-12: same
|
|
3
4
|
// task 1.1s local vs 60s+ timeout on the shared lane). Env-overridable — heavy offline drafts on
|
|
@@ -14,7 +15,9 @@ async function callProposer(p, messages) {
|
|
|
14
15
|
try {
|
|
15
16
|
const res = await fetch(`${p.endpoint.replace(/\/$/, "")}/chat/completions`, {
|
|
16
17
|
method: "POST",
|
|
17
|
-
|
|
18
|
+
// The same bearer scoping as every model call: the signed-in Operator token on the 0perator gateway (proposers
|
|
19
|
+
// default to it), nothing for a local server or a foreign host.
|
|
20
|
+
headers: { "content-type": "application/json", ...authHeaders({ base: p.endpoint, model: p.model }) },
|
|
18
21
|
body: JSON.stringify({ model: p.model, messages, stream: false }),
|
|
19
22
|
signal: ctrl.signal,
|
|
20
23
|
});
|
|
@@ -13,6 +13,8 @@ const toRE = (e, pin) => ({
|
|
|
13
13
|
loopbackAuth: e.loopbackAuth,
|
|
14
14
|
transport: e.transport,
|
|
15
15
|
chatPath: e.chatPath,
|
|
16
|
+
maxOutput: e.maxOutput,
|
|
17
|
+
provider: e.provider,
|
|
16
18
|
});
|
|
17
19
|
function estimateTokens(messages, tools) {
|
|
18
20
|
const chars = JSON.stringify(messages).length + (tools ? JSON.stringify(tools).length : 0);
|
package/dist/engine/selfheal.js
CHANGED
|
@@ -36,6 +36,45 @@ export function servedContextLimit(err) {
|
|
|
36
36
|
const n = Number(m[1] ?? m[2]);
|
|
37
37
|
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
38
38
|
}
|
|
39
|
+
// A 400 whose body states the endpoint's OUTPUT ceiling: the request's max_tokens is larger than the vendor
|
|
40
|
+
// accepts (JL2 2026-10-28, QwenCloud qwen3.8-flash: "Range of max_tokens should be [1, 131072]" while we sent
|
|
41
|
+
// ~220K). Not a context problem — compacting or failing over can't help — so it gets its own class: retry the
|
|
42
|
+
// round ONCE at the stated ceiling and remember it for the endpoint. Each pattern captures the ceiling; they
|
|
43
|
+
// all name max_tokens or output/completion tokens, so a context-length 400 ("maximum context length is N
|
|
44
|
+
// tokens") never reads as one.
|
|
45
|
+
const OUTPUT_CEILING_RES = [
|
|
46
|
+
/max_(?:completion_)?tokens\b[^[\]]{0,60}?\[\s*\d+\s*,\s*(\d+)\s*\]/i, // "Range of max_tokens should be [1, N]" / "valid range of max_tokens is [1, N]"
|
|
47
|
+
/max_(?:completion_)?tokens`?\s*(?:must|should)\s+be\s+(?:<=|less than or equal to|at most|no (?:more|greater|larger) than)\s*`?(\d+)/i, // "max_tokens must be <= N"
|
|
48
|
+
/max_tokens:\s*\d+\s*>\s*(\d+)/i, // Anthropic: "max_tokens: 200000 > 128000, which is the maximum allowed…"
|
|
49
|
+
/supports at most (\d+) (?:completion|output) tokens/i, // OpenAI: "This model supports at most N completion tokens"
|
|
50
|
+
/maximum (?:allowed |supported )?(?:number of )?(?:output|completion|generated|generation) tokens?(?: is| of|:|\s*\()?\s*(\d+)/i, // "the maximum output tokens is N"
|
|
51
|
+
/max_(?:completion_)?tokens\b[^.]{0,60}?\bmaximum(?: allowed| value)?(?: of| is|:)?\s*`?(\d+)/i, // "max_tokens (N') exceeds the maximum of N"
|
|
52
|
+
];
|
|
53
|
+
export function outputCeilingLimit(err) {
|
|
54
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
55
|
+
for (const re of OUTPUT_CEILING_RES) {
|
|
56
|
+
const m = re.exec(msg);
|
|
57
|
+
const n = m ? Number(m[1]) : NaN;
|
|
58
|
+
if (Number.isFinite(n) && n > 0)
|
|
59
|
+
return n;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
// Output ceilings learned from those 400s, keyed by endpointKey(base, model). Process-lifetime (a vendor's
|
|
64
|
+
// ceiling is a fact of the model, not of one turn), so later rounds and turns clamp up front instead of
|
|
65
|
+
// re-hitting the 400. Monotonic down, like AuroraRouter.observeContextLimit.
|
|
66
|
+
const learnedCeilings = new Map();
|
|
67
|
+
export function learnOutputCeiling(key, n) {
|
|
68
|
+
const prev = learnedCeilings.get(key);
|
|
69
|
+
if (n > 0 && (prev === undefined || n < prev))
|
|
70
|
+
learnedCeilings.set(key, n);
|
|
71
|
+
}
|
|
72
|
+
export function learnedOutputCeiling(key) {
|
|
73
|
+
return learnedCeilings.get(key);
|
|
74
|
+
}
|
|
75
|
+
export function _resetLearnedOutputCeilings() {
|
|
76
|
+
learnedCeilings.clear();
|
|
77
|
+
}
|
|
39
78
|
function statusOf(err) {
|
|
40
79
|
const s = err?.status;
|
|
41
80
|
if (typeof s === "number" && Number.isFinite(s))
|
|
@@ -58,6 +97,8 @@ export function classifyFailure(err) {
|
|
|
58
97
|
return "truncated_tool_call";
|
|
59
98
|
if (s === 413)
|
|
60
99
|
return "context"; // payload too large == context pressure
|
|
100
|
+
if ((s === 400 || s === 422) && outputCeilingLimit(msg) !== undefined)
|
|
101
|
+
return "output_ceiling"; // before CTX_RE: Groq's wording also says "context_window"
|
|
61
102
|
if (s === 400)
|
|
62
103
|
return CTX_RE.test(msg) ? "context" : "bad_request"; // the 400 body decides
|
|
63
104
|
if (s !== undefined && s >= 500 && LOADING_RE.test(msg))
|
package/dist/router/models.js
CHANGED
|
@@ -35,6 +35,11 @@ const ANTHROPIC_BASE = "https://api.anthropic.com/v1";
|
|
|
35
35
|
const GEMINI_BASE = "https://generativelanguage.googleapis.com/v1beta/openai"; // Google's OpenAI-compatible surface — no native transport
|
|
36
36
|
const GEMINI_CHAT_PATH = "/chat/completions"; // the base already carries its version: …/v1beta/openai/chat/completions
|
|
37
37
|
const QWEN_BASE = "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1";
|
|
38
|
+
/** Output ceilings (ModelProfile.maxOutput) — only where the vendor's limit is cited. Anthropic: the current Claude
|
|
39
|
+
* family's max_tokens ceiling (a larger value is a 400). QwenCloud qwen3.8-flash: the vendor's own 400 on JL2
|
|
40
|
+
* 2026-10-28 — "Range of max_tokens should be [1, 131072]". */
|
|
41
|
+
export const ANTHROPIC_MAX_OUTPUT = 128_000;
|
|
42
|
+
const QWEN_FLASH_MAX_OUTPUT = 131_072;
|
|
38
43
|
const NOUS_BASE = "https://inference-api.nousresearch.com/v1";
|
|
39
44
|
// Registry order IS picker order (visibleModels keeps it): fleet rows first (this box, then JL1), then the
|
|
40
45
|
// connected-provider rows (hidden until their key is connected), then the by-id-only lanes, then MOA. Free
|
|
@@ -108,9 +113,9 @@ export const BUILTIN_MODELS = [
|
|
|
108
113
|
// "anthropic" routes it through engine/anthropic-chat.ts (x-api-key auth from the BYO "anthropic" key; the
|
|
109
114
|
// Operator token is NEVER sent here — authHeaders scoping + anthropic-chat's own key resolution). Model ids
|
|
110
115
|
// are the vendor's complete 5.5-family ids (never a date suffix); ctx is the documented 1M, self-clamps to served truth.
|
|
111
|
-
{ id: "claude-opus", tier: "power_turbo", label: "Claude Opus 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the strongest Claude (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-opus-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
|
|
112
|
-
{ id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
|
|
113
|
-
{ id: "claude-haiku", tier: "economy", label: "Claude Haiku 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the fast, cheap Claude for light work, your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-haiku-5-5", ctx: 1000000, byo: "anthropic", transport: "anthropic" },
|
|
116
|
+
{ id: "claude-opus", tier: "power_turbo", label: "Claude Opus 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the strongest Claude (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-opus-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
|
|
117
|
+
{ id: "claude-sonnet", tier: "power_turbo", label: "Claude Sonnet 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — full tool-using delegate/chat target (native Messages wire), your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
|
|
118
|
+
{ id: "claude-haiku", tier: "economy", label: "Claude Haiku 5.5", box: "Anthropic", kind: "single", desc: "BYO Anthropic — the fast, cheap Claude for light work, your Anthropic key", endpoint: ANTHROPIC_BASE, model: "claude-haiku-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, byo: "anthropic", transport: "anthropic" },
|
|
114
119
|
// Gemini — BYO Google connectors over Google's OpenAI-compatible base (no native transport needed; the
|
|
115
120
|
// strict openai dialect is what that surface accepts). Same "gemini" key account as the byo-model preset.
|
|
116
121
|
{ id: "gemini-pro", tier: "power_turbo", label: "Gemini 2.5 Pro", box: "Google", kind: "single", desc: "BYO Google — Gemini 2.5 Pro over the OpenAI-compatible base, your Gemini key", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, byo: "gemini", transport: "openai", chatPath: GEMINI_CHAT_PATH },
|
|
@@ -120,7 +125,7 @@ export const BUILTIN_MODELS = [
|
|
|
120
125
|
// authHeaders NEVER sends the Operator token to this host. ctx starts conservative and self-clamps
|
|
121
126
|
// to the served truth (observeContext).
|
|
122
127
|
{ id: "qwen3.8-max", tier: "power_turbo", label: "Qwen 3.8 Max", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: QWEN_BASE, model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
|
|
123
|
-
{ id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
|
|
128
|
+
{ id: "qwen3.8-flash", tier: "economy", label: "Qwen 3.8 Flash", box: "QwenCloud", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: QWEN_BASE, model: "qwen3.8-flash", ctx: 262144, maxOutput: QWEN_FLASH_MAX_OUTPUT, byo: "qwen", transport: "openai" },
|
|
124
129
|
// ── by-id lanes (hidden from the picker, still resolve) ────────────────────────────────────────────────
|
|
125
130
|
// The cloud slot of the SAME Aurora, folded out of the picker in 0.1.332 (one Aurora row; the cloud legs ride
|
|
126
131
|
// in buildEndpointChain's failover chain). Reachable by id for scripts. api.0perator.co is AXE's OWN gateway
|
|
@@ -130,12 +135,12 @@ export const BUILTIN_MODELS = [
|
|
|
130
135
|
{ id: "axe-aurora-300k", tier: "power", label: "Aurora Code 1", params: "35B-A3B", box: "cloud", kind: "single", desc: "remote shared slot via api.0perator.co (api.axe.onl as fallback) — contended decode measured 1-4.6 tok/s vs local 24-47; cold >~100K prefills can hit the Cloudflare ~125s edge cutoff", endpoint: GATEWAY_BASE, endpoints: [GATEWAY_BASE, LEGACY_GATEWAY_BASE], model: "aurora-code-1", ctx: 307200, transport: "openai", hidden: true },
|
|
131
136
|
{ id: "operator-128k", tier: "economy", label: "Aurora Code 1", params: "35B-A3B", box: "JL2", kind: "single", desc: "128K context, lighter RAM (:8096) — slot not served on this fleet today; hidden from the picker, resolves by id when the slot comes up", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072, hidden: true },
|
|
132
137
|
// ── orchestrated ────────────────────────────────────────────────────────────────────────────────────────
|
|
133
|
-
{ id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot —
|
|
138
|
+
{ id: "moa", tier: "power_turbo", label: "MOA", box: "mixture of agents", kind: "orchestrated", desc: "the team slot — each turn goes to Cortana + Dolphin 7B (JL1) through the 0perator gateway in parallel, then Cortana writes the answer (settings.moa overrides)" },
|
|
134
139
|
];
|
|
135
140
|
export const OPERATOR_FREE_ACCOUNT = "0perator";
|
|
136
141
|
export const BYO_PRESETS = {
|
|
137
142
|
openai: { label: "OpenAI", box: "OpenAI", endpoint: "https://api.openai.com/v1", model: "gpt-5", ctx: 272000, account: "openai", envAlias: "OPENAI_API_KEY" },
|
|
138
|
-
anthropic: { label: "Anthropic", box: "Anthropic", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, account: "anthropic", transport: "anthropic", envAlias: "ANTHROPIC_API_KEY" },
|
|
143
|
+
anthropic: { label: "Anthropic", box: "Anthropic", endpoint: ANTHROPIC_BASE, model: "claude-sonnet-5-5", ctx: 1000000, maxOutput: ANTHROPIC_MAX_OUTPUT, account: "anthropic", transport: "anthropic", envAlias: "ANTHROPIC_API_KEY" },
|
|
139
144
|
gemini: { label: "Google (Gemini)", box: "Google", endpoint: GEMINI_BASE, model: "gemini-2.5-pro", ctx: 1000000, account: "gemini", envAlias: "GEMINI_API_KEY", chatPath: GEMINI_CHAT_PATH },
|
|
140
145
|
groq: { label: "Groq", box: "Groq", endpoint: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile", ctx: 131072, account: "groq", envAlias: "GROQ_API_KEY" },
|
|
141
146
|
deepseek: { label: "DeepSeek", box: "DeepSeek", endpoint: "https://api.deepseek.com/v1", model: "deepseek-chat", ctx: 131072, account: "deepseek", envAlias: "DEEPSEEK_API_KEY" },
|
package/dist/session.js
CHANGED
|
@@ -31,6 +31,7 @@ import { withHooks } from "./hooks/index.js";
|
|
|
31
31
|
import { Telemetry } from "./observability/index.js";
|
|
32
32
|
import { runSelfImprove } from "./selfimprove/index.js";
|
|
33
33
|
import { RollingSummarizer } from "./engine/rolling-summary.js";
|
|
34
|
+
import { decisionPointsEnabled } from "./engine/decision-points.js";
|
|
34
35
|
import { createSleepScheduler } from "./consolidation/scheduler.js";
|
|
35
36
|
/** The system-prompt directive for an extended-reasoning mode ("" when off). The owner watches the model's
|
|
36
37
|
* reasoning stream live (dim, above the answer) and re-reads it in scrollback, so /think asks the model to
|
|
@@ -207,19 +208,21 @@ function makeAskTool(handler) {
|
|
|
207
208
|
return {
|
|
208
209
|
name: "ask_user",
|
|
209
210
|
safe: false,
|
|
210
|
-
description: "
|
|
211
|
-
"
|
|
212
|
-
"
|
|
213
|
-
"
|
|
214
|
-
"
|
|
215
|
-
"
|
|
216
|
-
"the owner
|
|
217
|
-
"every
|
|
211
|
+
description: "Put a decision to the owner as a multiple-choice question; blocks until they choose, then returns the " +
|
|
212
|
+
"chosen option(s). ASK at a decision point: before the first change of a new build, feature or multi-step " +
|
|
213
|
+
"refactor (offer your short plan as the first option), when there are 2+ genuinely different approaches, " +
|
|
214
|
+
"scopes or tradeoffs, or before a destructive/irreversible step. DON'T ask for routine work (a typo, a clear " +
|
|
215
|
+
"small edit, a bug you found, running a check) or for anything you can determine from the code or the request. " +
|
|
216
|
+
"Give 2-4 concrete options, the recommended one FIRST labelled \"(recommended)\", each a short line saying " +
|
|
217
|
+
"what happens — the owner ALWAYS also gets a free-text 'type your own' choice, so list the likely paths, " +
|
|
218
|
+
"don't enumerate every one. Once answered, proceed with that choice. By default the owner picks exactly ONE " +
|
|
219
|
+
"option; set multiSelect:true when the options are not mutually exclusive (they toggle each with Space and " +
|
|
220
|
+
"confirm the set) — the reply then lists every option they chose.",
|
|
218
221
|
parameters: {
|
|
219
222
|
type: "object",
|
|
220
223
|
properties: {
|
|
221
|
-
question: { type: "string", description: "The
|
|
222
|
-
options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices." },
|
|
224
|
+
question: { type: "string", description: "The decision, one sentence." },
|
|
225
|
+
options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices, recommended first (labelled \"(recommended)\")." },
|
|
223
226
|
multiSelect: { type: "boolean", description: "Allow the owner to select more than one option (default false = pick exactly one)." },
|
|
224
227
|
},
|
|
225
228
|
required: ["question", "options"],
|
|
@@ -353,6 +356,7 @@ export class Session {
|
|
|
353
356
|
* outlives the 15s-abort classification); `operator run` headless MUST. Safe to call anytime, twice,
|
|
354
357
|
* from anywhere: the pending promise is swapped and failures were already swallowed by the module. */
|
|
355
358
|
async flushRouteShadow() { const p = this._shadowPending; this._shadowPending = Promise.resolve(); await p; }
|
|
359
|
+
decisionPoints;
|
|
356
360
|
planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
|
|
357
361
|
thinkMode = "off"; // /think, /ultrathink — extended reasoning
|
|
358
362
|
recalled = false;
|
|
@@ -405,6 +409,7 @@ export class Session {
|
|
|
405
409
|
reg.set("stop_agent", makeStopTool(cfg.stopAgent));
|
|
406
410
|
if (cfg.askUser)
|
|
407
411
|
reg.set("ask_user", makeAskTool(cfg.askUser));
|
|
412
|
+
this.decisionPoints = decisionPointsEnabled(cfg.decisionPoints);
|
|
408
413
|
reg.set("self_status", makeSelfStatusTool(() => ({
|
|
409
414
|
model: this.currentModel(),
|
|
410
415
|
route: this.currentRoute(),
|
|
@@ -825,6 +830,8 @@ export class Session {
|
|
|
825
830
|
token: token ?? (hasGatewayLeg && !requiresOperatorToken(ep) ? "" : undefined),
|
|
826
831
|
transport: profile.transport,
|
|
827
832
|
chatPath: profile.chatPath,
|
|
833
|
+
maxOutput: profile.maxOutput,
|
|
834
|
+
provider: profile.box,
|
|
828
835
|
}));
|
|
829
836
|
this.inner = new AuroraRouter(eps);
|
|
830
837
|
this.router = this.wrap(this.inner);
|
|
@@ -1295,15 +1302,20 @@ export class Session {
|
|
|
1295
1302
|
// these now.") gets one nudge to actually do it (≤2/turn) instead of finalizing. Off in plan mode — there
|
|
1296
1303
|
// the text IS the deliverable ("I'll implement this once you approve") — and via KODE_TURN_CONTINUATION=0.
|
|
1297
1304
|
turnContinuation: { enabled: process.env.KODE_TURN_CONTINUATION !== "0" && !this.planMode },
|
|
1305
|
+
// Decision points: a build turn's first change waits for the owner's choice of direction (ask_user). Off in
|
|
1306
|
+
// plan mode (the plan + exit picker IS the decision) and inert where ask_user isn't registered (headless).
|
|
1307
|
+
decisionPoints: { enabled: this.decisionPoints && !this.planMode },
|
|
1298
1308
|
});
|
|
1299
1309
|
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 });
|
|
1300
|
-
// MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched):
|
|
1301
|
-
//
|
|
1310
|
+
// MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
|
|
1311
|
+
// by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
|
|
1312
|
+
// llama-server (Cortana, --parallel 1) that 8-token call evicted the session's cached prompt after every turn:
|
|
1313
|
+
// the next round re-read ~42K tokens (~100 s) — measured on JL1 2026-10-28. Labels
|
|
1302
1314
|
// the turn with the gate's own 9-label contract and appends {label, model-that-ran, cost} to
|
|
1303
1315
|
// ~/.axe/operator/route-shadow/<date>.jsonl. The classifier runs as a BACKGROUND-priority call on
|
|
1304
1316
|
// the endpoint gate (a main turn always outranks it) with a 15s abort, and routeShadowTurn swallows
|
|
1305
1317
|
// every failure — observability that can degrade the observed thing is not observability.
|
|
1306
|
-
if (process.env.KODE_MOA_SHADOW
|
|
1318
|
+
if (process.env.KODE_MOA_SHADOW === "1") {
|
|
1307
1319
|
const prof = findModel(this.liveRegistry(), this.modelId);
|
|
1308
1320
|
// Not on a vendor's paid wire: an 8-token classifier call per Claude turn costs money and returns nothing once the model thinks.
|
|
1309
1321
|
const shadowBase = prof?.endpoint && prof.transport !== "anthropic" ? endpointBase(prof.endpoint) : undefined;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Document → TEXT, so file_read and image_analyze read a PDF/DOCX/XLSX/PPTX by its words instead of a
|
|
2
|
+
// picture of page 1 (the Hermes read_extract model). Dependency-free: macOS PDFKit through the JXA ObjC
|
|
3
|
+
// bridge for PDF, `textutil` for the word-processor formats, and `unzip` + the OOXML parts for sheets and
|
|
4
|
+
// decks. Every extractor is time-bounded; a failure or an empty result returns null so the caller can
|
|
5
|
+
// fall back (image_analyze then renders the page for vision — the scanned-PDF case).
|
|
6
|
+
import { pexecFile } from "./exec.js";
|
|
7
|
+
export const DOC_TEXT_TIMEOUT_MS = 30_000;
|
|
8
|
+
const MAX_BUFFER = 32 * 1024 * 1024;
|
|
9
|
+
const TEXTUTIL_EXTS = new Set(["doc", "docx", "rtf", "rtfd", "html", "htm", "odt", "webarchive", "wordml"]);
|
|
10
|
+
export const DOC_TEXT_EXTS = new Set(["pdf", "xlsx", "pptx", ...TEXTUTIL_EXTS]);
|
|
11
|
+
export function docExt(path) {
|
|
12
|
+
const base = path.split(/[\\/]/).pop() || "";
|
|
13
|
+
return base.includes(".") ? (base.split(".").pop() || "").toLowerCase() : "";
|
|
14
|
+
}
|
|
15
|
+
const opts = { timeout: DOC_TEXT_TIMEOUT_MS, killSignal: "SIGKILL", maxBuffer: MAX_BUFFER };
|
|
16
|
+
// Pages joined with a form feed so the page count survives the trip through stdout.
|
|
17
|
+
const PDFKIT_JXA = `ObjC.import("PDFKit");
|
|
18
|
+
function run(argv) {
|
|
19
|
+
const d = $.PDFDocument.alloc.initWithURL($.NSURL.fileURLWithPath(argv[0]));
|
|
20
|
+
if (!d) return "";
|
|
21
|
+
const out = [];
|
|
22
|
+
for (let i = 0; i < d.pageCount; i++) { const s = d.pageAtIndex(i).string; out.push(s && !s.isNil() ? s.js : ""); }
|
|
23
|
+
return out.join("\\f");
|
|
24
|
+
}`;
|
|
25
|
+
async function pdfText(path) {
|
|
26
|
+
const { stdout } = await pexecFile("osascript", ["-l", "JavaScript", "-e", PDFKIT_JXA, path], opts);
|
|
27
|
+
const pages = stdout.replace(/\n$/, "").split("\f");
|
|
28
|
+
const text = pages.map((p, i) => (pages.length > 1 ? `--- page ${i + 1} ---\n${p.trim()}` : p.trim())).join("\n\n");
|
|
29
|
+
return { text, method: "PDFKit", pages: pages.length };
|
|
30
|
+
}
|
|
31
|
+
async function textutilText(path) {
|
|
32
|
+
try {
|
|
33
|
+
const { stdout } = await pexecFile("textutil", ["-convert", "txt", "-stdout", path], opts);
|
|
34
|
+
return { text: stdout, method: "textutil" };
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
if (docExt(path) !== "docx")
|
|
38
|
+
throw e;
|
|
39
|
+
return docxText(path); // no textutil (non-macOS): read the OOXML body directly
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function zipList(path) {
|
|
43
|
+
const { stdout } = await pexecFile("unzip", ["-Z1", path], opts);
|
|
44
|
+
return stdout.split("\n").filter(Boolean);
|
|
45
|
+
}
|
|
46
|
+
async function zipPart(path, part) {
|
|
47
|
+
return (await pexecFile("unzip", ["-p", path, part], opts)).stdout;
|
|
48
|
+
}
|
|
49
|
+
const byNumber = (re) => (a, b) => Number((re.exec(a) || [])[1]) - Number((re.exec(b) || [])[1]);
|
|
50
|
+
export function xmlUnescape(s) {
|
|
51
|
+
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'")
|
|
52
|
+
.replace(/&#(\d+);/g, (_m, d) => String.fromCodePoint(Number(d)))
|
|
53
|
+
.replace(/&#x([0-9a-f]+);/gi, (_m, h) => String.fromCodePoint(parseInt(h, 16)))
|
|
54
|
+
.replace(/&/g, "&");
|
|
55
|
+
}
|
|
56
|
+
const runs = (xml, tag) => [...xml.matchAll(new RegExp(`<${tag}(?:\\s[^>]*)?>([^<]*)</${tag}>`, "g"))].map((m) => xmlUnescape(m[1]));
|
|
57
|
+
/** Sheet XML + the shared-string table → tab-separated rows. Shared (t="s"), inline (t="inlineStr") and
|
|
58
|
+
* literal values; formulas show their cached value. */
|
|
59
|
+
export function xlsxSheetRows(sheetXml, shared) {
|
|
60
|
+
const rows = [];
|
|
61
|
+
for (const row of sheetXml.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
|
|
62
|
+
const cells = [];
|
|
63
|
+
for (const c of row[1].matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
|
|
64
|
+
const attrs = c[1];
|
|
65
|
+
const body = c[2] ?? "";
|
|
66
|
+
const t = (/\bt="([^"]+)"/.exec(attrs) || [])[1];
|
|
67
|
+
const v = (/<v>([^<]*)<\/v>/.exec(body) || [])[1];
|
|
68
|
+
cells.push(t === "s" ? (shared[Number(v)] ?? "") : t === "inlineStr" ? runs(body, "t").join("") : v != null ? xmlUnescape(v) : "");
|
|
69
|
+
}
|
|
70
|
+
while (cells.length && cells[cells.length - 1] === "")
|
|
71
|
+
cells.pop();
|
|
72
|
+
if (cells.length)
|
|
73
|
+
rows.push(cells.join("\t"));
|
|
74
|
+
}
|
|
75
|
+
return rows;
|
|
76
|
+
}
|
|
77
|
+
async function xlsxText(path) {
|
|
78
|
+
const parts = await zipList(path);
|
|
79
|
+
const shared = parts.includes("xl/sharedStrings.xml")
|
|
80
|
+
? [...(await zipPart(path, "xl/sharedStrings.xml")).matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => runs(m[1], "t").join(""))
|
|
81
|
+
: [];
|
|
82
|
+
const re = /^xl\/worksheets\/sheet(\d+)\.xml$/;
|
|
83
|
+
const sheets = parts.filter((p) => re.test(p)).sort(byNumber(re));
|
|
84
|
+
const out = [];
|
|
85
|
+
for (const s of sheets)
|
|
86
|
+
out.push(`--- sheet ${(re.exec(s) || [])[1]} ---\n${xlsxSheetRows(await zipPart(path, s), shared).join("\n")}`);
|
|
87
|
+
return { text: out.join("\n\n"), method: "xlsx (OOXML)", pages: sheets.length };
|
|
88
|
+
}
|
|
89
|
+
async function docxText(path) {
|
|
90
|
+
const xml = await zipPart(path, "word/document.xml");
|
|
91
|
+
const paras = [...xml.matchAll(/<w:p\b[^>]*>([\s\S]*?)<\/w:p>/g)].map((m) => runs(m[1], "w:t").join(""));
|
|
92
|
+
return { text: paras.join("\n"), method: "docx (OOXML)" };
|
|
93
|
+
}
|
|
94
|
+
async function pptxText(path) {
|
|
95
|
+
const re = /^ppt\/slides\/slide(\d+)\.xml$/;
|
|
96
|
+
const slides = (await zipList(path)).filter((p) => re.test(p)).sort(byNumber(re));
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const s of slides) {
|
|
99
|
+
const xml = await zipPart(path, s);
|
|
100
|
+
const paras = [...xml.matchAll(/<a:p\b[^>]*>([\s\S]*?)<\/a:p>/g)].map((m) => runs(m[1], "a:t").join("")).filter((p) => p.trim());
|
|
101
|
+
out.push(`--- slide ${(re.exec(s) || [])[1]} ---\n${paras.join("\n")}`);
|
|
102
|
+
}
|
|
103
|
+
return { text: out.join("\n\n"), method: "pptx (OOXML)", pages: slides.length };
|
|
104
|
+
}
|
|
105
|
+
/** Extract a document's text, or null when the format isn't one we extract, the extractor is missing or
|
|
106
|
+
* fails, or the document carries no text layer (whitespace/page markers only). */
|
|
107
|
+
export async function extractDocText(path) {
|
|
108
|
+
const ext = docExt(path);
|
|
109
|
+
if (!DOC_TEXT_EXTS.has(ext))
|
|
110
|
+
return null;
|
|
111
|
+
try {
|
|
112
|
+
const r = ext === "pdf" ? await pdfText(path) : ext === "xlsx" ? await xlsxText(path) : ext === "pptx" ? await pptxText(path) : await textutilText(path);
|
|
113
|
+
if (!r)
|
|
114
|
+
return null;
|
|
115
|
+
const meaningful = r.text.replace(/--- (page|sheet|slide) \d+ ---/g, "").trim();
|
|
116
|
+
return meaningful ? r : null;
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** "PDFKit, 3 pages" / "xlsx (OOXML), 2 sheets" / "textutil" — the provenance line both readers print. */
|
|
123
|
+
export function describeDocText(path, doc) {
|
|
124
|
+
if (!doc.pages)
|
|
125
|
+
return doc.method;
|
|
126
|
+
const ext = docExt(path);
|
|
127
|
+
const unit = ext === "xlsx" ? "sheet" : ext === "pptx" ? "slide" : "page";
|
|
128
|
+
return `${doc.method}, ${doc.pages} ${unit}${doc.pages === 1 ? "" : "s"}`;
|
|
129
|
+
}
|
package/dist/tools/paths.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
// Node-free by construction (reads process.env only, no imports) so the tools module still loads in the
|
|
8
8
|
// headless conformance runner. Only a LEADING ~ is a home reference: bare "~" and "~/rest"; "~user" (a
|
|
9
9
|
// different account's home) and a ~ anywhere but the first character are left untouched, matching the shell.
|
|
10
|
-
export function expandPath(
|
|
10
|
+
export function expandPath(raw) {
|
|
11
|
+
const p = unshellPath(raw);
|
|
11
12
|
const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
|
|
12
13
|
if (!home)
|
|
13
14
|
return p;
|
|
@@ -17,6 +18,17 @@ export function expandPath(p) {
|
|
|
17
18
|
return home + p.slice(1);
|
|
18
19
|
return p;
|
|
19
20
|
}
|
|
21
|
+
/** A path pasted from a terminal arrives shell-quoted: `~/Downloads/Expense\ Form.pdf` or `'~/My File.pdf'`. The file
|
|
22
|
+
* tools call fs directly, so the backslash or quotes become part of the name and the file "doesn't exist" — on
|
|
23
|
+
* 2026-10-28 that sent Quick Look a nonexistent path and image_analyze hung 47 minutes. Undo the quoting a shell
|
|
24
|
+
* would: one pair of wrapping quotes, and a backslash before a shell-special character. A backslash before
|
|
25
|
+
* anything else stays (Windows `C:\Users\x` is untouched). */
|
|
26
|
+
export function unshellPath(p) {
|
|
27
|
+
let s = p.trim();
|
|
28
|
+
if (s.length >= 2 && ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))))
|
|
29
|
+
return s.slice(1, -1);
|
|
30
|
+
return s.replace(/\\([ ()'"&;|<>$`!*?[\]{}#=%^,])/g, "$1");
|
|
31
|
+
}
|
|
20
32
|
/** Strip trailing slashes; keep "/" as "/". */
|
|
21
33
|
function normPath(p) {
|
|
22
34
|
if (!p)
|
package/dist/tools/registry.js
CHANGED
|
@@ -21,6 +21,8 @@ import { MONITORING_TOOLS } from "./monitoring-tools.js";
|
|
|
21
21
|
import { desktopScreenshot, desktopClick, desktopRead, appInteract, capturePermalink, liveDrive } from "./chauffeur-native.js";
|
|
22
22
|
import { findFiles, FIND_FILES_DEFAULT_LIMIT, FIND_FILES_MAX_LIMIT, KINDS } from "./find-files.js";
|
|
23
23
|
import { formatGitStatus } from "./git-status.js";
|
|
24
|
+
import { DOC_TEXT_EXTS, describeDocText, docExt, extractDocText } from "./doc-text.js";
|
|
25
|
+
import { gatewayModelAllowed, resolveVisionGateway } from "./vision-gateway.js";
|
|
24
26
|
import { expandPath, assertContentSearchScope, assertShellHomeWideSearch, assertShellBlindDownload } from "./paths.js";
|
|
25
27
|
import { runMemoryTool } from "./memory.js";
|
|
26
28
|
import { documentGenerate } from "./document.js";
|
|
@@ -190,8 +192,19 @@ async function fileRead(args) {
|
|
|
190
192
|
if (blocked)
|
|
191
193
|
return `error: ${blocked}`;
|
|
192
194
|
try {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
+
let src;
|
|
196
|
+
let head = "";
|
|
197
|
+
if (DOC_TEXT_EXTS.has(docExt(path))) {
|
|
198
|
+
const doc = await extractDocText(path);
|
|
199
|
+
if (!doc)
|
|
200
|
+
return `error: no text could be extracted from ${path} (a scanned or image-only document?) — use image_analyze to look at it`;
|
|
201
|
+
src = doc.text;
|
|
202
|
+
head = `[extracted text — ${describeDocText(path, doc)}; layout and images are not included]\n`;
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
206
|
+
src = await readFile(path, "utf8");
|
|
207
|
+
}
|
|
195
208
|
const lines = src.split("\n");
|
|
196
209
|
const offset = Number(args.offset ?? 0);
|
|
197
210
|
const explicitLimit = args.limit !== undefined;
|
|
@@ -203,7 +216,7 @@ async function fileRead(args) {
|
|
|
203
216
|
else if (!explicitLimit && offset + limit < lines.length) {
|
|
204
217
|
out += `\n…[showing lines ${offset + 1}-${offset + limit} of ${lines.length} — pass offset/limit to see the rest]`;
|
|
205
218
|
}
|
|
206
|
-
return out;
|
|
219
|
+
return head + out;
|
|
207
220
|
}
|
|
208
221
|
catch (e) {
|
|
209
222
|
return `error: ${e.message}`;
|
|
@@ -1665,6 +1678,7 @@ function visionTargets(settings) {
|
|
|
1665
1678
|
// Documents the vision model can't read as pixels — rendered to a PNG first (see renderDocForVision).
|
|
1666
1679
|
// macOS Quick Look (qlmanage) covers all of these with no extra install, so image_analyze works on a
|
|
1667
1680
|
// deck/PDF/page the same way it works on a photo.
|
|
1681
|
+
export const QUICKLOOK_TIMEOUT_MS = 30_000;
|
|
1668
1682
|
const VISION_DOC_EXTS = new Set(["pdf", "pptx", "ppt", "docx", "doc", "html", "htm", "rtf", "odt", "odp", "pages", "key", "numbers", "xlsx", "xls", "epub", "webarchive", "md"]);
|
|
1669
1683
|
/** If `path` is a document (deck/PDF/page/sheet), render its first page to a PNG with macOS Quick Look and
|
|
1670
1684
|
* return that PNG path — so the vision pipeline SEES the document. Non-documents pass straight through; a
|
|
@@ -1682,7 +1696,8 @@ async function renderDocForVision(path) {
|
|
|
1682
1696
|
const { promisify } = await nodeImport("node:util");
|
|
1683
1697
|
const pexec = promisify(execFile);
|
|
1684
1698
|
const dir = await mkdtemp(join(os.tmpdir(), "axe-doc-"));
|
|
1685
|
-
|
|
1699
|
+
// Quick Look can wait forever (a nonexistent or unreadable file hung it 47 min on 2026-10-28): bound it.
|
|
1700
|
+
await pexec("qlmanage", ["-t", "-s", "1600", "-o", dir, path], { timeout: QUICKLOOK_TIMEOUT_MS, killSignal: "SIGKILL" });
|
|
1686
1701
|
const out = join(dir, `${basename(path)}.png`); // qlmanage names it <basename>.<ext>.png
|
|
1687
1702
|
await access(out); // throws if Quick Look produced nothing → fall through
|
|
1688
1703
|
return out;
|
|
@@ -1747,13 +1762,73 @@ async function visionImageDataUrl(image) {
|
|
|
1747
1762
|
catch { /* any resize failure → original bytes (correctness over speed) */ }
|
|
1748
1763
|
return `data:${mime};base64,${buf.toString("base64")}`;
|
|
1749
1764
|
}
|
|
1750
|
-
/**
|
|
1751
|
-
|
|
1752
|
-
|
|
1765
|
+
/** One OpenAI-vision chat POST to `base` (…/v1). Never throws: the outcome says what happened. */
|
|
1766
|
+
async function postVision(base, auth, model, parts, args, timeout) {
|
|
1767
|
+
const ctrl = new AbortController();
|
|
1768
|
+
const timer = setTimeout(() => ctrl.abort(), timeout);
|
|
1769
|
+
try {
|
|
1770
|
+
const res = await fetch(`${base}/chat/completions`, {
|
|
1771
|
+
method: "POST", signal: ctrl.signal,
|
|
1772
|
+
headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...auth },
|
|
1773
|
+
body: JSON.stringify({ model, messages: [{ role: "system", content: VISION_SYS }, { role: "user", content: parts }], ...(Number.isFinite(Number(args.max_tokens)) ? { max_tokens: Number(args.max_tokens) } : {}), temperature: 0 }),
|
|
1774
|
+
});
|
|
1775
|
+
if (!res.ok)
|
|
1776
|
+
return { status: res.status, body: (await res.text().catch(() => "")).slice(0, 180) };
|
|
1777
|
+
const j = (await res.json().catch(() => ({})));
|
|
1778
|
+
return { text: j.choices?.[0]?.message?.content?.trim() || "" };
|
|
1779
|
+
}
|
|
1780
|
+
catch (e) {
|
|
1781
|
+
const aborted = e?.name === "AbortError";
|
|
1782
|
+
return { aborted, error: aborted ? `timed out after ${Math.round(timeout / 1000)}s` : String(e?.message ?? e) };
|
|
1783
|
+
}
|
|
1784
|
+
finally {
|
|
1785
|
+
clearTimeout(timer);
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
/** The gateway path: one backend, the router owns failover. Returns the answer, throws a final error, or
|
|
1789
|
+
* returns `fallthrough` when the gateway can't serve vision at all (unreachable / no healthy leg) so the
|
|
1790
|
+
* caller may try the direct chain. */
|
|
1791
|
+
async function visionViaGateway(gw, parts, args, timeout) {
|
|
1792
|
+
// A per-call model is honored only when it names one of our own vision routes; anything else (an old
|
|
1793
|
+
// direct-server id, a free catalog model) would bypass the route's privacy decision, so the route is used.
|
|
1794
|
+
const model = gatewayModelAllowed(str(args.model)) ? str(args.model) : gw.model;
|
|
1795
|
+
let last = "";
|
|
1796
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1797
|
+
const r = await postVision(gw.base, gw.auth, model, parts, args, timeout);
|
|
1798
|
+
if (r.text)
|
|
1799
|
+
return { text: r.text };
|
|
1800
|
+
if (r.text === "") {
|
|
1801
|
+
last = `${gw.label} returned no text`;
|
|
1802
|
+
continue;
|
|
1803
|
+
}
|
|
1804
|
+
if (r.status === 502 || r.status === 503 || r.status === 504)
|
|
1805
|
+
return { fallthrough: `${gw.label} ${gw.base} returned ${r.status}${r.body ? ` — ${r.body}` : ""}` };
|
|
1806
|
+
if (r.status)
|
|
1807
|
+
throw new Error(`${gw.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`);
|
|
1808
|
+
if (r.aborted)
|
|
1809
|
+
throw new Error(`${gw.label} ${r.error}`);
|
|
1810
|
+
return { fallthrough: `${gw.label} ${gw.base} unreachable (${r.error})` };
|
|
1811
|
+
}
|
|
1812
|
+
throw new Error(last);
|
|
1813
|
+
}
|
|
1814
|
+
/** Send a vision chat. Through the gateway's `vision` route when one resolves (vision-gateway.ts); the
|
|
1815
|
+
* direct endpoint chain below runs only for an owner pin or when no gateway can serve vision: skip any
|
|
1816
|
+
* target in cooldown, /health-gate local targets, time each independently, retry once on an empty body,
|
|
1817
|
+
* and on timeout / 402 / 429 / auth-error mark the target unhealthy for a TTL and fall through to the next.
|
|
1818
|
+
* Throws with the last error only when all are exhausted. */
|
|
1753
1819
|
async function visionComplete(parts, args, defaultTimeoutMs) {
|
|
1754
1820
|
const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
|
|
1755
|
-
const
|
|
1821
|
+
const settings = loadSettings();
|
|
1756
1822
|
const timeout = Math.max(5_000, Number(args.timeout_ms ?? defaultTimeoutMs));
|
|
1823
|
+
const gw = await resolveVisionGateway(settings);
|
|
1824
|
+
let gatewayNote = "";
|
|
1825
|
+
if (gw) {
|
|
1826
|
+
const g = await visionViaGateway(gw, parts, args, timeout);
|
|
1827
|
+
if ("text" in g)
|
|
1828
|
+
return g.text;
|
|
1829
|
+
gatewayNote = `${g.fallthrough}; `;
|
|
1830
|
+
}
|
|
1831
|
+
const targets = visionTargets(settings);
|
|
1757
1832
|
const now = () => Date.now();
|
|
1758
1833
|
let lastErr = `no vision service reachable (tried ${targets.map((t) => t.url).join(", ")})`;
|
|
1759
1834
|
for (const t of targets) {
|
|
@@ -1776,41 +1851,27 @@ async function visionComplete(parts, args, defaultTimeoutMs) {
|
|
|
1776
1851
|
}
|
|
1777
1852
|
const model = str(args.model) || t.model || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
|
|
1778
1853
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1779
|
-
const
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
if (
|
|
1788
|
-
const body = (await res.text().catch(() => "")).slice(0, 180);
|
|
1789
|
-
if (res.status === 401 || res.status === 402 || res.status === 403 || res.status === 429 || /credit|insufficient|quota|billing/i.test(body))
|
|
1790
|
-
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1791
|
-
lastErr = `${t.label} returned ${res.status}${body ? ` — ${body}` : ""}`;
|
|
1792
|
-
break; // non-200 → next endpoint
|
|
1793
|
-
}
|
|
1794
|
-
const j = (await res.json().catch(() => ({})));
|
|
1795
|
-
const text = j.choices?.[0]?.message?.content?.trim();
|
|
1796
|
-
if (text)
|
|
1797
|
-
return text;
|
|
1798
|
-
lastErr = `${t.label} returned no text`; // empty → retry once, then next endpoint
|
|
1799
|
-
}
|
|
1800
|
-
catch (e) {
|
|
1801
|
-
const aborted = e?.name === "AbortError";
|
|
1802
|
-
lastErr = aborted ? `${t.label} timed out after ${Math.round(timeout / 1000)}s` : `${t.label}: ${String(e?.message ?? e)}`;
|
|
1803
|
-
if (aborted) {
|
|
1854
|
+
const r = await postVision(`${t.url}/v1`, t.auth, model, parts, args, timeout);
|
|
1855
|
+
if (r.text)
|
|
1856
|
+
return r.text;
|
|
1857
|
+
if (r.text === "") {
|
|
1858
|
+
lastErr = `${t.label} returned no text`;
|
|
1859
|
+
continue;
|
|
1860
|
+
} // empty → retry once, then next endpoint
|
|
1861
|
+
if (r.status) {
|
|
1862
|
+
if (r.status === 401 || r.status === 402 || r.status === 403 || r.status === 429 || /credit|insufficient|quota|billing/i.test(r.body || ""))
|
|
1804
1863
|
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
}
|
|
1808
|
-
finally {
|
|
1809
|
-
clearTimeout(timer);
|
|
1864
|
+
lastErr = `${t.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`;
|
|
1865
|
+
break; // non-200 → next endpoint
|
|
1810
1866
|
}
|
|
1867
|
+
lastErr = `${t.label}${r.aborted ? " " : ": "}${r.error}`;
|
|
1868
|
+
if (r.aborted) {
|
|
1869
|
+
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1870
|
+
break;
|
|
1871
|
+
} // busy/slow → cooldown + next endpoint
|
|
1811
1872
|
}
|
|
1812
1873
|
}
|
|
1813
|
-
throw new Error(lastErr);
|
|
1874
|
+
throw new Error(gatewayNote + lastErr);
|
|
1814
1875
|
}
|
|
1815
1876
|
// Uncensoring system prompt for the vision model (owner's private system): the engine-level unrestricted
|
|
1816
1877
|
// layer only sees chat() turns, not these direct vision calls, so the analyze side gets its own one-line
|
|
@@ -1885,10 +1946,21 @@ async function imageInspect(args) {
|
|
|
1885
1946
|
}
|
|
1886
1947
|
}
|
|
1887
1948
|
async function imageAnalyze(args) {
|
|
1888
|
-
const
|
|
1949
|
+
const raw = str(args.image);
|
|
1950
|
+
const image = /^https?:\/\//.test(raw) ? raw : expandPath(raw);
|
|
1889
1951
|
if (!image)
|
|
1890
1952
|
return "error: image_analyze needs an image or document (a local path or an http(s) url)";
|
|
1891
1953
|
const question = str(args.question) || "Describe this image in detail.";
|
|
1954
|
+
// A document is read by its TEXT first (every page, exact characters); only a document with no text layer
|
|
1955
|
+
// (a scan) — or an explicit as_image — goes to vision as a rendered first page.
|
|
1956
|
+
const asImage = args.as_image === true || str(args.as_image) === "true";
|
|
1957
|
+
if (!asImage && !/^https?:\/\//.test(image) && DOC_TEXT_EXTS.has(docExt(image))) {
|
|
1958
|
+
const doc = await extractDocText(image);
|
|
1959
|
+
if (doc) {
|
|
1960
|
+
const body = doc.text.length > FILE_READ_MAX_CHARS ? `${doc.text.slice(0, FILE_READ_MAX_CHARS)}\n…[truncated at ${FILE_READ_MAX_CHARS} of ${doc.text.length} chars — file_read with offset/limit pages through the rest]` : doc.text;
|
|
1961
|
+
return `document text (${describeDocText(image, doc)}) — extracted, not seen as pixels. Answer "${question}" from this text; call image_analyze again with as_image: true only if the question is about layout, charts or pictures.\n\n${body}`;
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1892
1964
|
let imageUrl;
|
|
1893
1965
|
try {
|
|
1894
1966
|
imageUrl = await visionImageDataUrl(image); // downscales a large local image first; http(s) passes through
|
|
@@ -1958,7 +2030,7 @@ async function videoAnalyze(args) {
|
|
|
1958
2030
|
}
|
|
1959
2031
|
catch (e) {
|
|
1960
2032
|
const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
|
|
1961
|
-
return `error: video_analyze failed (${msg}) — needs ffmpeg on PATH + the
|
|
2033
|
+
return `error: video_analyze failed (${msg}) — needs ffmpeg on PATH + a vision backend (the gateway vision route)`;
|
|
1962
2034
|
}
|
|
1963
2035
|
finally {
|
|
1964
2036
|
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
@@ -2528,12 +2600,13 @@ const TOOLS = [
|
|
|
2528
2600
|
},
|
|
2529
2601
|
{
|
|
2530
2602
|
name: "image_analyze", safe: true,
|
|
2531
|
-
description: "Analyze/describe an image
|
|
2603
|
+
description: "Analyze/describe an image with REAL vision (not pixel stats) through the 0perator gateway's `vision` route — the router picks a healthy fleet VL server. Pass a local path or an http(s) url + an optional question; returns the model's answer. Use this to actually SEE a reference, screenshot, or generated image before acting on it — NEVER guess an image's content from its file size or numpy brightness. A DOCUMENT (PDF, DOCX, XLSX, PPTX, RTF, HTML) comes back as its extracted TEXT, every page — answer from that; only a scanned/image-only document is rendered and looked at (first page). Pass as_image: true to look at a document's first page as a picture (layout, charts).",
|
|
2532
2604
|
parameters: { type: "object", properties: {
|
|
2533
|
-
image: { type: "string", description: "a local file path or an http(s) url — an image, OR a document (pdf/pptx/
|
|
2605
|
+
image: { type: "string", description: "a local file path or an http(s) url — an image, OR a document (pdf/docx/xlsx/pptx/rtf/html/…), which comes back as its extracted text" },
|
|
2534
2606
|
question: { type: "string", description: 'what to ask about the image (default "Describe this image in detail.")' },
|
|
2535
2607
|
max_tokens: { type: "number", description: "optional cap on answer length; omit for a full, uncapped description" },
|
|
2536
2608
|
timeout_ms: { type: "number", description: "default 120000" },
|
|
2609
|
+
as_image: { type: "boolean", description: "for a document: skip text extraction and look at its rendered first page (layout, charts, pictures)" },
|
|
2537
2610
|
}, required: ["image"] },
|
|
2538
2611
|
run: imageAnalyze,
|
|
2539
2612
|
},
|
|
@@ -2547,7 +2620,7 @@ const TOOLS = [
|
|
|
2547
2620
|
},
|
|
2548
2621
|
{
|
|
2549
2622
|
name: "video_analyze", safe: true,
|
|
2550
|
-
description: "Analyze/describe a VIDEO
|
|
2623
|
+
description: "Analyze/describe a VIDEO through the 0perator gateway's `vision` route — ffmpeg samples frames evenly across the clip and the VL model (multi-image) describes what happens. Pass a local path or an http(s) url + an optional question; returns the analysis. Use this to actually SEE a video's content — never guess from the file.",
|
|
2551
2624
|
parameters: { type: "object", properties: {
|
|
2552
2625
|
video: { type: "string", description: "a local file path or an http(s) url to the video" },
|
|
2553
2626
|
question: { type: "string", description: "what to ask about the video (default: describe what happens across it)" },
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// One resolved vision backend (Hermes resolve_vision_provider_client): image_analyze / video_analyze speak
|
|
2
|
+
// OpenAI-vision to OUR gateway's `vision` route, and the router owns failover across the fleet's VL
|
|
3
|
+
// servers. Resolution order: gateway "off" → none (the caller keeps its direct endpoint chain); an explicit
|
|
4
|
+
// gateway URL; an owner pin (KODE_VISION_URL, or services.vision.url/remoteUrl set in settings.json) →
|
|
5
|
+
// none; the local router on loopback (no token) when /healthz says the route is up; else the public
|
|
6
|
+
// gateway with the signed-in Operator token. No token and no local router → none (the direct chain). The
|
|
7
|
+
// engine never adds a cloud provider here — which servers back `vision` is the route's decision.
|
|
8
|
+
import { getOperatorToken, operatorTrustedUrl } from "../engine/aurora.js";
|
|
9
|
+
export const LOCAL_VISION_GATEWAY = "http://127.0.0.1:8620/v1";
|
|
10
|
+
export const PUBLIC_VISION_GATEWAY = "https://api.0perator.co/v1";
|
|
11
|
+
export const DEFAULT_VISION_ROUTE = "vision";
|
|
12
|
+
const PROBE_TIMEOUT_MS = 3_000;
|
|
13
|
+
const isLoopback = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:|\/|$)/.test(u);
|
|
14
|
+
function tokenFor(base) {
|
|
15
|
+
if (isLoopback(base) || !operatorTrustedUrl(base))
|
|
16
|
+
return {};
|
|
17
|
+
const token = getOperatorToken() || process.env.KODE_OPERATOR_TOKEN;
|
|
18
|
+
return token ? { Authorization: `Bearer ${token}` } : {};
|
|
19
|
+
}
|
|
20
|
+
/** Whether a router at `base` (…/v1) answers and reports `route` up. The router serves /healthz at its root. */
|
|
21
|
+
export async function routeUp(base, route, timeoutMs = PROBE_TIMEOUT_MS) {
|
|
22
|
+
try {
|
|
23
|
+
const root = base.replace(/\/v1\/?$/, "");
|
|
24
|
+
const r = await fetch(`${root}/healthz?route=${encodeURIComponent(route)}`, { signal: AbortSignal.timeout(timeoutMs) });
|
|
25
|
+
return r.ok;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export async function resolveVisionGateway(s, o = {}) {
|
|
32
|
+
const v = s.services?.vision;
|
|
33
|
+
const model = v?.model?.trim() || DEFAULT_VISION_ROUTE;
|
|
34
|
+
const gw = v?.gateway?.trim();
|
|
35
|
+
if (gw === "off")
|
|
36
|
+
return null;
|
|
37
|
+
if (gw && gw !== "auto") {
|
|
38
|
+
const base = gw.replace(/\/$/, "");
|
|
39
|
+
return { base, model, auth: tokenFor(base), label: "gateway" };
|
|
40
|
+
}
|
|
41
|
+
if (process.env.KODE_VISION_URL || s.explicit?.visionUrl)
|
|
42
|
+
return null;
|
|
43
|
+
const probe = o.probe ?? routeUp;
|
|
44
|
+
const local = (o.localBase ?? LOCAL_VISION_GATEWAY).replace(/\/$/, "");
|
|
45
|
+
if (await probe(local, model))
|
|
46
|
+
return { base: local, model, auth: {}, label: "local gateway" };
|
|
47
|
+
const pub = (o.publicBase ?? PUBLIC_VISION_GATEWAY).replace(/\/$/, "");
|
|
48
|
+
const auth = tokenFor(pub);
|
|
49
|
+
return auth.Authorization ? { base: pub, model, auth, label: "0perator gateway" } : null;
|
|
50
|
+
}
|
|
51
|
+
/** A per-call `model` the agent may pick on the gateway: only our own vision routes (`vision`, `vision-jl2`,
|
|
52
|
+
* …). A catalog id (`vendor/model:free`) would send a private image to a third-party provider. */
|
|
53
|
+
export function gatewayModelAllowed(model) {
|
|
54
|
+
return /^vision(-[a-z0-9]+)*$/i.test(model);
|
|
55
|
+
}
|
|
@@ -46,8 +46,9 @@ export function questionKey(st, input, key, options, multiSelect = false) {
|
|
|
46
46
|
return { state: { ...st, buffer: st.buffer + input } };
|
|
47
47
|
return {};
|
|
48
48
|
}
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
// Esc or ctrl+c closes the menu = discuss, NEVER a silently-picked real answer (a /model picker leaves the model as it was).
|
|
50
|
+
if (key.escape || (key.ctrl && input.toLowerCase() === "c"))
|
|
51
|
+
return { resolve: DISCUSS };
|
|
51
52
|
const chatIndex = options.length; // 0-based index of the chat escape
|
|
52
53
|
const total = options.length + 1; // options + chat escape
|
|
53
54
|
if (key.upArrow) {
|
|
@@ -125,5 +126,5 @@ export function QuestionPrompt({ pending }) {
|
|
|
125
126
|
if (!pending)
|
|
126
127
|
return null;
|
|
127
128
|
const chatIndex = pending.options.length; // 0-based highlight index for the chat escape
|
|
128
|
-
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Box, { ref: qRef, children: _jsxs(Text, { color: "cyan", bold: true, children: ["? ", _jsx(Text, { color: "white", children: pending.question })] }) }), pending.options.map((o, i) => (_jsxs(Text, { children: [" ", st.mode === "choose" && st.highlight === i ? _jsx(Text, { color: "cyan", bold: true, children: "❯ " }) : _jsx(Text, { children: " " }), _jsx(Text, { color: "cyan", children: multi ? (st.selected?.includes(i) ? "[x]" : "[ ]") : `[${i + 1}]` }), " ", _jsx(Text, { bold: st.mode === "choose" && st.highlight === i, children: o })] }, i))), _jsxs(Text, { children: [" ", st.mode === "choose" && st.highlight === chatIndex ? _jsx(Text, { color: "cyan", bold: true, children: "❯ " }) : _jsx(Text, { children: " " }), _jsxs(Text, { color: "cyan", children: ["[", chatIndex + 1, "]"] }), " ", _jsx(Text, { color: "magenta", bold: st.mode === "choose" && st.highlight === chatIndex, children: CHAT_LABEL })] }), st.mode === "type" ? (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: "› " }), st.buffer, _jsx(Text, { color: "cyan", children: "\u258C" })] }), _jsx(Text, { dimColor: true, children: " type your reply · Enter to send · Esc for the menu" })] })) : multi ? (_jsxs(Text, { dimColor: true, children: [" ↑/↓ to move · Space (or 1-", chatIndex, ") to toggle · Enter to confirm · ", chatIndex + 1, " to type your own"] })) : (_jsxs(Text, { dimColor: true, children: [" ↑/↓ to move · Enter to pick · or press 1-", chatIndex + 1, " to jump"] }))] }));
|
|
129
|
+
return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Box, { ref: qRef, children: _jsxs(Text, { color: "cyan", bold: true, children: ["? ", _jsx(Text, { color: "white", children: pending.question })] }) }), pending.options.map((o, i) => (_jsxs(Text, { children: [" ", st.mode === "choose" && st.highlight === i ? _jsx(Text, { color: "cyan", bold: true, children: "❯ " }) : _jsx(Text, { children: " " }), _jsx(Text, { color: "cyan", children: multi ? (st.selected?.includes(i) ? "[x]" : "[ ]") : `[${i + 1}]` }), " ", _jsx(Text, { bold: st.mode === "choose" && st.highlight === i, children: o })] }, i))), _jsxs(Text, { children: [" ", st.mode === "choose" && st.highlight === chatIndex ? _jsx(Text, { color: "cyan", bold: true, children: "❯ " }) : _jsx(Text, { children: " " }), _jsxs(Text, { color: "cyan", children: ["[", chatIndex + 1, "]"] }), " ", _jsx(Text, { color: "magenta", bold: st.mode === "choose" && st.highlight === chatIndex, children: CHAT_LABEL })] }), st.mode === "type" ? (_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: "› " }), st.buffer, _jsx(Text, { color: "cyan", children: "\u258C" })] }), _jsx(Text, { dimColor: true, children: " type your reply · Enter to send · Esc for the menu" })] })) : multi ? (_jsxs(Text, { dimColor: true, children: [" ↑/↓ to move · Space (or 1-", chatIndex, ") to toggle · Enter to confirm · ", chatIndex + 1, " to type your own · Esc to close"] })) : (_jsxs(Text, { dimColor: true, children: [" ↑/↓ to move · Enter to pick · or press 1-", chatIndex + 1, " to jump · Esc to close"] }))] }));
|
|
129
130
|
}
|