@0perator/operator 0.1.333 → 0.1.335
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 +13 -2
- 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 +151 -0
- package/dist/tools/paths.js +11 -0
- package/dist/tools/read-path.js +18 -0
- package/dist/tools/registry.js +135 -46
- package/dist/tools/vision-gateway.js +55 -0
- package/dist/ui/QuestionPrompt.js +4 -3
- package/package.json +1 -1
package/dist/tools/registry.js
CHANGED
|
@@ -21,7 +21,10 @@ 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";
|
|
27
|
+
import { resolveReadPath } from "./read-path.js";
|
|
25
28
|
import { runMemoryTool } from "./memory.js";
|
|
26
29
|
import { documentGenerate } from "./document.js";
|
|
27
30
|
import { runCronTool } from "../autonomy/cron.js";
|
|
@@ -183,15 +186,26 @@ async function shellExec(args) {
|
|
|
183
186
|
const FILE_READ_DEFAULT_LIMIT_LINES = 2000;
|
|
184
187
|
const FILE_READ_MAX_CHARS = 40_000;
|
|
185
188
|
async function fileRead(args) {
|
|
186
|
-
const path =
|
|
189
|
+
const path = await resolveReadPath(str(args.path));
|
|
187
190
|
if (!path)
|
|
188
191
|
return "error: no path given";
|
|
189
192
|
const blocked = await deniedReadAsync(path); // sandbox on: refuse reads of credential paths (exfil guard)
|
|
190
193
|
if (blocked)
|
|
191
194
|
return `error: ${blocked}`;
|
|
192
195
|
try {
|
|
193
|
-
|
|
194
|
-
|
|
196
|
+
let src;
|
|
197
|
+
let head = "";
|
|
198
|
+
if (DOC_TEXT_EXTS.has(docExt(path))) {
|
|
199
|
+
const doc = await extractDocText(path);
|
|
200
|
+
if (!doc)
|
|
201
|
+
return `error: no text could be extracted from ${path} (a scanned or image-only document?) — use image_analyze to look at it`;
|
|
202
|
+
src = doc.text;
|
|
203
|
+
head = `[extracted text — ${describeDocText(path, doc)}; layout and images are not included]\n`;
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
207
|
+
src = await readFile(path, "utf8");
|
|
208
|
+
}
|
|
195
209
|
const lines = src.split("\n");
|
|
196
210
|
const offset = Number(args.offset ?? 0);
|
|
197
211
|
const explicitLimit = args.limit !== undefined;
|
|
@@ -203,7 +217,7 @@ async function fileRead(args) {
|
|
|
203
217
|
else if (!explicitLimit && offset + limit < lines.length) {
|
|
204
218
|
out += `\n…[showing lines ${offset + 1}-${offset + limit} of ${lines.length} — pass offset/limit to see the rest]`;
|
|
205
219
|
}
|
|
206
|
-
return out;
|
|
220
|
+
return head + out;
|
|
207
221
|
}
|
|
208
222
|
catch (e) {
|
|
209
223
|
return `error: ${e.message}`;
|
|
@@ -1665,12 +1679,22 @@ function visionTargets(settings) {
|
|
|
1665
1679
|
// Documents the vision model can't read as pixels — rendered to a PNG first (see renderDocForVision).
|
|
1666
1680
|
// macOS Quick Look (qlmanage) covers all of these with no extra install, so image_analyze works on a
|
|
1667
1681
|
// deck/PDF/page the same way it works on a photo.
|
|
1682
|
+
export const QUICKLOOK_TIMEOUT_MS = 30_000;
|
|
1683
|
+
/** A local media path as an ABSOLUTE path before it reaches qlmanage/sips/ffmpeg as an argument: a relative "path"
|
|
1684
|
+
* starting with "-" would be read as an option (sips has options that write files). URLs pass through. */
|
|
1685
|
+
async function absMediaPath(p) {
|
|
1686
|
+
if (/^https?:\/\//.test(p))
|
|
1687
|
+
return p;
|
|
1688
|
+
const { resolve } = await nodeImport("node:path");
|
|
1689
|
+
return resolve(p);
|
|
1690
|
+
}
|
|
1668
1691
|
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
1692
|
/** If `path` is a document (deck/PDF/page/sheet), render its first page to a PNG with macOS Quick Look and
|
|
1670
1693
|
* return that PNG path — so the vision pipeline SEES the document. Non-documents pass straight through; a
|
|
1671
1694
|
* render failure also passes through (the caller then fails with a clear "couldn't read" message). Quick
|
|
1672
1695
|
* Look only renders the first page, so multi-page docs are analyzed by their opening page. */
|
|
1673
1696
|
async function renderDocForVision(path) {
|
|
1697
|
+
path = await absMediaPath(path);
|
|
1674
1698
|
const ext = (path.split(".").pop() || "").toLowerCase();
|
|
1675
1699
|
if (!VISION_DOC_EXTS.has(ext))
|
|
1676
1700
|
return path;
|
|
@@ -1682,7 +1706,8 @@ async function renderDocForVision(path) {
|
|
|
1682
1706
|
const { promisify } = await nodeImport("node:util");
|
|
1683
1707
|
const pexec = promisify(execFile);
|
|
1684
1708
|
const dir = await mkdtemp(join(os.tmpdir(), "axe-doc-"));
|
|
1685
|
-
|
|
1709
|
+
// Quick Look can wait forever (a nonexistent or unreadable file hung it 47 min on 2026-10-28): bound it.
|
|
1710
|
+
await pexec("qlmanage", ["-t", "-s", "1600", "-o", dir, path], { timeout: QUICKLOOK_TIMEOUT_MS, killSignal: "SIGKILL" });
|
|
1686
1711
|
const out = join(dir, `${basename(path)}.png`); // qlmanage names it <basename>.<ext>.png
|
|
1687
1712
|
await access(out); // throws if Quick Look produced nothing → fall through
|
|
1688
1713
|
return out;
|
|
@@ -1692,6 +1717,7 @@ async function renderDocForVision(path) {
|
|
|
1692
1717
|
}
|
|
1693
1718
|
}
|
|
1694
1719
|
async function visionImageDataUrl(image) {
|
|
1720
|
+
image = await absMediaPath(image);
|
|
1695
1721
|
if (/^https?:\/\//.test(image))
|
|
1696
1722
|
return image;
|
|
1697
1723
|
image = await renderDocForVision(image); // a document becomes a rendered PNG; an image is unchanged
|
|
@@ -1747,13 +1773,73 @@ async function visionImageDataUrl(image) {
|
|
|
1747
1773
|
catch { /* any resize failure → original bytes (correctness over speed) */ }
|
|
1748
1774
|
return `data:${mime};base64,${buf.toString("base64")}`;
|
|
1749
1775
|
}
|
|
1750
|
-
/**
|
|
1751
|
-
|
|
1752
|
-
|
|
1776
|
+
/** One OpenAI-vision chat POST to `base` (…/v1). Never throws: the outcome says what happened. */
|
|
1777
|
+
async function postVision(base, auth, model, parts, args, timeout) {
|
|
1778
|
+
const ctrl = new AbortController();
|
|
1779
|
+
const timer = setTimeout(() => ctrl.abort(), timeout);
|
|
1780
|
+
try {
|
|
1781
|
+
const res = await fetch(`${base}/chat/completions`, {
|
|
1782
|
+
method: "POST", signal: ctrl.signal,
|
|
1783
|
+
headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...auth },
|
|
1784
|
+
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 }),
|
|
1785
|
+
});
|
|
1786
|
+
if (!res.ok)
|
|
1787
|
+
return { status: res.status, body: (await res.text().catch(() => "")).slice(0, 180) };
|
|
1788
|
+
const j = (await res.json().catch(() => ({})));
|
|
1789
|
+
return { text: j.choices?.[0]?.message?.content?.trim() || "" };
|
|
1790
|
+
}
|
|
1791
|
+
catch (e) {
|
|
1792
|
+
const aborted = e?.name === "AbortError";
|
|
1793
|
+
return { aborted, error: aborted ? `timed out after ${Math.round(timeout / 1000)}s` : String(e?.message ?? e) };
|
|
1794
|
+
}
|
|
1795
|
+
finally {
|
|
1796
|
+
clearTimeout(timer);
|
|
1797
|
+
}
|
|
1798
|
+
}
|
|
1799
|
+
/** The gateway path: one backend, the router owns failover. Returns the answer, throws a final error, or
|
|
1800
|
+
* returns `fallthrough` when the gateway can't serve vision at all (unreachable / no healthy leg) so the
|
|
1801
|
+
* caller may try the direct chain. */
|
|
1802
|
+
async function visionViaGateway(gw, parts, args, timeout) {
|
|
1803
|
+
// A per-call model is honored only when it names one of our own vision routes; anything else (an old
|
|
1804
|
+
// direct-server id, a free catalog model) would bypass the route's privacy decision, so the route is used.
|
|
1805
|
+
const model = gatewayModelAllowed(str(args.model)) ? str(args.model) : gw.model;
|
|
1806
|
+
let last = "";
|
|
1807
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1808
|
+
const r = await postVision(gw.base, gw.auth, model, parts, args, timeout);
|
|
1809
|
+
if (r.text)
|
|
1810
|
+
return { text: r.text };
|
|
1811
|
+
if (r.text === "") {
|
|
1812
|
+
last = `${gw.label} returned no text`;
|
|
1813
|
+
continue;
|
|
1814
|
+
}
|
|
1815
|
+
if (r.status === 502 || r.status === 503 || r.status === 504)
|
|
1816
|
+
return { fallthrough: `${gw.label} ${gw.base} returned ${r.status}${r.body ? ` — ${r.body}` : ""}` };
|
|
1817
|
+
if (r.status)
|
|
1818
|
+
throw new Error(`${gw.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`);
|
|
1819
|
+
if (r.aborted)
|
|
1820
|
+
throw new Error(`${gw.label} ${r.error}`);
|
|
1821
|
+
return { fallthrough: `${gw.label} ${gw.base} unreachable (${r.error})` };
|
|
1822
|
+
}
|
|
1823
|
+
throw new Error(last);
|
|
1824
|
+
}
|
|
1825
|
+
/** Send a vision chat. Through the gateway's `vision` route when one resolves (vision-gateway.ts); the
|
|
1826
|
+
* direct endpoint chain below runs only for an owner pin or when no gateway can serve vision: skip any
|
|
1827
|
+
* target in cooldown, /health-gate local targets, time each independently, retry once on an empty body,
|
|
1828
|
+
* and on timeout / 402 / 429 / auth-error mark the target unhealthy for a TTL and fall through to the next.
|
|
1829
|
+
* Throws with the last error only when all are exhausted. */
|
|
1753
1830
|
async function visionComplete(parts, args, defaultTimeoutMs) {
|
|
1754
1831
|
const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
|
|
1755
|
-
const
|
|
1832
|
+
const settings = loadSettings();
|
|
1756
1833
|
const timeout = Math.max(5_000, Number(args.timeout_ms ?? defaultTimeoutMs));
|
|
1834
|
+
const gw = await resolveVisionGateway(settings);
|
|
1835
|
+
let gatewayNote = "";
|
|
1836
|
+
if (gw) {
|
|
1837
|
+
const g = await visionViaGateway(gw, parts, args, timeout);
|
|
1838
|
+
if ("text" in g)
|
|
1839
|
+
return g.text;
|
|
1840
|
+
gatewayNote = `${g.fallthrough}; `;
|
|
1841
|
+
}
|
|
1842
|
+
const targets = visionTargets(settings);
|
|
1757
1843
|
const now = () => Date.now();
|
|
1758
1844
|
let lastErr = `no vision service reachable (tried ${targets.map((t) => t.url).join(", ")})`;
|
|
1759
1845
|
for (const t of targets) {
|
|
@@ -1776,41 +1862,27 @@ async function visionComplete(parts, args, defaultTimeoutMs) {
|
|
|
1776
1862
|
}
|
|
1777
1863
|
const model = str(args.model) || t.model || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
|
|
1778
1864
|
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) {
|
|
1865
|
+
const r = await postVision(`${t.url}/v1`, t.auth, model, parts, args, timeout);
|
|
1866
|
+
if (r.text)
|
|
1867
|
+
return r.text;
|
|
1868
|
+
if (r.text === "") {
|
|
1869
|
+
lastErr = `${t.label} returned no text`;
|
|
1870
|
+
continue;
|
|
1871
|
+
} // empty → retry once, then next endpoint
|
|
1872
|
+
if (r.status) {
|
|
1873
|
+
if (r.status === 401 || r.status === 402 || r.status === 403 || r.status === 429 || /credit|insufficient|quota|billing/i.test(r.body || ""))
|
|
1804
1874
|
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
}
|
|
1808
|
-
finally {
|
|
1809
|
-
clearTimeout(timer);
|
|
1875
|
+
lastErr = `${t.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`;
|
|
1876
|
+
break; // non-200 → next endpoint
|
|
1810
1877
|
}
|
|
1878
|
+
lastErr = `${t.label}${r.aborted ? " " : ": "}${r.error}`;
|
|
1879
|
+
if (r.aborted) {
|
|
1880
|
+
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1881
|
+
break;
|
|
1882
|
+
} // busy/slow → cooldown + next endpoint
|
|
1811
1883
|
}
|
|
1812
1884
|
}
|
|
1813
|
-
throw new Error(lastErr);
|
|
1885
|
+
throw new Error(gatewayNote + lastErr);
|
|
1814
1886
|
}
|
|
1815
1887
|
// Uncensoring system prompt for the vision model (owner's private system): the engine-level unrestricted
|
|
1816
1888
|
// layer only sees chat() turns, not these direct vision calls, so the analyze side gets its own one-line
|
|
@@ -1885,10 +1957,26 @@ async function imageInspect(args) {
|
|
|
1885
1957
|
}
|
|
1886
1958
|
}
|
|
1887
1959
|
async function imageAnalyze(args) {
|
|
1888
|
-
const
|
|
1960
|
+
const raw = str(args.image);
|
|
1961
|
+
const image = /^https?:\/\//.test(raw) ? raw : await resolveReadPath(raw);
|
|
1889
1962
|
if (!image)
|
|
1890
1963
|
return "error: image_analyze needs an image or document (a local path or an http(s) url)";
|
|
1964
|
+
if (!/^https?:\/\//.test(image)) {
|
|
1965
|
+
const blocked = await deniedReadAsync(image); // same credential-path guard as file_read: it now returns document TEXT
|
|
1966
|
+
if (blocked)
|
|
1967
|
+
return `error: ${blocked}`;
|
|
1968
|
+
}
|
|
1891
1969
|
const question = str(args.question) || "Describe this image in detail.";
|
|
1970
|
+
// A document is read by its TEXT first (every page, exact characters); only a document with no text layer
|
|
1971
|
+
// (a scan) — or an explicit as_image — goes to vision as a rendered first page.
|
|
1972
|
+
const asImage = args.as_image === true || str(args.as_image) === "true";
|
|
1973
|
+
if (!asImage && !/^https?:\/\//.test(image) && DOC_TEXT_EXTS.has(docExt(image))) {
|
|
1974
|
+
const doc = await extractDocText(image);
|
|
1975
|
+
if (doc) {
|
|
1976
|
+
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;
|
|
1977
|
+
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}`;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1892
1980
|
let imageUrl;
|
|
1893
1981
|
try {
|
|
1894
1982
|
imageUrl = await visionImageDataUrl(image); // downscales a large local image first; http(s) passes through
|
|
@@ -1908,7 +1996,7 @@ async function imageAnalyze(args) {
|
|
|
1908
1996
|
// (same Qwen2-VL endpoint, multi-image) describes what happens. Needs ffmpeg on PATH; verified the model
|
|
1909
1997
|
// synthesizes motion from ordered frames ("calm ocean with gentle waves, golden hue").
|
|
1910
1998
|
async function videoAnalyze(args) {
|
|
1911
|
-
const video = str(args.video);
|
|
1999
|
+
const video = str(args.video) ? await absMediaPath(await resolveReadPath(str(args.video))) : "";
|
|
1912
2000
|
if (!video)
|
|
1913
2001
|
return "error: video_analyze needs a video (a local path or an http(s) url)";
|
|
1914
2002
|
const question = str(args.question) || "These frames are sampled in order across a video. Describe what happens across the video.";
|
|
@@ -1958,7 +2046,7 @@ async function videoAnalyze(args) {
|
|
|
1958
2046
|
}
|
|
1959
2047
|
catch (e) {
|
|
1960
2048
|
const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
|
|
1961
|
-
return `error: video_analyze failed (${msg}) — needs ffmpeg on PATH + the
|
|
2049
|
+
return `error: video_analyze failed (${msg}) — needs ffmpeg on PATH + a vision backend (the gateway vision route)`;
|
|
1962
2050
|
}
|
|
1963
2051
|
finally {
|
|
1964
2052
|
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
@@ -2528,12 +2616,13 @@ const TOOLS = [
|
|
|
2528
2616
|
},
|
|
2529
2617
|
{
|
|
2530
2618
|
name: "image_analyze", safe: true,
|
|
2531
|
-
description: "Analyze/describe an image
|
|
2619
|
+
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
2620
|
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/
|
|
2621
|
+
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
2622
|
question: { type: "string", description: 'what to ask about the image (default "Describe this image in detail.")' },
|
|
2535
2623
|
max_tokens: { type: "number", description: "optional cap on answer length; omit for a full, uncapped description" },
|
|
2536
2624
|
timeout_ms: { type: "number", description: "default 120000" },
|
|
2625
|
+
as_image: { type: "boolean", description: "for a document: skip text extraction and look at its rendered first page (layout, charts, pictures)" },
|
|
2537
2626
|
}, required: ["image"] },
|
|
2538
2627
|
run: imageAnalyze,
|
|
2539
2628
|
},
|
|
@@ -2547,7 +2636,7 @@ const TOOLS = [
|
|
|
2547
2636
|
},
|
|
2548
2637
|
{
|
|
2549
2638
|
name: "video_analyze", safe: true,
|
|
2550
|
-
description: "Analyze/describe a VIDEO
|
|
2639
|
+
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
2640
|
parameters: { type: "object", properties: {
|
|
2552
2641
|
video: { type: "string", description: "a local file path or an http(s) url to the video" },
|
|
2553
2642
|
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
|
}
|