@0perator/operator 0.1.360-next.1 → 0.1.360-next.2
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/autonomy/session-factory.js +6 -2
- package/dist/browser/session.js +61 -13
- package/dist/cli.js +87 -58
- package/dist/config/settings.js +27 -6
- package/dist/config/skills-index.js +4 -0
- package/dist/engine/aurora.js +19 -10
- package/dist/engine/speed-compaction.js +37 -0
- package/dist/gateway-cli.js +14 -5
- package/dist/router/models.js +46 -12
- package/dist/services/preflight.js +31 -8
- package/dist/session.js +48 -7
- package/dist/tools/registry.js +230 -45
- package/dist/tools/vision-media.js +162 -0
- package/dist/ui/modelPicker.js +26 -8
- package/dist/update.js +28 -3
- package/package.json +1 -1
package/dist/tools/registry.js
CHANGED
|
@@ -26,6 +26,7 @@ import { findFiles, FIND_FILES_DEFAULT_LIMIT, FIND_FILES_MAX_LIMIT, KINDS } from
|
|
|
26
26
|
import { formatGitStatus } from "./git-status.js";
|
|
27
27
|
import { DOC_TEXT_EXTS, describeDocText, docExt, extractDocText } from "./doc-text.js";
|
|
28
28
|
import { askVision, visionGateways, VISION_LIMITS } from "./vision-gateway.js";
|
|
29
|
+
import { DESIGN_PROBE_JS, DESIGN_QUESTION, MEDIA_CAPS, downloadVideoPage, evenTimes, fmtTime, formatDesignRead, grabFrames, isVideoPageUrl, parseTimestamps } from "./vision-media.js";
|
|
29
30
|
import { expandPath, assertContentSearchScope, assertShellHomeWideSearch, assertShellBlindDownload } from "./paths.js";
|
|
30
31
|
import { resolveReadPath } from "./read-path.js";
|
|
31
32
|
import { recordRead, getRead, forgetReads, seenView } from "./read-ledger.js"; // per-session read-state (pure, node-free — stays out of the neutral graph)
|
|
@@ -44,7 +45,7 @@ import { BYO_PRESETS } from "../router/models.js";
|
|
|
44
45
|
const BYO_DELEGATE_PROVIDERS = Object.keys(BYO_PRESETS).join(", ");
|
|
45
46
|
import { runSessionRewind } from "../memory/session-rewind.js";
|
|
46
47
|
import { runSkillCatalog } from "../skills/catalogue.js";
|
|
47
|
-
import { runBrowser, runBrowserRead } from "../browser/session.js";
|
|
48
|
+
import { runBrowser, runBrowserRead, pageCaptureHooks } from "../browser/session.js";
|
|
48
49
|
import { deniedWriteAsync, deniedReadAsync, wrapShell } from "./sandbox.js";
|
|
49
50
|
import { ensureSearxng, noteSearxngUsed } from "./searxng.js";
|
|
50
51
|
// execFile helper lives in ./exec (shared with computer.ts — one copy, not two).
|
|
@@ -1856,11 +1857,56 @@ async function flatColour(pexec, image, bmp) {
|
|
|
1856
1857
|
}
|
|
1857
1858
|
// Only a file this light for its pixel count is checked for flatness: a real picture never pays the extra sips call.
|
|
1858
1859
|
const BLANK_BYTES_PER_PX = 0.1;
|
|
1860
|
+
const IMAGE_URL_MAX_BYTES = 25_000_000;
|
|
1861
|
+
// A vision server may not fetch URLs (llama-server built without TLS answers "HTTPS is not supported"), so an
|
|
1862
|
+
// http(s) image is downloaded here and sent as bytes, like a local file.
|
|
1863
|
+
async function fetchImageToTemp(url) {
|
|
1864
|
+
const res = await fetch(url, { signal: AbortSignal.timeout(30_000), headers: { "user-agent": "Mozilla/5.0 (Operator image_analyze)" } });
|
|
1865
|
+
if (!res.ok)
|
|
1866
|
+
throw new Error(`${url} returned ${res.status}`);
|
|
1867
|
+
const type = (res.headers.get("content-type") || "").split(";")[0].trim();
|
|
1868
|
+
if (type && !type.startsWith("image/"))
|
|
1869
|
+
throw new Error(`${url} is ${type}, not an image`);
|
|
1870
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
1871
|
+
if (buf.length > IMAGE_URL_MAX_BYTES)
|
|
1872
|
+
throw new Error(`${url} is ${buf.length} bytes (cap ${IMAGE_URL_MAX_BYTES})`);
|
|
1873
|
+
const ext = type === "image/jpeg" ? "jpg" : type === "image/webp" ? "webp" : type === "image/gif" ? "gif" : "png";
|
|
1874
|
+
const os = await nodeImport("node:os");
|
|
1875
|
+
const { join } = await nodeImport("node:path");
|
|
1876
|
+
const { mkdtemp, writeFile } = await nodeImport("node:fs/promises");
|
|
1877
|
+
const file = join(await mkdtemp(join(os.tmpdir(), "axe-iu-")), `image.${ext}`);
|
|
1878
|
+
await writeFile(file, buf);
|
|
1879
|
+
return file;
|
|
1880
|
+
}
|
|
1881
|
+
// A transparent image is flattened onto white first: measured 11/25, the same Google wordmark read as "Coca-Cola"
|
|
1882
|
+
// with its alpha channel and as "the Google logo" on white. No ffprobe/ffmpeg, or no alpha: the image is unchanged.
|
|
1883
|
+
async function flattenAlpha(image) {
|
|
1884
|
+
if (!/\.(png|webp|gif)$/i.test(image))
|
|
1885
|
+
return image;
|
|
1886
|
+
try {
|
|
1887
|
+
const { execFile } = await nodeImport("node:child_process");
|
|
1888
|
+
const { promisify } = await nodeImport("node:util");
|
|
1889
|
+
const pexec = promisify(execFile);
|
|
1890
|
+
const { stdout } = await pexec("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=pix_fmt", "-of", "csv=p=0", image]);
|
|
1891
|
+
if (!/a|pal8/.test(stdout.trim()))
|
|
1892
|
+
return image;
|
|
1893
|
+
const os = await nodeImport("node:os");
|
|
1894
|
+
const { join } = await nodeImport("node:path");
|
|
1895
|
+
const { mkdtemp } = await nodeImport("node:fs/promises");
|
|
1896
|
+
const out = join(await mkdtemp(join(os.tmpdir(), "axe-ia-")), "flat.png");
|
|
1897
|
+
await pexec("ffmpeg", ["-v", "error", "-y", "-i", image, "-filter_complex", "color=white,format=rgb24[bg];[bg][0:v]scale2ref[bg][fg];[bg][fg]overlay=shortest=1:format=auto,format=rgb24", "-frames:v", "1", out]);
|
|
1898
|
+
return out;
|
|
1899
|
+
}
|
|
1900
|
+
catch {
|
|
1901
|
+
return image;
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1859
1904
|
async function visionImageDataUrl(image, lim) {
|
|
1860
1905
|
image = await absMediaPath(image);
|
|
1861
1906
|
if (/^https?:\/\//.test(image))
|
|
1862
|
-
|
|
1907
|
+
image = await fetchImageToTemp(image);
|
|
1863
1908
|
image = await renderDocForVision(image); // a document becomes a rendered PNG; an image is unchanged
|
|
1909
|
+
image = await flattenAlpha(image);
|
|
1864
1910
|
const { readFile } = await nodeImport("node:fs/promises");
|
|
1865
1911
|
const orig = await readFile(image).catch(() => null);
|
|
1866
1912
|
if (!orig)
|
|
@@ -1968,6 +2014,13 @@ async function imageInspect(args) {
|
|
|
1968
2014
|
const image = str(args.image);
|
|
1969
2015
|
if (!image)
|
|
1970
2016
|
return "error: image_inspect needs an image (a local path or an http(s) url)";
|
|
2017
|
+
const facts = await imageFacts(image);
|
|
2018
|
+
if (typeof facts === "string")
|
|
2019
|
+
return `error: image_inspect ${facts}`;
|
|
2020
|
+
return Object.entries(facts).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`).join("\n");
|
|
2021
|
+
}
|
|
2022
|
+
/** image_inspect's measurements as an object, or why there are none ("could not …" / "— <reason> (needs …)"). */
|
|
2023
|
+
async function imageFacts(image) {
|
|
1971
2024
|
const os = await nodeImport("node:os");
|
|
1972
2025
|
const { join } = await nodeImport("node:path");
|
|
1973
2026
|
const { mkdtemp, writeFile, rm, stat } = await nodeImport("node:fs/promises");
|
|
@@ -1980,31 +2033,33 @@ async function imageInspect(args) {
|
|
|
1980
2033
|
if (/^https?:\/\//.test(image)) {
|
|
1981
2034
|
const res = await fetch(image).catch(() => null);
|
|
1982
2035
|
if (!res || !res.ok)
|
|
1983
|
-
return `
|
|
2036
|
+
return `could not fetch ${image}`;
|
|
1984
2037
|
path = join(dir, "img");
|
|
1985
2038
|
await writeFile(path, Buffer.from(await res.arrayBuffer()));
|
|
1986
2039
|
}
|
|
1987
2040
|
else if (!(await stat(path).catch(() => null))) {
|
|
1988
|
-
return `
|
|
2041
|
+
return `could not read a file at ${image}`;
|
|
1989
2042
|
}
|
|
1990
2043
|
const script = join(dir, "inspect.py");
|
|
1991
2044
|
await writeFile(script, IMAGE_INSPECT_PY);
|
|
1992
2045
|
const { stdout } = await pexec("python3", ["-I", script, path]);
|
|
1993
|
-
|
|
1994
|
-
return Object.entries(facts).map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`).join("\n");
|
|
2046
|
+
return JSON.parse(stdout.trim());
|
|
1995
2047
|
}
|
|
1996
2048
|
catch (e) {
|
|
1997
|
-
return
|
|
2049
|
+
return `— ${String(e?.message ?? e)} (needs python3 + Pillow; for SEMANTIC questions use image_analyze instead)`;
|
|
1998
2050
|
}
|
|
1999
2051
|
finally {
|
|
2000
2052
|
await rm(dir, { recursive: true, force: true }).catch(() => { });
|
|
2001
2053
|
}
|
|
2002
2054
|
}
|
|
2055
|
+
const flag = (v) => v === true || str(v) === "true";
|
|
2003
2056
|
async function imageAnalyze(args) {
|
|
2057
|
+
if (str(args.page))
|
|
2058
|
+
return analyzePage(args);
|
|
2004
2059
|
const raw = str(args.image);
|
|
2005
2060
|
const image = /^https?:\/\//.test(raw) ? raw : await resolveReadPath(raw);
|
|
2006
2061
|
if (!image)
|
|
2007
|
-
return "error: image_analyze needs an image or document (a local path or an http(s) url)";
|
|
2062
|
+
return "error: image_analyze needs an image or document (a local path or an http(s) url), or a web `page` url";
|
|
2008
2063
|
if (!/^https?:\/\//.test(image)) {
|
|
2009
2064
|
const blocked = await deniedReadAsync(image); // same credential-path guard as file_read: it now returns document TEXT
|
|
2010
2065
|
if (blocked)
|
|
@@ -2027,29 +2082,104 @@ async function imageAnalyze(args) {
|
|
|
2027
2082
|
// downscales a large local image first; http(s) passes through
|
|
2028
2083
|
img = await visionImageDataUrl(image, { maxEdge: visionLimit(v, "maxEdge", 256), maxBytes: visionLimit(v, "maxBytes", 100_000) });
|
|
2029
2084
|
}
|
|
2030
|
-
catch {
|
|
2031
|
-
return
|
|
2085
|
+
catch (e) {
|
|
2086
|
+
return /^https?:\/\//.test(image)
|
|
2087
|
+
? `error: image_analyze could not download ${image}: ${e.message}`
|
|
2088
|
+
: `error: image_analyze could not read a file at ${image} (pass a local path or an http(s) url)`;
|
|
2032
2089
|
}
|
|
2033
2090
|
if ("blank" in img)
|
|
2034
2091
|
return `error: image is blank (${img.blank}) — ${image}. Nothing to analyze; capture it again.`;
|
|
2035
|
-
const
|
|
2092
|
+
const design = flag(args.design);
|
|
2093
|
+
const ask = design ? designQuestion(args) : question;
|
|
2094
|
+
const parts = [{ type: "text", text: ask }, { type: "image_url", image_url: { url: img.url } }];
|
|
2036
2095
|
try {
|
|
2037
|
-
|
|
2096
|
+
const seen = await visionComplete(parts, args, v);
|
|
2097
|
+
if (!design)
|
|
2098
|
+
return seen;
|
|
2099
|
+
const facts = await imageFacts(image);
|
|
2100
|
+
return formatDesignRead({ source: image, seen, ...measuredPixels(facts) });
|
|
2038
2101
|
}
|
|
2039
2102
|
catch (e) {
|
|
2040
2103
|
return `error: ${String(e?.message ?? e)}`;
|
|
2041
2104
|
}
|
|
2042
2105
|
}
|
|
2106
|
+
const designQuestion = (args) => str(args.question) ? `${DESIGN_QUESTION} Also answer: ${str(args.question)}` : DESIGN_QUESTION;
|
|
2107
|
+
function measuredPixels(facts) {
|
|
2108
|
+
if (typeof facts === "string")
|
|
2109
|
+
return { paletteNote: `image_inspect ${facts}` };
|
|
2110
|
+
const palette = Array.isArray(facts.dominant_colors) ? facts.dominant_colors : [];
|
|
2111
|
+
return { size: `${facts.width}×${facts.height} px`, palette, ...(palette.length ? {} : { paletteNote: "Pillow returned no colours" }) };
|
|
2112
|
+
}
|
|
2113
|
+
// image_analyze `page`: render a web page in the `browser` tool's headless Chrome (a tab of its own), save the
|
|
2114
|
+
// screenshot, then ask vision. A long full-page capture goes to vision as viewport slices, top to bottom. `design`
|
|
2115
|
+
// adds what the page's CSS computes and the screenshot's real palette above the model's read.
|
|
2116
|
+
const PAGE_VIEW = { width: 1280, height: 800, tiles: 4 };
|
|
2117
|
+
async function analyzePage(args) {
|
|
2118
|
+
const page = str(args.page);
|
|
2119
|
+
if (!/^https?:\/\//.test(page))
|
|
2120
|
+
return "error: page must be an http(s) url (a local file goes in `image`)";
|
|
2121
|
+
const design = flag(args.design);
|
|
2122
|
+
let shot;
|
|
2123
|
+
try {
|
|
2124
|
+
shot = await pageCaptureHooks.capture(page, { ...PAGE_VIEW, fullPage: flag(args.full_page), probe: design ? DESIGN_PROBE_JS : undefined });
|
|
2125
|
+
}
|
|
2126
|
+
catch (e) {
|
|
2127
|
+
return `error: could not render ${page} — ${String(e?.message ?? e)}`;
|
|
2128
|
+
}
|
|
2129
|
+
const cut = shot.height < shot.fullHeight && flag(args.full_page) ? `, cut at ${shot.height} of ${shot.fullHeight} px` : "";
|
|
2130
|
+
const head = `page ${shot.finalUrl}${shot.status && shot.status >= 400 ? ` (HTTP ${shot.status})` : ""} — "${shot.title}"\nscreenshot ${shot.path} (${shot.width}×${shot.height}${cut})`;
|
|
2131
|
+
if (shot.loadError)
|
|
2132
|
+
return `error: ${page} did not load (${shot.loadError}). Screenshot of what Chrome showed: ${shot.path}`;
|
|
2133
|
+
const v = await visionSettings();
|
|
2134
|
+
const images = shot.tiles.length ? shot.tiles : [shot.path];
|
|
2135
|
+
// Several slices are read in one request: smaller slices keep it inside a CPU vision server's window and time.
|
|
2136
|
+
const lim = { maxEdge: Math.min(visionLimit(v, "maxEdge", 256), images.length > 1 ? 1024 : Infinity), maxBytes: visionLimit(v, "maxBytes", 100_000) };
|
|
2137
|
+
if (images.length > 1 && args.timeout_ms === undefined)
|
|
2138
|
+
args = { ...args, timeout_ms: 300_000 };
|
|
2139
|
+
const question = design ? designQuestion(args) : str(args.question) || "Describe this web page as rendered: what it is, its layout, and the visible text that matters.";
|
|
2140
|
+
const parts = [{ type: "text", text: images.length > 1 ? `${question} (${images.length} slices of one page, top to bottom)` : question }];
|
|
2141
|
+
for (const p of images) {
|
|
2142
|
+
const img = await visionImageDataUrl(p, lim).catch(() => null);
|
|
2143
|
+
if (!img)
|
|
2144
|
+
return `${head}\nerror: could not read the screenshot back`;
|
|
2145
|
+
if ("blank" in img)
|
|
2146
|
+
return `${head}\nerror: the page rendered blank (${img.blank}) — nothing to analyze`;
|
|
2147
|
+
parts.push({ type: "image_url", image_url: { url: img.url } });
|
|
2148
|
+
}
|
|
2149
|
+
let seen;
|
|
2150
|
+
try {
|
|
2151
|
+
seen = await visionComplete(parts, args, v);
|
|
2152
|
+
}
|
|
2153
|
+
catch (e) {
|
|
2154
|
+
return `${head}\nerror: ${String(e?.message ?? e)}`;
|
|
2155
|
+
}
|
|
2156
|
+
if (!design)
|
|
2157
|
+
return `${head}\n\n${seen}`;
|
|
2158
|
+
const css = shot.probe && typeof shot.probe === "object" ? shot.probe : undefined;
|
|
2159
|
+
const pixels = measuredPixels(await imageFacts(shot.path));
|
|
2160
|
+
return `${head}\n\n${formatDesignRead({ source: shot.finalUrl, seen, ...pixels, ...(css ? { css } : {}) })}`;
|
|
2161
|
+
}
|
|
2043
2162
|
// video_analyze — real video understanding: ffmpeg samples frames evenly across the clip, then the VL model
|
|
2044
2163
|
// (same Qwen2-VL endpoint, multi-image) describes what happens. Needs ffmpeg on PATH; verified the model
|
|
2045
2164
|
// synthesizes motion from ordered frames ("calm ocean with gentle waves, golden hue").
|
|
2165
|
+
// A video PAGE link (YouTube, Vimeo, … or any url that answers HTML) resolves to a file through yt-dlp, inside
|
|
2166
|
+
// MEDIA_CAPS; frames are single ffmpeg seeks at `timestamps` or evenly spaced times, so a long video is never decoded
|
|
2167
|
+
// whole. `save_frames` / `analyze: false` keep the frames as PNGs in Operator's cache and return their paths;
|
|
2168
|
+
// analyze: false asks no model.
|
|
2046
2169
|
async function videoAnalyze(args) {
|
|
2047
|
-
const
|
|
2170
|
+
const raw = str(args.video);
|
|
2171
|
+
const isUrl = /^https?:\/\//.test(raw);
|
|
2172
|
+
const video = !raw ? "" : isUrl ? raw : await absMediaPath(await resolveReadPath(raw));
|
|
2048
2173
|
if (!video)
|
|
2049
|
-
return "error: video_analyze needs a video (a local path
|
|
2174
|
+
return "error: video_analyze needs a video (a local path, an http(s) video url, or a video page link)";
|
|
2050
2175
|
const question = str(args.question) || "These frames are sampled in order across a video. Describe what happens across the video.";
|
|
2051
|
-
const
|
|
2052
|
-
|
|
2176
|
+
const times = parseTimestamps(args.timestamps);
|
|
2177
|
+
if (typeof times === "string")
|
|
2178
|
+
return `error: video_analyze ${times}`;
|
|
2179
|
+
const nFrames = times.length || Math.max(2, Math.min(Number(args.frames) || 8, MEDIA_CAPS.maxFrames));
|
|
2180
|
+
const analyze = args.analyze !== false && str(args.analyze) !== "false";
|
|
2181
|
+
const caps = { maxDurationS: Number(args.max_duration_s) > 0 ? Number(args.max_duration_s) : MEDIA_CAPS.maxDurationS, maxBytes: MEDIA_CAPS.maxBytes };
|
|
2182
|
+
const { mkdtemp, mkdir, readFile, rm, writeFile, readdir } = await nodeImport("node:fs/promises");
|
|
2053
2183
|
const os = await nodeImport("node:os");
|
|
2054
2184
|
const { join } = await nodeImport("node:path");
|
|
2055
2185
|
const { execFile } = await nodeImport("node:child_process");
|
|
@@ -2058,39 +2188,87 @@ async function videoAnalyze(args) {
|
|
|
2058
2188
|
const dir = await mkdtemp(join(os.tmpdir(), "axe-va-"));
|
|
2059
2189
|
try {
|
|
2060
2190
|
let src = video;
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2191
|
+
let title = "";
|
|
2192
|
+
if (isUrl) {
|
|
2193
|
+
let page = isVideoPageUrl(video);
|
|
2194
|
+
if (!page) {
|
|
2195
|
+
const r = await fetch(video).catch(() => null);
|
|
2196
|
+
if (!r || !r.ok)
|
|
2197
|
+
return `error: video_analyze could not fetch ${video}${r ? ` (HTTP ${r.status})` : ""}`;
|
|
2198
|
+
page = /text\/html/i.test(r.headers.get("content-type") ?? "");
|
|
2199
|
+
const size = Number(r.headers.get("content-length")) || 0;
|
|
2200
|
+
if (page || size > caps.maxBytes)
|
|
2201
|
+
await r.body?.cancel().catch(() => { });
|
|
2202
|
+
if (!page && size > caps.maxBytes)
|
|
2203
|
+
return `error: ${video} is ${Math.round(size / 1e6)} MB, over the ${caps.maxBytes / 1e6} MB cap`;
|
|
2204
|
+
if (!page) {
|
|
2205
|
+
src = join(dir, "src.mp4");
|
|
2206
|
+
await writeFile(src, Buffer.from(await r.arrayBuffer()));
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
if (page) {
|
|
2210
|
+
const got = await downloadVideoPage(video, dir, caps);
|
|
2211
|
+
if ("error" in got)
|
|
2212
|
+
return `error: ${got.error}`;
|
|
2213
|
+
src = got.path;
|
|
2214
|
+
title = got.title;
|
|
2215
|
+
}
|
|
2074
2216
|
}
|
|
2075
|
-
|
|
2217
|
+
let duration = 0;
|
|
2076
2218
|
try {
|
|
2077
|
-
await pexec("
|
|
2219
|
+
const { stdout } = await pexec("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", src]);
|
|
2220
|
+
duration = parseFloat(stdout.trim()) || 0;
|
|
2221
|
+
}
|
|
2222
|
+
catch { /* ffprobe missing → sample at a default rate below */ }
|
|
2223
|
+
const label = `${title ? `"${title}" ` : ""}${fmtTime(duration)}`;
|
|
2224
|
+
const late = times.filter((t) => duration > 0 && t > duration);
|
|
2225
|
+
if (late.length)
|
|
2226
|
+
return `error: ${late.map(fmtTime).join(", ")} ${late.length === 1 ? "is" : "are"} past the end (the video is ${fmtTime(duration)})`;
|
|
2227
|
+
const picks = times.length ? times : duration > 0 ? evenTimes(duration, nFrames) : [];
|
|
2228
|
+
const keepDir = flag(args.save_frames) || !analyze ? operatorPath("cache", "frames", `video-${Date.now()}`) : "";
|
|
2229
|
+
let saved = [];
|
|
2230
|
+
let missedNote = "";
|
|
2231
|
+
if (keepDir) {
|
|
2232
|
+
if (!picks.length)
|
|
2233
|
+
return "error: video_analyze could not read the video's length (is ffprobe installed?), so pass `timestamps` to save frames";
|
|
2234
|
+
await mkdir(keepDir, { recursive: true });
|
|
2235
|
+
const got = await grabFrames(src, picks, keepDir, "frame", MEDIA_CAPS.frameEdge);
|
|
2236
|
+
if (!got.frames.length)
|
|
2237
|
+
return "error: ffmpeg saved no frames — is it installed, and is the input a valid video?";
|
|
2238
|
+
saved = got.frames;
|
|
2239
|
+
if (got.missed.length)
|
|
2240
|
+
missedNote = `\nno frame at ${got.missed.map(fmtTime).join(", ")} (ffmpeg returned none)`;
|
|
2241
|
+
}
|
|
2242
|
+
const savedLines = saved.map((f) => `${f.path} (at ${fmtTime(f.t)})`).join("\n") + missedNote;
|
|
2243
|
+
if (!analyze)
|
|
2244
|
+
return `${saved.length} frame${saved.length === 1 ? "" : "s"} saved from ${title ? `"${title}"` : video} (video ${fmtTime(duration)}), no model asked:\n${savedLines}`;
|
|
2245
|
+
let picked;
|
|
2246
|
+
let at = "";
|
|
2247
|
+
if (picks.length) {
|
|
2248
|
+
const got = (await grabFrames(src, picks, dir, "f", MEDIA_CAPS.analyzeWidth)).frames;
|
|
2249
|
+
picked = got.map((f) => f.path);
|
|
2250
|
+
at = ` at ${got.map((f) => fmtTime(f.t)).join(", ")}`;
|
|
2078
2251
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2252
|
+
else {
|
|
2253
|
+
try {
|
|
2254
|
+
await pexec("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-i", src, "-vf", `scale=${MEDIA_CAPS.analyzeWidth}:-1,fps=2`, "-frames:v", String(nFrames * 3), join(dir, "f%03d.png")]);
|
|
2255
|
+
}
|
|
2256
|
+
catch {
|
|
2257
|
+
return "error: ffmpeg failed to sample frames — is it installed, and is the input a valid video?";
|
|
2258
|
+
}
|
|
2259
|
+
const files = (await readdir(dir)).filter((f) => /^f\d+\.png$/.test(f)).sort();
|
|
2260
|
+
const step = Math.max(1, Math.floor(files.length / nFrames));
|
|
2261
|
+
picked = files.filter((_f, i) => i % step === 0).slice(0, nFrames).map((f) => join(dir, f));
|
|
2081
2262
|
}
|
|
2082
|
-
|
|
2083
|
-
if (!files.length)
|
|
2263
|
+
if (!picked.length)
|
|
2084
2264
|
return "error: no frames extracted from the video (is it a valid video file?)";
|
|
2085
|
-
const
|
|
2086
|
-
const picked = files.filter((_f, i) => i % step === 0).slice(0, nFrames);
|
|
2087
|
-
const parts = [{ type: "text", text: `${question} (${picked.length} frames, in order)` }];
|
|
2265
|
+
const parts = [{ type: "text", text: `${question} (${picked.length} frames, in order${at})` }];
|
|
2088
2266
|
for (const f of picked) {
|
|
2089
|
-
const b = await readFile(
|
|
2267
|
+
const b = await readFile(f);
|
|
2090
2268
|
parts.push({ type: "image_url", image_url: { url: `data:image/png;base64,${b.toString("base64")}` } });
|
|
2091
2269
|
}
|
|
2092
2270
|
const text = await visionComplete(parts, args, await visionSettings(), 180_000);
|
|
2093
|
-
return `video analysis (${picked.length} frames) → ${text}`;
|
|
2271
|
+
return `video analysis (${picked.length} frames${duration ? ` of ${label}` : ""}) → ${text}${saved.length ? `\nframes saved:\n${savedLines}` : ""}`;
|
|
2094
2272
|
}
|
|
2095
2273
|
catch (e) {
|
|
2096
2274
|
const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
|
|
@@ -2632,15 +2810,18 @@ const TOOLS = [
|
|
|
2632
2810
|
},
|
|
2633
2811
|
{
|
|
2634
2812
|
name: "image_analyze", safe: true,
|
|
2635
|
-
contract: { v:
|
|
2813
|
+
contract: { v: 2, effects: ["read", "fetch"], bins: ["osascript", "textutil", "unzip", "qlmanage", "sips", "ffmpeg", "chrome", "python3"] },
|
|
2636
2814
|
description: "SEE an image with real vision (the gateway's `vision` route): a local path or http(s) url + an optional question → the model's answer. Use it on a reference, screenshot or generated image before acting — never guess content from file size or pixel stats. A DOCUMENT (PDF, DOCX, XLSX, PPTX, RTF, HTML) returns its extracted TEXT, every page; only an image-only document is rendered (first page). as_image: true looks at a document's first page as a picture.",
|
|
2637
2815
|
parameters: { type: "object", properties: {
|
|
2638
2816
|
image: { type: "string", description: "local path or http(s) url — an image, or a document (returned as text)" },
|
|
2817
|
+
page: { type: "string", description: "web page url: screenshot + see it" },
|
|
2818
|
+
full_page: { type: "boolean" },
|
|
2819
|
+
design: { type: "boolean", description: "layout, real palette, fonts, parts" },
|
|
2639
2820
|
question: { type: "string", description: "default \"Describe this image in detail.\"" },
|
|
2640
2821
|
max_tokens: { type: "number", description: "answer cap (default 1024)" },
|
|
2641
2822
|
timeout_ms: { type: "number", description: "default 120000" },
|
|
2642
2823
|
as_image: { type: "boolean", description: "document: look at its first page as an image (layout, charts)" },
|
|
2643
|
-
}, required: [
|
|
2824
|
+
}, required: [] },
|
|
2644
2825
|
run: imageAnalyze,
|
|
2645
2826
|
},
|
|
2646
2827
|
{
|
|
@@ -2654,12 +2835,16 @@ const TOOLS = [
|
|
|
2654
2835
|
},
|
|
2655
2836
|
{
|
|
2656
2837
|
name: "video_analyze", safe: true,
|
|
2657
|
-
contract: { v:
|
|
2658
|
-
description: "SEE a video: frames sampled evenly
|
|
2838
|
+
contract: { v: 2, effects: ["read", "fetch"], bins: ["ffprobe", "ffmpeg", "yt-dlp"] },
|
|
2839
|
+
description: "SEE a video: frames sampled evenly (or at timestamps) are described by the VL model (the gateway's `vision` route). A local path, video url, or video page link (YouTube, Vimeo: needs yt-dlp) + an optional question. Frame capture: save_frames returns PNG paths; analyze: false skips the model. Never guess a video's content from the file.",
|
|
2659
2840
|
parameters: { type: "object", properties: {
|
|
2660
|
-
video: { type: "string", description: "local path or
|
|
2841
|
+
video: { type: "string", description: "local path or url" },
|
|
2661
2842
|
question: { type: "string", description: "default: describe what happens" },
|
|
2662
2843
|
frames: { type: "number", description: "2-16 (default 8)" },
|
|
2844
|
+
timestamps: { type: "string", description: "e.g. \"5, 1:30\"" },
|
|
2845
|
+
save_frames: { type: "boolean" },
|
|
2846
|
+
analyze: { type: "boolean", description: "default true" },
|
|
2847
|
+
max_duration_s: { type: "number", description: "page links (default 1800)" },
|
|
2663
2848
|
max_tokens: { type: "number", description: "answer cap (default 1024)" },
|
|
2664
2849
|
timeout_ms: { type: "number", description: "default 180000" },
|
|
2665
2850
|
}, required: ["video"] },
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// Web pages and video links for the vision tools (image_analyze `page` / `design`, video_analyze on a video page,
|
|
2
|
+
// at timestamps, frames saved). Everything that can be measured is measured here in code — frame times, a page's
|
|
3
|
+
// computed fonts and colours — so the vision model is asked only about what it can see. Node builtins load lazily
|
|
4
|
+
// (same contract as registry.ts) so the neutral bundle can import this module for nothing but its types.
|
|
5
|
+
import { pexecFile } from "./exec.js";
|
|
6
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
7
|
+
/** Caps for media this engine downloads. A page link resolves through yt-dlp, which refuses past both. */
|
|
8
|
+
export const MEDIA_CAPS = { maxDurationS: 1800, maxBytes: 300_000_000, maxFrames: 16, frameEdge: 1920, analyzeWidth: 384 };
|
|
9
|
+
export const YTDLP_INSTALL = "`brew install yt-dlp` or `pipx install yt-dlp`";
|
|
10
|
+
// Hosts whose links are pages around a player, never a video file. Any other url that answers text/html is too.
|
|
11
|
+
const VIDEO_PAGE_HOST = /^(?:[\w-]+\.)*(?:youtube\.com|youtu\.be|youtube-nocookie\.com|vimeo\.com|dailymotion\.com|dai\.ly|twitch\.tv|tiktok\.com|loom\.com|streamable\.com|x\.com|twitter\.com|instagram\.com|facebook\.com|fb\.watch)$/i;
|
|
12
|
+
export function isVideoPageUrl(url) {
|
|
13
|
+
try {
|
|
14
|
+
return VIDEO_PAGE_HOST.test(new URL(url).hostname);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return false;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** 83 → "1:23", 3723.5 → "1:02:03.5". */
|
|
21
|
+
export function fmtTime(s) {
|
|
22
|
+
const whole = Math.floor(s), frac = Math.round((s - whole) * 10);
|
|
23
|
+
const h = Math.floor(whole / 3600), m = Math.floor((whole % 3600) / 60), sec = whole % 60;
|
|
24
|
+
const tail = `${String(sec).padStart(2, "0")}${frac ? `.${frac}` : ""}`;
|
|
25
|
+
return h ? `${h}:${String(m).padStart(2, "0")}:${tail}` : `${m}:${tail}`;
|
|
26
|
+
}
|
|
27
|
+
/** "5, 1:30, 1:02:03.5" (or an array of them) → seconds. A string result is the error, in plain words. */
|
|
28
|
+
export function parseTimestamps(raw) {
|
|
29
|
+
if (raw === undefined || raw === null || raw === "")
|
|
30
|
+
return [];
|
|
31
|
+
const items = (Array.isArray(raw) ? raw : String(raw).split(/[,\s]+/)).map((x) => String(x).trim()).filter(Boolean);
|
|
32
|
+
const out = [];
|
|
33
|
+
for (const it of items) {
|
|
34
|
+
const m = /^(?:(\d+):)?(?:(\d+):)?(\d+(?:\.\d+)?)s?$/.exec(it);
|
|
35
|
+
if (!m)
|
|
36
|
+
return `"${it}" is not a timestamp (use seconds or m:ss / h:mm:ss)`;
|
|
37
|
+
const parts = [m[1], m[2], m[3]].filter((p) => p !== undefined).map(Number);
|
|
38
|
+
out.push(parts.reduce((acc, p) => acc * 60 + p, 0));
|
|
39
|
+
}
|
|
40
|
+
if (out.length > MEDIA_CAPS.maxFrames)
|
|
41
|
+
return `${out.length} timestamps — at most ${MEDIA_CAPS.maxFrames} per call`;
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
/** n times spread evenly across a clip, each in the middle of its slice (never the black first frame). */
|
|
45
|
+
export function evenTimes(duration, n) {
|
|
46
|
+
return Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * duration) / n * 100) / 100);
|
|
47
|
+
}
|
|
48
|
+
const lastLine = (s) => String(s ?? "").trim().split("\n").filter(Boolean).pop()?.slice(0, 240) ?? "";
|
|
49
|
+
/** Resolve a video PAGE (YouTube, Vimeo, …) to a local file with yt-dlp, inside the duration and size caps.
|
|
50
|
+
* Missing yt-dlp is named with its install command; every refusal says why. */
|
|
51
|
+
export async function downloadVideoPage(url, dir, caps) {
|
|
52
|
+
let info;
|
|
53
|
+
try {
|
|
54
|
+
const { stdout } = await pexecFile("yt-dlp", ["--dump-single-json", "--no-playlist", "--no-warnings", "--", url], { timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
|
|
55
|
+
info = JSON.parse(stdout);
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
if (e?.code === "ENOENT")
|
|
59
|
+
return { error: `yt-dlp is not installed, so ${url} (a video page, not a video file) cannot be resolved. Install it with ${YTDLP_INSTALL}, then call again.` };
|
|
60
|
+
return { error: `yt-dlp could not read ${url}: ${lastLine(e?.stderr) || String(e?.message ?? e)}` };
|
|
61
|
+
}
|
|
62
|
+
if (info.is_live)
|
|
63
|
+
return { error: `${url} is a live stream; only recorded videos can be sampled` };
|
|
64
|
+
const duration = Number(info.duration) || 0;
|
|
65
|
+
if (duration > caps.maxDurationS)
|
|
66
|
+
return { error: `${url} is ${fmtTime(duration)} long, over the ${fmtTime(caps.maxDurationS)} cap (raise max_duration_s to sample it)` };
|
|
67
|
+
const { join } = await nodeImport("node:path");
|
|
68
|
+
const { readdir } = await nodeImport("node:fs/promises");
|
|
69
|
+
const mb = Math.floor(caps.maxBytes / 1_000_000);
|
|
70
|
+
try {
|
|
71
|
+
// Video only, 720p at most: frames need no audio, and the smaller stream stays inside the size cap.
|
|
72
|
+
await pexecFile("yt-dlp", ["--no-playlist", "--no-warnings", "--no-part", "-f", "bv*[height<=720]/b[height<=720]/wv*/w",
|
|
73
|
+
"--max-filesize", `${mb}M`, "-o", join(dir, "page-video.%(ext)s"), "--", url], { timeout: 600_000, maxBuffer: 16 * 1024 * 1024 });
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
return { error: `yt-dlp could not download ${url}: ${lastLine(e?.stderr) || String(e?.message ?? e)}` };
|
|
77
|
+
}
|
|
78
|
+
const file = (await readdir(dir)).find((f) => f.startsWith("page-video."));
|
|
79
|
+
if (!file)
|
|
80
|
+
return { error: `yt-dlp downloaded nothing for ${url} (its smallest stream is over the ${mb} MB cap, or the site refused)` };
|
|
81
|
+
return { path: join(dir, file), title: String(info.title ?? ""), duration };
|
|
82
|
+
}
|
|
83
|
+
/** One ffmpeg seek per time → `<dir>/<prefix>-NN-t<seconds>s.png`, at most `edge` px wide (never upscaled).
|
|
84
|
+
* A time past the end yields no file and is reported, not invented. */
|
|
85
|
+
export async function grabFrames(src, times, dir, prefix, edge) {
|
|
86
|
+
const { join } = await nodeImport("node:path");
|
|
87
|
+
const { stat } = await nodeImport("node:fs/promises");
|
|
88
|
+
const frames = [];
|
|
89
|
+
const missed = [];
|
|
90
|
+
for (const [i, t] of times.entries()) {
|
|
91
|
+
const out = join(dir, `${prefix}-${String(i + 1).padStart(2, "0")}-t${t.toFixed(1)}s.png`);
|
|
92
|
+
try {
|
|
93
|
+
await pexecFile("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-ss", String(t), "-i", src, "-frames:v", "1", "-vf", `scale='min(iw,${edge})':-2`, out], { timeout: 60_000 });
|
|
94
|
+
}
|
|
95
|
+
catch { /* checked below */ }
|
|
96
|
+
if ((await stat(out).catch(() => null))?.size)
|
|
97
|
+
frames.push({ path: out, t });
|
|
98
|
+
else
|
|
99
|
+
missed.push(t);
|
|
100
|
+
}
|
|
101
|
+
return { frames, missed };
|
|
102
|
+
}
|
|
103
|
+
// ── Design read ──────────────────────────────────────────────────────────────
|
|
104
|
+
/** Runs in the page: what its CSS actually computes — font stacks by use, loaded web fonts, heading styles, text and
|
|
105
|
+
* background colours by use, and how many grid / flex containers lay it out. Returned by value as plain JSON. */
|
|
106
|
+
export const DESIGN_PROBE_JS = `(() => {
|
|
107
|
+
const hex = (c) => { const m = /rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)(?:,\\s*([\\d.]+))?/.exec(c); if (!m || (m[4] !== undefined && Number(m[4]) === 0)) return null; return "#" + [m[1], m[2], m[3]].map((n) => Number(n).toString(16).padStart(2, "0")).join(""); };
|
|
108
|
+
const bump = (map, k, extra) => { if (!k) return; const e = map.get(k) || { n: 0, sizes: new Map(), weights: new Set() }; e.n++; if (extra) { e.sizes.set(extra.size, (e.sizes.get(extra.size) || 0) + 1); e.weights.add(extra.weight); } map.set(k, e); };
|
|
109
|
+
const fonts = new Map(), text = new Map(), bg = new Map();
|
|
110
|
+
let grid = 0, flex = 0;
|
|
111
|
+
for (const el of Array.from(document.querySelectorAll("body, body *")).slice(0, 5000)) {
|
|
112
|
+
const cs = getComputedStyle(el);
|
|
113
|
+
if (cs.display === "none" || cs.visibility === "hidden" || !el.getClientRects().length) continue;
|
|
114
|
+
if (cs.display.includes("grid")) grid++;
|
|
115
|
+
if (cs.display.includes("flex")) flex++;
|
|
116
|
+
bump(bg, hex(cs.backgroundColor));
|
|
117
|
+
if (Array.from(el.childNodes).some((n) => n.nodeType === 3 && n.textContent.trim())) {
|
|
118
|
+
bump(fonts, cs.fontFamily, { size: cs.fontSize, weight: cs.fontWeight });
|
|
119
|
+
bump(text, hex(cs.color));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const top = (map, k) => Array.from(map.entries()).sort((a, b) => b[1].n - a[1].n).slice(0, k);
|
|
123
|
+
const headings = ["h1", "h2", "h3"].map((t) => { const el = document.querySelector(t); if (!el) return null; const cs = getComputedStyle(el); return { tag: t, family: cs.fontFamily, size: cs.fontSize, weight: cs.fontWeight }; }).filter(Boolean);
|
|
124
|
+
let loaded = [];
|
|
125
|
+
try { loaded = Array.from(new Set(Array.from(document.fonts).filter((f) => f.status === "loaded").map((f) => f.family.replace(/["']/g, "")))); } catch (e) {}
|
|
126
|
+
return {
|
|
127
|
+
fonts: top(fonts, 5).map(([family, e]) => ({ family, uses: e.n, sizes: Array.from(e.sizes.entries()).sort((a, b) => b[1] - a[1]).slice(0, 4).map((s) => s[0]), weights: Array.from(e.weights) })),
|
|
128
|
+
webFonts: loaded, headings,
|
|
129
|
+
textColors: top(text, 6).map(([c, e]) => c + " ×" + e.n), backgrounds: top(bg, 6).map(([c, e]) => c + " ×" + e.n),
|
|
130
|
+
grid, flex, width: innerWidth, height: document.documentElement.scrollHeight,
|
|
131
|
+
};
|
|
132
|
+
})()`;
|
|
133
|
+
export const DESIGN_QUESTION = "Read the design of this UI. Answer in four short sections with exactly these headings: "
|
|
134
|
+
+ "LAYOUT (grid and columns, alignment, spacing rhythm, the sections from top to bottom), "
|
|
135
|
+
+ "COMPONENTS (each UI component you can see: navigation, buttons, cards, forms, icons, imagery), "
|
|
136
|
+
+ "TYPOGRAPHY (GUESS) (likely type classification and families, weights, size scale — say these are guesses from pixels), "
|
|
137
|
+
+ "STYLE (the overall visual style in one or two lines). Do not list hex colour values: the palette is measured separately.";
|
|
138
|
+
const firstFamily = (stack) => stack.split(",")[0].trim().replace(/^["']|["']$/g, "");
|
|
139
|
+
/** The design read: MEASURED (code) above SEEN (the model), each value labelled with where it came from. */
|
|
140
|
+
export function formatDesignRead(o) {
|
|
141
|
+
const out = [`design read — ${o.source}`, "MEASURED (from code, not the model)"];
|
|
142
|
+
if (o.size)
|
|
143
|
+
out.push(`- canvas: ${o.size}`);
|
|
144
|
+
out.push(o.palette?.length
|
|
145
|
+
? `- palette (dominant pixel colours, most common first): ${o.palette.join(" ")}`
|
|
146
|
+
: `- palette: not measured${o.paletteNote ? ` (${o.paletteNote})` : ""}`);
|
|
147
|
+
const css = o.css;
|
|
148
|
+
if (css) {
|
|
149
|
+
if (css.fonts?.length)
|
|
150
|
+
out.push(`- fonts (computed CSS, by text elements): ${css.fonts.map((f) => `${firstFamily(f.family)} ${f.weights.join("/")} at ${f.sizes.join(", ")} (${f.uses})`).join("; ")}`);
|
|
151
|
+
out.push(`- web fonts loaded: ${css.webFonts?.length ? css.webFonts.join(", ") : "none (system or fallback fonts)"}`);
|
|
152
|
+
if (css.headings?.length)
|
|
153
|
+
out.push(`- headings: ${css.headings.map((h) => `${h.tag} ${firstFamily(h.family)} ${h.size}/${h.weight}`).join("; ")}`);
|
|
154
|
+
if (css.textColors?.length)
|
|
155
|
+
out.push(`- text colours (CSS): ${css.textColors.join(", ")}`);
|
|
156
|
+
if (css.backgrounds?.length)
|
|
157
|
+
out.push(`- backgrounds (CSS): ${css.backgrounds.join(", ")}`);
|
|
158
|
+
out.push(`- layout containers (CSS): ${css.grid ?? 0} grid, ${css.flex ?? 0} flex`);
|
|
159
|
+
}
|
|
160
|
+
out.push(`SEEN (vision model — typography is a guess from pixels${css ? "; the measured CSS wins where they differ" : ""})`, o.seen.trim());
|
|
161
|
+
return out.join("\n");
|
|
162
|
+
}
|
package/dist/ui/modelPicker.js
CHANGED
|
@@ -14,6 +14,10 @@ export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, Nous, O
|
|
|
14
14
|
/** Presets whose zero-price rows /model lists once their key is connected (router/free-models.ts) — OpenRouter's
|
|
15
15
|
* `:free` listing joins here. */
|
|
16
16
|
export const FREE_ROW_PRESETS = ["operator", "nous"];
|
|
17
|
+
/** The /model main rows, in this order (0.1.361); everything else sits behind MORE_ROW. */
|
|
18
|
+
export const MAIN_MODEL_IDS = ["operator-flash", "kimi-linear-48b", "qwen3.8-27b"];
|
|
19
|
+
/** The last main row: an action that opens the rest (other fleet rows, connected providers, free rows, MOA, connect). */
|
|
20
|
+
export const MORE_ROW = "More models…";
|
|
17
21
|
// fleet → connected providers → free rows → MOA. The built-ins already list the local row before the gateway rows.
|
|
18
22
|
const group = (m) => (m.kind === "orchestrated" ? 3 : m.tier === "free" ? 2 : m.byo ? 1 : 0);
|
|
19
23
|
/** The picker order of a visible registry: fleet rows, the connected providers, the free rows, then MOA — a stable
|
|
@@ -39,10 +43,28 @@ export function costParts(c, now = Date.now()) {
|
|
|
39
43
|
const ROW_CHROME = 16;
|
|
40
44
|
/** The /model rows in picker order — pickerRow for each (the active single model shows its served window), " · cached"
|
|
41
45
|
* on free rows served from the disk cache, and with `cost` the re-read each switch would cost — closed by the connect
|
|
42
|
-
* row. With `cols`, a row with a cost is fitted to one line. */
|
|
46
|
+
* row. With `cols`, a row with a cost is fitted to one line. "More models…" draws this from every row but the main ones. */
|
|
43
47
|
export function modelPickerView(models, o) {
|
|
44
48
|
const ordered = pickerOrder(models);
|
|
45
|
-
|
|
49
|
+
return {
|
|
50
|
+
rows: [...modelRows(ordered, o), CONNECT_ROW],
|
|
51
|
+
entries: [...ordered.map((profile) => ({ kind: "model", profile })), { kind: "connect" }],
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/** The first /model screen: the main rows present in `models` (MAIN_MODEL_IDS order), then "More models…". */
|
|
55
|
+
export function mainPickerView(models, o) {
|
|
56
|
+
const main = MAIN_MODEL_IDS.flatMap((id) => models.filter((m) => m.id === id));
|
|
57
|
+
return {
|
|
58
|
+
rows: [...modelRows(main, o), MORE_ROW],
|
|
59
|
+
entries: [...main.map((profile) => ({ kind: "model", profile })), { kind: "more" }],
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/** Whether a row is one of the main /model rows (and so not repeated under "More models…"). */
|
|
63
|
+
export function isMainModel(m) {
|
|
64
|
+
return MAIN_MODEL_IDS.includes(m.id);
|
|
65
|
+
}
|
|
66
|
+
function modelRows(ordered, o) {
|
|
67
|
+
return ordered.map((m) => {
|
|
46
68
|
const active = m.id === o.active;
|
|
47
69
|
const row = pickerRow(m, { servedCtx: active && m.kind === "single" ? o.servedCtx : undefined });
|
|
48
70
|
const cost = active ? [] : costParts(o.cost?.(m), o.now);
|
|
@@ -60,13 +82,9 @@ export function modelPickerView(models, o) {
|
|
|
60
82
|
const keep = `${cost[0].forms[0]}${tail}`;
|
|
61
83
|
return `${truncateToWidth(row, Math.max(8, width - 1 - cellWidth(keep)))}${keep}`;
|
|
62
84
|
});
|
|
63
|
-
return {
|
|
64
|
-
rows: [...rows, CONNECT_ROW],
|
|
65
|
-
entries: [...ordered.map((profile) => ({ kind: "model", profile })), { kind: "connect" }],
|
|
66
|
-
};
|
|
67
85
|
}
|
|
68
|
-
/** The rows with the portal's live markers (● ○ ✕ ?) on the model rows — same count, same order; the connect
|
|
69
|
-
* never marked. `cat` undefined leaves them as they are. */
|
|
86
|
+
/** The rows with the portal's live markers (● ○ ✕ ?) on the model rows — same count, same order; the connect and more
|
|
87
|
+
* rows are never marked. `cat` undefined leaves them as they are. */
|
|
70
88
|
export function markModelRows(view, cat) {
|
|
71
89
|
const models = view.entries.flatMap((e) => (e.kind === "model" ? [e.profile] : []));
|
|
72
90
|
return [...markPickerOptions(view.rows.slice(0, models.length), models.map(portalIdFor), cat), ...view.rows.slice(models.length)];
|