@0perator/operator 0.1.359 → 0.1.360-next.0
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/dashboard/index.html +2 -2
- package/dist/autonomy/cloud-agent.js +2 -2
- package/dist/autonomy/headless.js +15 -6
- package/dist/autonomy/session-factory.js +2 -1
- package/dist/background/notices.js +1 -1
- package/dist/browser/session.js +7 -0
- package/dist/cli.js +94 -52
- package/dist/config/features.js +6 -5
- package/dist/config/persona.js +57 -40
- package/dist/config/settings.js +39 -55
- package/dist/engine/agent.js +72 -33
- package/dist/engine/aurora.js +24 -2
- package/dist/engine/compaction.js +27 -7
- package/dist/engine/decision-points.js +16 -4
- package/dist/engine/kv-slot.js +87 -0
- package/dist/engine/loop-guard.js +49 -18
- package/dist/engine/messages.js +8 -1
- package/dist/engine/progress-deadline.js +37 -0
- package/dist/engine/verify-gate.js +134 -9
- package/dist/enterprise/cli.js +13 -1
- package/dist/mcp/craft-server.js +5 -3
- package/dist/memory/live-progress.js +35 -6
- package/dist/permissions/policy.js +8 -0
- package/dist/permissions/signature.js +9 -0
- package/dist/products/artifact-library.js +47 -0
- package/dist/products/craft.js +58 -94
- package/dist/products/temple.js +230 -0
- package/dist/remote/host.js +28 -1
- package/dist/router/discovery.js +23 -6
- package/dist/router/models.js +29 -70
- package/dist/services/preflight.js +3 -41
- package/dist/session.js +121 -38
- package/dist/skills/catalogue.js +2 -0
- package/dist/skills/finder.js +1 -1
- package/dist/tools/background-result.js +26 -0
- package/dist/tools/chauffeur-native.js +6 -0
- package/dist/tools/craft.js +17 -6
- package/dist/tools/deferred.js +64 -30
- package/dist/tools/executor.js +4 -2
- package/dist/tools/paths.js +3 -3
- package/dist/tools/read-ledger.js +44 -0
- package/dist/tools/registry.js +218 -264
- package/dist/tools/sandbox.js +52 -39
- package/dist/tools/shell-context.js +5 -0
- package/dist/tools/shell-session.js +61 -29
- package/dist/tools/vision-gateway.js +79 -34
- package/dist/tools/wave-tools.js +2 -2
- package/dist/tools/wave2-tools.js +6 -6
- package/dist/ui/ArtifactPicker.js +2 -2
- package/dist/ui/Composer.js +9 -2
- package/dist/ui/StatusRule.js +1 -1
- package/dist/ui/modelPicker.js +1 -1
- package/dist/ui/nextStep.js +1 -0
- package/dist/ui/pending.js +10 -0
- package/dist/update.js +78 -4
- package/dist/util/retry.js +34 -0
- package/dist/util/slash.js +2 -1
- package/dist/vault/tool.js +3 -1
- package/mcp/powertools-toolbox.mjs +166 -1
- package/package.json +9 -13
- package/dashboard/README.md +0 -62
- package/dist/compose/client.js +0 -56
- package/mcp/README.md +0 -88
- package/mcp/powertools.md +0 -210
package/dist/tools/registry.js
CHANGED
|
@@ -14,6 +14,7 @@ import { PRODUCT_API_HOST } from "../config/product-hosts.js";
|
|
|
14
14
|
import { ownChild } from "../util/owned-children.js";
|
|
15
15
|
import { BG_MAX_RUNNING, createJob, finishJob, newJobId, pruneShellJobs, runningJobCount, shellJobs, stopShellJob, trackJobOutput } from "./shell-jobs.js";
|
|
16
16
|
import { pexecFile } from "./exec.js";
|
|
17
|
+
import { AUTO_BACKGROUNDED, MOVED_TO_BACKGROUND, STARTED_BACKGROUND_JOB, jobFinishedLine } from "./background-result.js";
|
|
17
18
|
import { WAVE_TOOLS } from "./wave-tools.js";
|
|
18
19
|
import { WAVE2_TOOLS } from "./wave2-tools.js";
|
|
19
20
|
import { GIT_PR_TOOLS } from "./git-pr.js";
|
|
@@ -24,9 +25,10 @@ import { desktopScreenshot, desktopClick, desktopRead, appInteract, capturePerma
|
|
|
24
25
|
import { findFiles, FIND_FILES_DEFAULT_LIMIT, FIND_FILES_MAX_LIMIT, KINDS } from "./find-files.js";
|
|
25
26
|
import { formatGitStatus } from "./git-status.js";
|
|
26
27
|
import { DOC_TEXT_EXTS, describeDocText, docExt, extractDocText } from "./doc-text.js";
|
|
27
|
-
import {
|
|
28
|
+
import { askVision, visionGateways, VISION_LIMITS } from "./vision-gateway.js";
|
|
28
29
|
import { expandPath, assertContentSearchScope, assertShellHomeWideSearch, assertShellBlindDownload } from "./paths.js";
|
|
29
30
|
import { resolveReadPath } from "./read-path.js";
|
|
31
|
+
import { recordRead, getRead, forgetReads, seenView } from "./read-ledger.js"; // per-session read-state (pure, node-free — stays out of the neutral graph)
|
|
30
32
|
import { CRAFT_TOOLS } from "./craft.js";
|
|
31
33
|
import { runMemoryTool } from "./memory.js";
|
|
32
34
|
import { documentGenerate } from "./document.js";
|
|
@@ -92,6 +94,8 @@ function adoptDetached(key, run, id, ShellSession, processCwd) {
|
|
|
92
94
|
/** Kill EVERY persistent shell (and their process groups) on process shutdown so none orphan.
|
|
93
95
|
* Wired into the CLI's exit/SIGTERM handlers — no-op if no shell was ever started. */
|
|
94
96
|
export function disposeShellSession() {
|
|
97
|
+
for (const key of _shells.keys())
|
|
98
|
+
forgetReads(key); // drop each lane's read ledger alongside its shell
|
|
95
99
|
for (const sess of _shells.values())
|
|
96
100
|
sess.dispose();
|
|
97
101
|
_shells.clear();
|
|
@@ -104,6 +108,7 @@ export function disposeShellSessionKey(key) {
|
|
|
104
108
|
sess.dispose();
|
|
105
109
|
_shells.delete(key);
|
|
106
110
|
}
|
|
111
|
+
forgetReads(key); // release this lane's read ledger too
|
|
107
112
|
}
|
|
108
113
|
// Commands that routinely outlive a foreground timeout. ssh is deliberately absent: what runs on the remote host is unknown.
|
|
109
114
|
const LONG_CMD_RE = /(?:^|[;&|(]\s*|&&\s*)(?:(?:sudo\s+)?(?:npm|pnpm|yarn|bun)\s+(?:install|i|ci|add|test|run\s+(?:build|test)|build)\b|pip3?\s+install\b|(?:python3?\s+-m\s+)?pytest\b|cargo\s+(?:build|test|install)\b|go\s+(?:build|test)\b|(?:g?make|cmake|gradle|\.\/gradlew|mvn)\b|docker\s+(?:build|pull)\b|brew\s+(?:install|upgrade)\b|apt(?:-get)?\s+(?:install|upgrade)\b|wget\b|curl\b[^|;&]*\s(?:-[a-zA-Z]*[OL]\b|--output\b|-o\s))/;
|
|
@@ -123,8 +128,8 @@ async function shellExec(args) {
|
|
|
123
128
|
// An explicit timeout_ms is the model's own choice and is honored; otherwise a known-long command goes straight to a job.
|
|
124
129
|
if (args.timeout_ms === undefined && isLongRunningCommand(command)) {
|
|
125
130
|
const started = await shellBackground(args);
|
|
126
|
-
if (started.startsWith(
|
|
127
|
-
return
|
|
131
|
+
if (started.startsWith(STARTED_BACKGROUND_JOB))
|
|
132
|
+
return `${AUTO_BACKGROUNDED}this command is expected to run long, so it was NOT run in the foreground shell]\n${started}`;
|
|
128
133
|
return started;
|
|
129
134
|
}
|
|
130
135
|
const timeout = Number(args.timeout_ms ?? 120_000);
|
|
@@ -135,27 +140,34 @@ async function shellExec(args) {
|
|
|
135
140
|
// closing brace until the 120 s timeout (sub-agents in worktrees, headless --cwd runs)
|
|
136
141
|
const toRun = cwd ? `( cd ${JSON.stringify(cwd)} && {\n${command}\n} )` : command;
|
|
137
142
|
try {
|
|
138
|
-
const { shellExecMode } = (await nodeImport("./shell-context.js"));
|
|
143
|
+
const { shellExecMode, shellSignalStore } = (await nodeImport("./shell-context.js"));
|
|
139
144
|
const mod = (await nodeImport("./shell-session.js"));
|
|
140
145
|
const mode = shellExecMode.getStore() ?? "persistent";
|
|
146
|
+
const signal = shellSignalStore.getStore(); // turn abort (esc): kills this command's process group (FIX 5)
|
|
141
147
|
// Multi-shell rounds (Executor.executeParallel sets mode=ephemeral) must NOT share the persistent
|
|
142
148
|
// FIFO — concurrent stdin/sentinel framing would cross-wire output. One-shot bash overlaps for real.
|
|
143
149
|
// Lone bash stays persistent (cwd/env + ctrl+b detach).
|
|
144
150
|
let r;
|
|
145
151
|
let movedId = "";
|
|
146
152
|
if (mode === "ephemeral") {
|
|
147
|
-
r = await mod.runEphemeralShell(toRun, timeout);
|
|
153
|
+
r = await mod.runEphemeralShell(toRun, timeout, undefined, signal);
|
|
148
154
|
}
|
|
149
155
|
else {
|
|
150
156
|
const { sess, key } = await getShellSession();
|
|
151
|
-
r = await sess.run(toRun, timeout, { onDetach: (run) => { movedId = newJobId(); adoptDetached(key, run, movedId, mod.ShellSession, mod.processCwd); } });
|
|
157
|
+
r = await sess.run(toRun, timeout, { onDetach: (run) => { movedId = newJobId(); adoptDetached(key, run, movedId, mod.ShellSession, mod.processCwd); }, signal });
|
|
152
158
|
}
|
|
153
159
|
let out = r.output || "";
|
|
154
160
|
if (r.detached) {
|
|
155
161
|
const sofar = out ? `\nOutput so far:\n${out.split("\n").slice(-20).join("\n")}` : "";
|
|
156
|
-
return
|
|
162
|
+
return `${MOVED_TO_BACKGROUND}${movedId}: ${command}\nIt keeps running. You will be notified when it finishes, so do not poll. bash_output {"id":"${movedId}"} reads its output, bash_kill {"id":"${movedId}"} (on demand) stops it.\nThe shell restarted in the same directory (environment variables, functions and aliases from the old shell are not carried over). It is free for your next command.${sofar}`;
|
|
157
163
|
}
|
|
158
164
|
const { shellResultNotes } = mod;
|
|
165
|
+
if (r.aborted) {
|
|
166
|
+
// esc / turn interrupt: the command's process group was signalled (FIX 5). The persistent shell survives
|
|
167
|
+
// unless its own death reset it. The result is mostly cosmetic — the turn is already ending on the abort.
|
|
168
|
+
const resetNote = r.reset ? " (the shell had to be reset: cwd/env cleared)" : "";
|
|
169
|
+
return (out ? out + "\n" : "") + `[interrupted — the command was stopped${resetNote}]`;
|
|
170
|
+
}
|
|
159
171
|
if (r.timedOut) {
|
|
160
172
|
const resetNote = mode === "ephemeral"
|
|
161
173
|
? `[timed out after ${timeout}ms — ephemeral shell killed; run long commands with shell_background instead]`
|
|
@@ -216,6 +228,61 @@ function rawOffsetAt(lines, offset, cut) {
|
|
|
216
228
|
}
|
|
217
229
|
return raw;
|
|
218
230
|
}
|
|
231
|
+
// The active lane's read ledger key: the Executor sets the shell key around every tool.run (executor.ts
|
|
232
|
+
// → shellKeyStore), so file_read and file_edit/file_write in the same session share one ledger. A tool
|
|
233
|
+
// run outside any Executor (a direct registry call in a test) falls back to the stable default key.
|
|
234
|
+
async function readLedgerKey() {
|
|
235
|
+
const { shellKeyStore, DEFAULT_SHELL_KEY } = (await nodeImport("./shell-context.js"));
|
|
236
|
+
return shellKeyStore.getStore() ?? DEFAULT_SHELL_KEY;
|
|
237
|
+
}
|
|
238
|
+
/** `path`'s on-disk state now: stat plus a content hash (mtime alone misses a same-second or mtime-preserving write). */
|
|
239
|
+
async function fileState(path) {
|
|
240
|
+
try {
|
|
241
|
+
const { stat, readFile } = await nodeImport("node:fs/promises");
|
|
242
|
+
const { createHash } = await nodeImport("node:crypto");
|
|
243
|
+
const st = await stat(path);
|
|
244
|
+
if (!st.isFile())
|
|
245
|
+
return null;
|
|
246
|
+
// Always the bytes on disk: hashing a decoded string would never match a file that is not valid UTF-8.
|
|
247
|
+
return { mtimeMs: st.mtimeMs, size: st.size, hash: createHash("sha256").update(await readFile(path)).digest("hex") };
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return null;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** Record `path`'s current on-disk state as seen this session — after a read, and after a write/edit (the
|
|
254
|
+
* model now knows what it just wrote, so a following edit of the same file is not a stale clobber).
|
|
255
|
+
* Best-effort: a miss only costs a future re-read, never a failed read/write. */
|
|
256
|
+
async function noteFileRead(path) {
|
|
257
|
+
const st = await fileState(path);
|
|
258
|
+
if (st)
|
|
259
|
+
recordRead(await readLedgerKey(), path, st);
|
|
260
|
+
}
|
|
261
|
+
/** Gate a file_edit/file_write against the read ledger. Two refusals, each naming the fix:
|
|
262
|
+
* - the file changed on disk since this session read it (content hash, so a touch does not count): the change
|
|
263
|
+
* would be made against a version the model never saw;
|
|
264
|
+
* - `overwrite` (file_write) of an existing file this session never read: a whole-file replace of unseen content
|
|
265
|
+
* is how work is lost. file_edit stays allowed unread — its exact, unique old_string match is the proof it is
|
|
266
|
+
* working on the current text (the model may have read the file through bash).
|
|
267
|
+
* Returns an error string to refuse with, or null to proceed. A ledger/stat error never blocks (fail open). */
|
|
268
|
+
async function assertReadBeforeMutate(path, o = {}) {
|
|
269
|
+
try {
|
|
270
|
+
const key = await readLedgerKey();
|
|
271
|
+
const rec = getRead(key, path);
|
|
272
|
+
const now = await fileState(path);
|
|
273
|
+
if (!now)
|
|
274
|
+
return null; // new file, or not a regular file — no read precondition
|
|
275
|
+
if (!rec)
|
|
276
|
+
return o.overwrite ? `error: ${path} exists and you have not read it this session — file_read it first (file_write replaces the whole file), or make a targeted change with file_edit.` : null;
|
|
277
|
+
const changed = rec.hash ? rec.hash !== now.hash : now.mtimeMs > rec.mtimeMs;
|
|
278
|
+
if (changed)
|
|
279
|
+
return `error: ${path} was modified since you read it — re-read it (file_read) before editing, or your change would overwrite newer contents.`;
|
|
280
|
+
return null;
|
|
281
|
+
}
|
|
282
|
+
catch {
|
|
283
|
+
return null;
|
|
284
|
+
} // never block an edit on a ledger failure
|
|
285
|
+
}
|
|
219
286
|
async function fileRead(args) {
|
|
220
287
|
const path = await resolveReadPath(str(args.path));
|
|
221
288
|
if (!path)
|
|
@@ -237,6 +304,13 @@ async function fileRead(args) {
|
|
|
237
304
|
const { readFile } = await nodeImport("node:fs/promises");
|
|
238
305
|
src = await readFile(path, "utf8");
|
|
239
306
|
}
|
|
307
|
+
await noteFileRead(path); // the session has now seen this file — a later file_edit/file_write of it is not a blind edit
|
|
308
|
+
// The same view of the same content, asked for again: one line, not the file. The text is already in the
|
|
309
|
+
// conversation; re-sending it is how a turn loops and a context fills (force, or a compaction, resets this).
|
|
310
|
+
const view = JSON.stringify([args.offset ?? null, args.limit ?? null, args.start_char ?? null, args.max_chars ?? null]);
|
|
311
|
+
if (seenView(await readLedgerKey(), path, view) && !args.force) {
|
|
312
|
+
return `[unchanged since you read it — this same part of ${path} is already above in this conversation; use that. Pass force: true only if it is no longer there.]`;
|
|
313
|
+
}
|
|
240
314
|
if (args.start_char !== undefined || args.max_chars !== undefined) {
|
|
241
315
|
return head + rawSlice(src, Number(args.start_char ?? 0), Number(args.max_chars ?? RAW_READ_MAX_CHARS));
|
|
242
316
|
}
|
|
@@ -295,11 +369,15 @@ async function fileWrite(args) {
|
|
|
295
369
|
const blocked = await deniedWriteAsync(path); // async: realpath closes the symlink-laundering gap
|
|
296
370
|
if (blocked)
|
|
297
371
|
return `error: ${blocked}`;
|
|
372
|
+
const stale = await assertReadBeforeMutate(path, { overwrite: true }); // overwriting an EXISTING file requires a current read (new files are free)
|
|
373
|
+
if (stale)
|
|
374
|
+
return stale;
|
|
298
375
|
try {
|
|
299
376
|
const { mkdir, writeFile } = await nodeImport("node:fs/promises");
|
|
300
377
|
const { dirname } = await nodeImport("node:path");
|
|
301
378
|
await mkdir(dirname(path), { recursive: true });
|
|
302
379
|
await writeFile(path, str(args.content), "utf8");
|
|
380
|
+
await noteFileRead(path); // the model now knows this file's on-disk state (it just wrote it) — a following edit is not stale
|
|
303
381
|
return `wrote ${path}`;
|
|
304
382
|
}
|
|
305
383
|
catch (e) {
|
|
@@ -316,6 +394,9 @@ async function fileEdit(args) {
|
|
|
316
394
|
const blocked = await deniedWriteAsync(path); // async: realpath closes the symlink-laundering gap
|
|
317
395
|
if (blocked)
|
|
318
396
|
return `error: ${blocked}`;
|
|
397
|
+
const stale = await assertReadBeforeMutate(path); // edit the file the model actually saw, not a stale/never-read version
|
|
398
|
+
if (stale)
|
|
399
|
+
return stale;
|
|
319
400
|
try {
|
|
320
401
|
const { readFile, writeFile } = await nodeImport("node:fs/promises");
|
|
321
402
|
const src = await readFile(path, "utf8");
|
|
@@ -324,8 +405,12 @@ async function fileEdit(args) {
|
|
|
324
405
|
return `error: old_string not found in ${path}`;
|
|
325
406
|
if (!replaceAll && count > 1)
|
|
326
407
|
return `error: old_string matches ${count} times in ${path} — not unique, pass replace_all or narrow it`;
|
|
327
|
-
|
|
408
|
+
// Both paths replace LITERALLY: split/join never interprets $-patterns, and the single-edit replace uses a
|
|
409
|
+
// function replacement so `$$`, `$&`, `` $` ``, `$'` and `$n` in new_string are inserted verbatim (a string
|
|
410
|
+
// 2nd arg would expand them and corrupt the result for any new_string containing a `$`).
|
|
411
|
+
const next = replaceAll ? src.split(oldStr).join(newStr) : src.replace(oldStr, () => newStr);
|
|
328
412
|
await writeFile(path, next, "utf8");
|
|
413
|
+
await noteFileRead(path); // refresh the ledger to the post-edit state so a follow-up edit of the same file is allowed
|
|
329
414
|
const n = replaceAll ? count : 1;
|
|
330
415
|
return `edited ${path} (${n} replacement${n === 1 ? "" : "s"})`;
|
|
331
416
|
}
|
|
@@ -996,7 +1081,9 @@ async function emailSend(args) {
|
|
|
996
1081
|
if (!key)
|
|
997
1082
|
return "error: email sending isn't configured on this machine (Quill key missing). Ask the fleet owner to set it.";
|
|
998
1083
|
const url = process.env.KODE_QUILL_URL || "http://127.0.0.1:8025/send";
|
|
999
|
-
const from = process.env.KODE_QUILL_FROM
|
|
1084
|
+
const from = process.env.KODE_QUILL_FROM;
|
|
1085
|
+
if (!from)
|
|
1086
|
+
return "error: email sending isn't configured on this machine (no sender address). Set OPERATOR_QUILL_FROM.";
|
|
1000
1087
|
const html = args.html != null ? str(args.html) : undefined;
|
|
1001
1088
|
const ctrl = new AbortController();
|
|
1002
1089
|
const timer = setTimeout(() => ctrl.abort(), 25_000);
|
|
@@ -1175,7 +1262,7 @@ async function downloadFileTool(args) {
|
|
|
1175
1262
|
}
|
|
1176
1263
|
pruneShellJobs();
|
|
1177
1264
|
if (runningJobCount() >= BG_MAX_RUNNING)
|
|
1178
|
-
return `error: ${BG_MAX_RUNNING} background jobs already running —
|
|
1265
|
+
return `error: ${BG_MAX_RUNNING} background jobs already running — stop one (bash_kill, on demand) before starting another`;
|
|
1179
1266
|
const id = newJobId();
|
|
1180
1267
|
const ac = new AbortController();
|
|
1181
1268
|
const job = createJob(id, `download_file ${url} -> ${opts.dest}`, { kill: () => ac.abort() }, "background");
|
|
@@ -1190,7 +1277,7 @@ async function downloadFileTool(args) {
|
|
|
1190
1277
|
trackJobOutput(job, `${p.total ? `${Math.round((p.bytes / p.total) * 100)}% ` : ""}${(p.bytes / 1e6).toFixed(1)} MB${p.total ? ` of ${(p.total / 1e6).toFixed(1)} MB` : ""} · ${(p.bytesPerSec / 1e6).toFixed(1)} MB/s\n`);
|
|
1191
1278
|
},
|
|
1192
1279
|
}).then((r) => { trackJobOutput(job, `${r.message}\n`); finishJob(job, r.ok ? 0 : 1); }, (e) => { trackJobOutput(job, `error: ${e.message}\n`); finishJob(job, 1); });
|
|
1193
|
-
return `started download job ${id}: ${url} -> ${opts.dest}\nYou will be notified when it finishes (the notice carries the final size and sha256, or the error), so do not poll. Progress: bash_output {"id":"${id}"}; stop: bash_kill {"id":"${id}"}. Do NOT claim it is downloaded until the notice says so.`;
|
|
1280
|
+
return `started download job ${id}: ${url} -> ${opts.dest}\nYou will be notified when it finishes (the notice carries the final size and sha256, or the error), so do not poll. Progress: bash_output {"id":"${id}"}; stop: bash_kill {"id":"${id}"} (on demand). Do NOT claim it is downloaded until the notice says so.`;
|
|
1194
1281
|
}
|
|
1195
1282
|
// --- Background / detached shell (checklist gap: shell_exec is synchronous with a timeout only). For a
|
|
1196
1283
|
// long-running command, shell_background spawns it detached, buffers output, and returns a job id to poll
|
|
@@ -1208,7 +1295,7 @@ async function shellBackground(args) {
|
|
|
1208
1295
|
return blind;
|
|
1209
1296
|
pruneShellJobs();
|
|
1210
1297
|
if (runningJobCount() >= BG_MAX_RUNNING)
|
|
1211
|
-
return `error: ${BG_MAX_RUNNING} background jobs already running —
|
|
1298
|
+
return `error: ${BG_MAX_RUNNING} background jobs already running — stop one (bash_kill, on demand) before starting another`;
|
|
1212
1299
|
const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
|
|
1213
1300
|
const { spawn } = await nodeImport("node:child_process");
|
|
1214
1301
|
const { file, args: argv } = await wrapShell(command); // same OS sandbox wrap as shell_exec
|
|
@@ -1227,7 +1314,7 @@ async function shellBackground(args) {
|
|
|
1227
1314
|
p.on("close", (c) => finishJob(job, c));
|
|
1228
1315
|
p.on("error", (e) => { trackJobOutput(job, `\n[spawn error: ${e.message}]`); finishJob(job, -1); });
|
|
1229
1316
|
const label = job.description ? ` (${job.description})` : "";
|
|
1230
|
-
return
|
|
1317
|
+
return `${STARTED_BACKGROUND_JOB}${id}${label}: ${command}\nYou will be notified when it finishes, so do not poll. Read output with bash_output {"id":"${id}"}; stop it with bash_kill {"id":"${id}"} (on demand).`;
|
|
1231
1318
|
}
|
|
1232
1319
|
async function verifyPipeline(args) {
|
|
1233
1320
|
const stages = args.stages;
|
|
@@ -1324,7 +1411,7 @@ function subAgentRedirect(id) {
|
|
|
1324
1411
|
return null;
|
|
1325
1412
|
return `${id} is a sub-agent (from spawn_agent), not a shell_background job — its result posts to the ` +
|
|
1326
1413
|
`conversation automatically when it finishes; don't poll it here. Use agent_status to check its real ` +
|
|
1327
|
-
`status, or message_agent to nudge it. bash_output/bash_kill only work on shell_background job ids.`;
|
|
1414
|
+
`status, or message_agent to nudge it (both on demand). bash_output/bash_kill only work on shell_background job ids.`;
|
|
1328
1415
|
}
|
|
1329
1416
|
async function bashOutput(args) {
|
|
1330
1417
|
const id = str(args.id);
|
|
@@ -1336,7 +1423,7 @@ async function bashOutput(args) {
|
|
|
1336
1423
|
return `error: no background job "${id}" (list ids from shell_background's return)`;
|
|
1337
1424
|
const out = job.buf;
|
|
1338
1425
|
job.buf = ""; // drain what's arrived since the last poll
|
|
1339
|
-
const status = job.done ?
|
|
1426
|
+
const status = job.done ? jobFinishedLine(id, job.code) : `[job ${id} running — ${Math.round((Date.now() - job.started) / 1000)}s elapsed]`;
|
|
1340
1427
|
return `${status}\n${out || "(no new output since last poll)"}`;
|
|
1341
1428
|
}
|
|
1342
1429
|
async function bashKill(args) {
|
|
@@ -1365,9 +1452,10 @@ export function renderActiveTasks() {
|
|
|
1365
1452
|
return ["[Your active task list was preserved across context compaction]", ...active.map((t) => `${TASK_MARK[t.status]} #${t.id} ${t.text} (${t.status})`)].join("\n");
|
|
1366
1453
|
}
|
|
1367
1454
|
async function taskAdd(args) {
|
|
1368
|
-
const
|
|
1455
|
+
const listed = Array.isArray(args.tasks) ? args.tasks.map(String).filter(Boolean) : [];
|
|
1456
|
+
const items = listed.length ? listed : [str(args.text)].filter(Boolean);
|
|
1369
1457
|
if (!items.length)
|
|
1370
|
-
return "error: task_add needs `
|
|
1458
|
+
return "error: task_add needs `tasks`, one string per step — e.g. tasks: [\"run the tests\"]";
|
|
1371
1459
|
for (const t of items)
|
|
1372
1460
|
agentTasks.push({ id: ++taskSeq, text: t, status: "pending" });
|
|
1373
1461
|
planRevision++;
|
|
@@ -1457,13 +1545,13 @@ function imageEndpoints() {
|
|
|
1457
1545
|
const defaults = ["https://image.axe.onl", "http://127.0.0.1:8791"];
|
|
1458
1546
|
return [...new Set([...gatewayEndpoints("images"), ...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
|
|
1459
1547
|
}
|
|
1460
|
-
/** Candidate IDENTITY-broker endpoints (reference-likeness: SDXL RealVisXL + IP-Adapter-FaceID
|
|
1461
|
-
*
|
|
1462
|
-
* a cold render (~80-90s to load the 9.4GB pipeline) never hits
|
|
1463
|
-
*
|
|
1548
|
+
/** Candidate IDENTITY-broker endpoints (reference-likeness: SDXL RealVisXL + IP-Adapter-FaceID). Used when
|
|
1549
|
+
* image_generate carries a `reference` (preserve a SPECIFIC face). KODE_IDENTITY_URL is tried FIRST: point it at
|
|
1550
|
+
* a worker on your own network so a cold render (~80-90s to load the 9.4GB pipeline) never hits the public host's
|
|
1551
|
+
* ~100s edge timeout (524). */
|
|
1464
1552
|
function identityEndpoints() {
|
|
1465
1553
|
const envs = [process.env.KODE_IDENTITY_URL].filter(Boolean);
|
|
1466
|
-
const defaults = ["
|
|
1554
|
+
const defaults = ["https://identity.axe.onl", "http://127.0.0.1:8793"];
|
|
1467
1555
|
return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
|
|
1468
1556
|
}
|
|
1469
1557
|
/** Media-broker auth: send a bearer token to the image/video/vision brokers when KODE_MEDIA_TOKEN is set.
|
|
@@ -1635,10 +1723,9 @@ function videoEndpoints() {
|
|
|
1635
1723
|
const envs = [process.env.KODE_VIDEO_URL].filter(Boolean);
|
|
1636
1724
|
// The LTX video broker lives at its OWN host (video.axe.onl), not the image host — do NOT fall back to the
|
|
1637
1725
|
// image endpoints, whose /health is 200 but which 404 on /v1/video (we'd pick a healthy-but-wrong broker).
|
|
1638
|
-
//
|
|
1639
|
-
//
|
|
1640
|
-
|
|
1641
|
-
const defaults = ["http://192.168.1.146:8792", "https://video.axe.onl"];
|
|
1726
|
+
// An LTX render takes >100s, which trips the public host's ~100s edge timeout (524): point KODE_VIDEO_URL at a
|
|
1727
|
+
// worker on your own network (tried first, no such cap). The public host is the fallback.
|
|
1728
|
+
const defaults = ["https://video.axe.onl"];
|
|
1642
1729
|
return [...new Set([...envs, ...defaults])].map((u) => u.replace(/\/$/, ""));
|
|
1643
1730
|
}
|
|
1644
1731
|
async function videoGenerate(args) {
|
|
@@ -1695,48 +1782,12 @@ async function videoGenerate(args) {
|
|
|
1695
1782
|
clearTimeout(timer);
|
|
1696
1783
|
}
|
|
1697
1784
|
}
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
// Enterprise-grade vision plumbing (mirrors the Python core's vision_tools.py strategy, adapted for a single-threaded
|
|
1702
|
-
// local 7B). Three parts: (1) proactive downscale — a VL model's cost scales with pixels, and full-res
|
|
1703
|
-
// (3680x2392 ~78s) stalls the worker past the timeout, which also blocks its /health and cascades retries
|
|
1704
|
-
// into "no vision service reachable"; downscaling the long edge to 1568px is a measured ~10x speedup with no
|
|
1705
|
-
// description-quality loss. (2) An ordered endpoint chain with per-endpoint health cooldown, so a busy /
|
|
1706
|
-
// rate-limited / 402'd target is skipped for a TTL instead of failing the turn. (3) An optional cloud
|
|
1707
|
-
// fallback (KODE_VISION_FALLBACK_URL, OpenAI-vision compatible) so a cold/busy local worker never hard-fails.
|
|
1708
|
-
const VISION_MAX_EDGE = Math.max(256, Number(process.env.KODE_VISION_MAX_EDGE) || 1568);
|
|
1709
|
-
const VISION_COOLDOWN_MS = Math.max(10_000, Number(process.env.KODE_VISION_COOLDOWN_MS) || 120_000);
|
|
1710
|
-
const visionUnhealthy = new Map(); // base url -> epoch ms it may be retried after
|
|
1711
|
-
/** Vision endpoints in priority order: KODE_VISION_URL, the fleet Qwen2-VL worker (JL1), then an optional
|
|
1712
|
-
* cloud fallback. Each carries its own auth + model; local targets get a /health gate, cloud targets don't. */
|
|
1713
|
-
function visionTargets(settings) {
|
|
1714
|
-
const seen = new Set();
|
|
1715
|
-
const out = [];
|
|
1716
|
-
const add = (u, auth, model, label) => {
|
|
1717
|
-
if (!u)
|
|
1718
|
-
return;
|
|
1719
|
-
const url = u.trim().replace(/\/$/, "");
|
|
1720
|
-
if (!url || seen.has(url))
|
|
1721
|
-
return;
|
|
1722
|
-
seen.add(url);
|
|
1723
|
-
const local = /\/\/(127\.0\.0\.1|localhost|192\.168\.|10\.|\[?::1)/.test(url) || /\.local(:|\/|$)/.test(url);
|
|
1724
|
-
out.push({ url, auth, model, local, label });
|
|
1725
|
-
};
|
|
1726
|
-
// Priority order, every source explicit — no baked endpoints. A loopback target gets a /health gate + the
|
|
1727
|
-
// point-of-need auto-on; a remote one is tried as-is. settings carries the real URLs (services.vision.*),
|
|
1728
|
-
// so a different box/deploy is one config edit, not a code change. The local worker is tried BEFORE the
|
|
1729
|
-
// remote fleet node: it's on THIS box (zero LAN cost, revivable), and omitting it was the bug that sent
|
|
1730
|
-
// image_analyze straight to a possibly-down remote node with no local fallback.
|
|
1731
|
-
const v = settings.services?.vision;
|
|
1732
|
-
add(process.env.KODE_VISION_URL, mediaAuth(), undefined, "env-override"); // explicit hard override
|
|
1733
|
-
add(v?.url, mediaAuth(), undefined, "local"); // this box's managed worker (loopback → auto-on)
|
|
1734
|
-
add(v?.remoteUrl, mediaAuth(), undefined, "remote"); // LAN fallback (another fleet node)
|
|
1735
|
-
add(process.env.KODE_VISION_FALLBACK_URL, // cloud fallback (never health-gated)
|
|
1736
|
-
process.env.KODE_VISION_FALLBACK_KEY ? { Authorization: `Bearer ${process.env.KODE_VISION_FALLBACK_KEY}` } : {}, process.env.KODE_VISION_FALLBACK_MODEL || undefined, "cloud-fallback");
|
|
1737
|
-
return out;
|
|
1785
|
+
async function visionSettings() {
|
|
1786
|
+
const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
|
|
1787
|
+
return loadSettings().services?.vision ?? {};
|
|
1738
1788
|
}
|
|
1739
|
-
|
|
1789
|
+
const visionLimit = (v, k, min) => Math.max(min, Number(v[k]) || VISION_LIMITS[k]);
|
|
1790
|
+
/** Read a local image, downscaling its long edge to `lim.maxEdge` first (macOS `sips`, then `ffmpeg`, then
|
|
1740
1791
|
* the original bytes — never upscales). http(s) urls pass straight through (the server fetches them). */
|
|
1741
1792
|
// Documents the vision model can't read as pixels — rendered to a PNG first (see renderDocForVision).
|
|
1742
1793
|
// macOS Quick Look (qlmanage) covers all of these with no extra install, so image_analyze works on a
|
|
@@ -1778,10 +1829,37 @@ async function renderDocForVision(path) {
|
|
|
1778
1829
|
return path;
|
|
1779
1830
|
}
|
|
1780
1831
|
}
|
|
1781
|
-
|
|
1832
|
+
/** The colour (#rrggbb) of an image that is one flat colour — a screenshot of a window that never painted —
|
|
1833
|
+
* or null when it holds any picture. A 32×32 BMP from sips is raw pixels, so no decoder is needed. */
|
|
1834
|
+
async function flatColour(pexec, image, bmp) {
|
|
1835
|
+
try {
|
|
1836
|
+
await pexec("sips", ["-s", "format", "bmp", "-z", "32", "32", image, "--out", bmp]);
|
|
1837
|
+
const { readFile } = await nodeImport("node:fs/promises");
|
|
1838
|
+
const b = (await readFile(bmp));
|
|
1839
|
+
const start = b.readUInt32LE(10), step = b.readUInt16LE(28) / 8;
|
|
1840
|
+
if (step < 3)
|
|
1841
|
+
return null;
|
|
1842
|
+
const lo = [255, 255, 255], hi = [0, 0, 0];
|
|
1843
|
+
for (let i = start; i + 2 < b.length; i += step) {
|
|
1844
|
+
for (let c = 0; c < 3; c++) {
|
|
1845
|
+
lo[c] = Math.min(lo[c], b[i + c]);
|
|
1846
|
+
hi[c] = Math.max(hi[c], b[i + c]);
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
if (hi.some((v, c) => v - lo[c] > 2))
|
|
1850
|
+
return null; // 2 = resampling noise, not a picture
|
|
1851
|
+
return `#${[2, 1, 0].map((c) => b[start + c].toString(16).padStart(2, "0")).join("")}`; // BMP stores BGR
|
|
1852
|
+
}
|
|
1853
|
+
catch {
|
|
1854
|
+
return null;
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
// Only a file this light for its pixel count is checked for flatness: a real picture never pays the extra sips call.
|
|
1858
|
+
const BLANK_BYTES_PER_PX = 0.1;
|
|
1859
|
+
async function visionImageDataUrl(image, lim) {
|
|
1782
1860
|
image = await absMediaPath(image);
|
|
1783
1861
|
if (/^https?:\/\//.test(image))
|
|
1784
|
-
return image;
|
|
1862
|
+
return { url: image };
|
|
1785
1863
|
image = await renderDocForVision(image); // a document becomes a rendered PNG; an image is unchanged
|
|
1786
1864
|
const { readFile } = await nodeImport("node:fs/promises");
|
|
1787
1865
|
const orig = await readFile(image).catch(() => null);
|
|
@@ -1805,15 +1883,21 @@ async function visionImageDataUrl(image) {
|
|
|
1805
1883
|
const { stdout } = await pexec("sips", ["-g", "pixelWidth", "-g", "pixelHeight", image]);
|
|
1806
1884
|
const w = Number((/pixelWidth:\s*(\d+)/.exec(stdout) || [])[1] || 0);
|
|
1807
1885
|
const h = Number((/pixelHeight:\s*(\d+)/.exec(stdout) || [])[1] || 0);
|
|
1808
|
-
if (
|
|
1809
|
-
|
|
1810
|
-
|
|
1886
|
+
if (w && h && buf.length < w * h * BLANK_BYTES_PER_PX) {
|
|
1887
|
+
const flat = await flatColour(pexec, image, join(dir, "t.bmp"));
|
|
1888
|
+
if (flat)
|
|
1889
|
+
return { blank: `${w}×${h}, one flat colour ${flat}, ${Math.max(1, Math.round(buf.length / 1024))} KB` };
|
|
1890
|
+
}
|
|
1891
|
+
if (!w || !h || (Math.max(w, h) <= lim.maxEdge && buf.length <= lim.maxBytes))
|
|
1892
|
+
return { url: `data:${mime};base64,${buf.toString("base64")}` }; // already small enough
|
|
1893
|
+
// sips -Z upscales a smaller image, so the box is clamped to the image itself.
|
|
1894
|
+
await pexec("sips", ["-Z", String(Math.min(lim.maxEdge, Math.max(w, h))), "-s", "format", "jpeg", image, "--out", out]);
|
|
1811
1895
|
shrank = true;
|
|
1812
1896
|
}
|
|
1813
1897
|
catch {
|
|
1814
1898
|
try {
|
|
1815
1899
|
// non-macOS / sips missing → ffmpeg; min() clamps the fit-box to the image so it never upscales.
|
|
1816
|
-
await pexec("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-i", image, "-vf", `scale='min(iw,${
|
|
1900
|
+
await pexec("ffmpeg", ["-nostdin", "-y", "-loglevel", "error", "-i", image, "-vf", `scale='min(iw,${lim.maxEdge})':'min(ih,${lim.maxEdge})':force_original_aspect_ratio=decrease`, out]);
|
|
1817
1901
|
shrank = true;
|
|
1818
1902
|
}
|
|
1819
1903
|
catch {
|
|
@@ -1833,118 +1917,16 @@ async function visionImageDataUrl(image) {
|
|
|
1833
1917
|
}
|
|
1834
1918
|
}
|
|
1835
1919
|
catch { /* any resize failure → original bytes (correctness over speed) */ }
|
|
1836
|
-
return `data:${mime};base64,${buf.toString("base64")}
|
|
1837
|
-
}
|
|
1838
|
-
/** One
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
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 }),
|
|
1847
|
-
});
|
|
1848
|
-
if (!res.ok)
|
|
1849
|
-
return { status: res.status, body: (await res.text().catch(() => "")).slice(0, 180) };
|
|
1850
|
-
const j = (await res.json().catch(() => ({})));
|
|
1851
|
-
return { text: j.choices?.[0]?.message?.content?.trim() || "" };
|
|
1852
|
-
}
|
|
1853
|
-
catch (e) {
|
|
1854
|
-
const aborted = e?.name === "AbortError";
|
|
1855
|
-
return { aborted, error: aborted ? `timed out after ${Math.round(timeout / 1000)}s` : String(e?.message ?? e) };
|
|
1856
|
-
}
|
|
1857
|
-
finally {
|
|
1858
|
-
clearTimeout(timer);
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
/** The gateway path: one backend, the router owns failover. Returns the answer, throws a final error, or
|
|
1862
|
-
* returns `fallthrough` when the gateway can't serve vision at all (unreachable / no healthy leg) so the
|
|
1863
|
-
* caller may try the direct chain. */
|
|
1864
|
-
async function visionViaGateway(gw, parts, args, timeout) {
|
|
1865
|
-
// A per-call model is honored only when it names one of our own vision routes; anything else (an old
|
|
1866
|
-
// direct-server id, a free catalog model) would bypass the route's privacy decision, so the route is used.
|
|
1867
|
-
const model = gatewayModelAllowed(str(args.model)) ? str(args.model) : gw.model;
|
|
1868
|
-
let last = "";
|
|
1869
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1870
|
-
const r = await postVision(gw.base, gw.auth, model, parts, args, timeout);
|
|
1871
|
-
if (r.text)
|
|
1872
|
-
return { text: r.text };
|
|
1873
|
-
if (r.text === "") {
|
|
1874
|
-
last = `${gw.label} returned no text`;
|
|
1875
|
-
continue;
|
|
1876
|
-
}
|
|
1877
|
-
if (r.status === 502 || r.status === 503 || r.status === 504)
|
|
1878
|
-
return { fallthrough: `${gw.label} ${gw.base} returned ${r.status}${r.body ? ` — ${r.body}` : ""}` };
|
|
1879
|
-
if (r.status)
|
|
1880
|
-
throw new Error(`${gw.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`);
|
|
1881
|
-
if (r.aborted)
|
|
1882
|
-
throw new Error(`${gw.label} ${r.error}`);
|
|
1883
|
-
return { fallthrough: `${gw.label} ${gw.base} unreachable (${r.error})` };
|
|
1884
|
-
}
|
|
1885
|
-
throw new Error(last);
|
|
1886
|
-
}
|
|
1887
|
-
/** Send a vision chat. Through the gateway's `vision` route when one resolves (vision-gateway.ts); the
|
|
1888
|
-
* direct endpoint chain below runs only for an owner pin or when no gateway can serve vision: skip any
|
|
1889
|
-
* target in cooldown, /health-gate local targets, time each independently, retry once on an empty body,
|
|
1890
|
-
* and on timeout / 402 / 429 / auth-error mark the target unhealthy for a TTL and fall through to the next.
|
|
1891
|
-
* Throws with the last error only when all are exhausted. */
|
|
1892
|
-
async function visionComplete(parts, args, defaultTimeoutMs) {
|
|
1893
|
-
const { loadSettings } = await nodeImport("../config/settings.js"); // variable-specifier load keeps settings out of the browser graph
|
|
1894
|
-
const settings = loadSettings();
|
|
1895
|
-
const timeout = Math.max(5_000, Number(args.timeout_ms ?? defaultTimeoutMs));
|
|
1896
|
-
const gw = await resolveVisionGateway(settings);
|
|
1897
|
-
let gatewayNote = "";
|
|
1898
|
-
if (gw) {
|
|
1899
|
-
const g = await visionViaGateway(gw, parts, args, timeout);
|
|
1900
|
-
if ("text" in g)
|
|
1901
|
-
return g.text;
|
|
1902
|
-
gatewayNote = `${g.fallthrough}; `;
|
|
1903
|
-
}
|
|
1904
|
-
const targets = visionTargets(settings);
|
|
1905
|
-
const now = () => Date.now();
|
|
1906
|
-
let lastErr = `no vision service reachable (tried ${targets.map((t) => t.url).join(", ")})`;
|
|
1907
|
-
for (const t of targets) {
|
|
1908
|
-
if ((visionUnhealthy.get(t.url) || 0) > now()) {
|
|
1909
|
-
lastErr = `${t.label} in cooldown`;
|
|
1910
|
-
continue;
|
|
1911
|
-
}
|
|
1912
|
-
if (t.local && !(await imageHealthy(t.url))) {
|
|
1913
|
-
// Media pipeline is off BY DEFAULT (ADR 2026-10-19 — GPU stays with Aurora), so a dead LOCAL vision
|
|
1914
|
-
// worker is the EXPECTED state, not an outage: bring it up at point of need (single-flight; repairs a
|
|
1915
|
-
// launchd-disabled job too) and re-probe before condemning the target. Loopback only — a remote LAN
|
|
1916
|
-
// worker (JL1) isn't served by this box's launchd job.
|
|
1917
|
-
const loopback = /\/\/(127\.0\.0\.1|localhost|\[?::1)/.test(t.url);
|
|
1918
|
-
const revived = loopback && await import("../services/preflight.js").then((m) => m.ensureVisionUp(t.url)).catch(() => false);
|
|
1919
|
-
if (!(revived && await imageHealthy(t.url))) {
|
|
1920
|
-
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1921
|
-
lastErr = `${t.label} health check failed at ${t.url}`;
|
|
1922
|
-
continue;
|
|
1923
|
-
}
|
|
1924
|
-
}
|
|
1925
|
-
const model = str(args.model) || t.model || "mlx-community/Qwen2-VL-7B-Instruct-4bit";
|
|
1926
|
-
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1927
|
-
const r = await postVision(`${t.url}/v1`, t.auth, model, parts, args, timeout);
|
|
1928
|
-
if (r.text)
|
|
1929
|
-
return r.text;
|
|
1930
|
-
if (r.text === "") {
|
|
1931
|
-
lastErr = `${t.label} returned no text`;
|
|
1932
|
-
continue;
|
|
1933
|
-
} // empty → retry once, then next endpoint
|
|
1934
|
-
if (r.status) {
|
|
1935
|
-
if (r.status === 401 || r.status === 402 || r.status === 403 || r.status === 429 || /credit|insufficient|quota|billing/i.test(r.body || ""))
|
|
1936
|
-
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1937
|
-
lastErr = `${t.label} returned ${r.status}${r.body ? ` — ${r.body}` : ""}`;
|
|
1938
|
-
break; // non-200 → next endpoint
|
|
1939
|
-
}
|
|
1940
|
-
lastErr = `${t.label}${r.aborted ? " " : ": "}${r.error}`;
|
|
1941
|
-
if (r.aborted) {
|
|
1942
|
-
visionUnhealthy.set(t.url, now() + VISION_COOLDOWN_MS);
|
|
1943
|
-
break;
|
|
1944
|
-
} // busy/slow → cooldown + next endpoint
|
|
1945
|
-
}
|
|
1946
|
-
}
|
|
1947
|
-
throw new Error(gatewayNote + lastErr);
|
|
1920
|
+
return { url: `data:${mime};base64,${buf.toString("base64")}` };
|
|
1921
|
+
}
|
|
1922
|
+
/** One vision chat through the gateway's `vision` route (vision-gateway.ts), inside one deadline.
|
|
1923
|
+
* Throws the plain "vision is down: …" line when none answers. */
|
|
1924
|
+
async function visionComplete(parts, args, v, defaultTimeoutMs = visionLimit(v, "timeoutMs", 5_000)) {
|
|
1925
|
+
return askVision(visionGateways(v), {
|
|
1926
|
+
system: VISION_SYS, parts, model: str(args.model),
|
|
1927
|
+
maxTokens: Math.max(1, Number(args.max_tokens) || visionLimit(v, "maxTokens", 1)),
|
|
1928
|
+
timeoutMs: Math.max(5_000, Number(args.timeout_ms) || defaultTimeoutMs),
|
|
1929
|
+
});
|
|
1948
1930
|
}
|
|
1949
1931
|
// Uncensoring system prompt for the vision model (owner's private system): the engine-level unrestricted
|
|
1950
1932
|
// layer only sees chat() turns, not these direct vision calls, so the analyze side gets its own one-line
|
|
@@ -2039,19 +2021,23 @@ async function imageAnalyze(args) {
|
|
|
2039
2021
|
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}`;
|
|
2040
2022
|
}
|
|
2041
2023
|
}
|
|
2042
|
-
|
|
2024
|
+
const v = await visionSettings();
|
|
2025
|
+
let img;
|
|
2043
2026
|
try {
|
|
2044
|
-
|
|
2027
|
+
// downscales a large local image first; http(s) passes through
|
|
2028
|
+
img = await visionImageDataUrl(image, { maxEdge: visionLimit(v, "maxEdge", 256), maxBytes: visionLimit(v, "maxBytes", 100_000) });
|
|
2045
2029
|
}
|
|
2046
2030
|
catch {
|
|
2047
2031
|
return `error: image_analyze could not read a file at ${image} (pass a local path or an http(s) url)`;
|
|
2048
2032
|
}
|
|
2049
|
-
|
|
2033
|
+
if ("blank" in img)
|
|
2034
|
+
return `error: image is blank (${img.blank}) — ${image}. Nothing to analyze; capture it again.`;
|
|
2035
|
+
const parts = [{ type: "text", text: question }, { type: "image_url", image_url: { url: img.url } }];
|
|
2050
2036
|
try {
|
|
2051
|
-
return await visionComplete(parts, args,
|
|
2037
|
+
return await visionComplete(parts, args, v);
|
|
2052
2038
|
}
|
|
2053
2039
|
catch (e) {
|
|
2054
|
-
return `error:
|
|
2040
|
+
return `error: ${String(e?.message ?? e)}`;
|
|
2055
2041
|
}
|
|
2056
2042
|
}
|
|
2057
2043
|
// video_analyze — real video understanding: ffmpeg samples frames evenly across the clip, then the VL model
|
|
@@ -2103,7 +2089,7 @@ async function videoAnalyze(args) {
|
|
|
2103
2089
|
const b = await readFile(join(dir, f));
|
|
2104
2090
|
parts.push({ type: "image_url", image_url: { url: `data:image/png;base64,${b.toString("base64")}` } });
|
|
2105
2091
|
}
|
|
2106
|
-
const text = await visionComplete(parts, args, 180_000);
|
|
2092
|
+
const text = await visionComplete(parts, args, await visionSettings(), 180_000);
|
|
2107
2093
|
return `video analysis (${picked.length} frames) → ${text}`;
|
|
2108
2094
|
}
|
|
2109
2095
|
catch (e) {
|
|
@@ -2138,51 +2124,17 @@ async function imageRecreate(args) {
|
|
|
2138
2124
|
const seen = extracted.length > 280 ? extracted.slice(0, 280) + "…" : extracted;
|
|
2139
2125
|
return `${gen}\n ↳ recreated from your reference. Understood as: ${seen}\n (self-review: image_analyze the result and compare to the reference; refine + rerun if it's off.)`;
|
|
2140
2126
|
}
|
|
2141
|
-
// artifact_create — the NATIVE "make a shareable page/
|
|
2142
|
-
// artifact surface
|
|
2143
|
-
//
|
|
2144
|
-
// create for a page/svg/markdown; compose/canvas for interactive HTML/JS (animations, visualizations, decks).
|
|
2127
|
+
// artifact_create — the NATIVE "make a shareable page/deck/doc/image/video" path, for every surface: publishes to
|
|
2128
|
+
// Temple (products/temple.ts, the one artifact surface) as the signed-in owner and returns the 0perator.co share link.
|
|
2129
|
+
// Operator never hunts for an artifact MCP, hand-rolls an HTML file, or asks where artifacts go — it makes one.
|
|
2145
2130
|
async function artifactCreate(args) {
|
|
2146
|
-
const
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
const
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
const canvas = ct === "canvas";
|
|
2154
|
-
const rpc = {
|
|
2155
|
-
jsonrpc: "2.0", id: 1, method: "tools/call",
|
|
2156
|
-
params: canvas
|
|
2157
|
-
? { name: "compose/canvas", arguments: { html: content, title } }
|
|
2158
|
-
: { name: "compose/create", arguments: { content, content_type: ct, title } },
|
|
2159
|
-
};
|
|
2160
|
-
const token = process.env.KODE_COMPOSE_TOKEN || process.env.KODE_OPERATOR_TOKEN || process.env.OPERATOR_TOKEN;
|
|
2161
|
-
const ctrl = new AbortController();
|
|
2162
|
-
const timer = setTimeout(() => ctrl.abort(), Number(args.timeout_ms ?? 30_000));
|
|
2163
|
-
try {
|
|
2164
|
-
const res = await fetch(`${base}/mcp`, {
|
|
2165
|
-
method: "POST", signal: ctrl.signal,
|
|
2166
|
-
headers: { "Content-Type": "application/json", "User-Agent": "operator/kode-tsi", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
|
2167
|
-
body: JSON.stringify(rpc),
|
|
2168
|
-
});
|
|
2169
|
-
if (!res.ok)
|
|
2170
|
-
return `error: compose.casa returned ${res.status} — the artifact surface is at ${base}/mcp — if it moved, the owner needs to update Operator's compose endpoint.`;
|
|
2171
|
-
const j = (await res.json().catch(() => ({})));
|
|
2172
|
-
if (j.error)
|
|
2173
|
-
return `error: compose.casa: ${j.error.message ?? "unknown error"}`;
|
|
2174
|
-
const text = (j.result?.content ?? []).map((c) => c.text ?? "").join(" ").trim();
|
|
2175
|
-
const rel = text.match(/\/v\/[A-Za-z0-9_-]+/); // compose returns a relative "/v/<id>"
|
|
2176
|
-
const url = rel ? `${base}${rel[0]}` : (text.match(/https?:\/\/\S+/) || [])[0];
|
|
2177
|
-
return url ? `created artifact → ${url}` : (text ? `artifact created: ${text}` : "artifact created (no URL returned)");
|
|
2178
|
-
}
|
|
2179
|
-
catch (e) {
|
|
2180
|
-
const msg = e?.name === "AbortError" ? "timed out" : String(e?.message ?? e);
|
|
2181
|
-
return `error: could not reach the artifact surface at ${base}/mcp (${msg})`;
|
|
2182
|
-
}
|
|
2183
|
-
finally {
|
|
2184
|
-
clearTimeout(timer);
|
|
2185
|
-
}
|
|
2131
|
+
const temple = (await nodeImport("../products/temple.js"));
|
|
2132
|
+
const paths = Array.isArray(args.paths) ? args.paths.map(String).filter(Boolean) : [];
|
|
2133
|
+
const visibility = /^(private|link|public)$/.test(str(args.visibility)) ? str(args.visibility) : "link";
|
|
2134
|
+
const r = await temple.publish({ title: str(args.title) || "Operator artifact", content: str(args.content) || undefined, content_type: str(args.content_type) || undefined, kind: str(args.kind) || undefined, paths, visibility });
|
|
2135
|
+
if (!r.ok)
|
|
2136
|
+
return `error: ${r.error}${/reach|timed out/.test(r.error) ? " — if this persists, write a local file with file_create instead" : ""}`;
|
|
2137
|
+
return `created ${r.value.kind} artifact ${r.value.id} (v${r.value.version}, ${r.value.visibility}) → ${r.value.share}`;
|
|
2186
2138
|
}
|
|
2187
2139
|
// voice_speak / voice_transcribe — Operator's OWN voice (operator-voice :8099: Kokoro TTS + whisper.cpp STT).
|
|
2188
2140
|
// Same backend-broker shape as the media tools: env-configurable base (KODE_VOICE_URL), /health-gated, graceful
|
|
@@ -2302,7 +2254,7 @@ const TOOLS = [
|
|
|
2302
2254
|
command: { type: "string", description: "the command to run" },
|
|
2303
2255
|
description: { type: "string", description: "short label for the UI" },
|
|
2304
2256
|
cwd: { type: "string", description: "run this one command here (the session's cwd is unchanged)" },
|
|
2305
|
-
timeout_ms: { type: "number", description: "default 120000; on timeout the command is killed
|
|
2257
|
+
timeout_ms: { type: "number", description: "default 120000; on timeout the command is killed" },
|
|
2306
2258
|
}, required: ["command"] },
|
|
2307
2259
|
run: shellExec,
|
|
2308
2260
|
},
|
|
@@ -2319,7 +2271,7 @@ const TOOLS = [
|
|
|
2319
2271
|
{
|
|
2320
2272
|
name: "shell_background", safe: false,
|
|
2321
2273
|
contract: { v: 1, effects: ["exec"], bins: ["bash", "sandbox-exec", "bwrap"] },
|
|
2322
|
-
description: "Start a long-running command DETACHED and get a job id at once. Use it from the start for servers, builds, watchers and full test suites — anything over ~2 minutes, which bash's timeout would kill. You are notified when it ends (don't poll); bash_output reads its output
|
|
2274
|
+
description: "Start a long-running command DETACHED and get a job id at once. Use it from the start for servers, builds, watchers and full test suites — anything over ~2 minutes, which bash's timeout would kill. You are notified when it ends (don't poll); bash_output reads its output.",
|
|
2323
2275
|
parameters: { type: "object", properties: { command: { type: "string" }, description: { type: "string" }, cwd: { type: "string" } }, required: ["command"] },
|
|
2324
2276
|
run: shellBackground,
|
|
2325
2277
|
},
|
|
@@ -2341,7 +2293,7 @@ const TOOLS = [
|
|
|
2341
2293
|
},
|
|
2342
2294
|
{
|
|
2343
2295
|
name: "bash_output", safe: true,
|
|
2344
|
-
description: "Read new output from a background shell job (shell_background or ctrl+b) and whether it is still running. Finished jobs are announced — don't poll. Not for spawn_agent ids
|
|
2296
|
+
description: "Read new output from a background shell job (shell_background or ctrl+b) and whether it is still running. Finished jobs are announced — don't poll. Not for spawn_agent ids.",
|
|
2345
2297
|
parameters: { type: "object", properties: { id: { type: "string", description: "the job id" } }, required: ["id"] },
|
|
2346
2298
|
run: bashOutput,
|
|
2347
2299
|
},
|
|
@@ -2382,8 +2334,8 @@ const TOOLS = [
|
|
|
2382
2334
|
},
|
|
2383
2335
|
{
|
|
2384
2336
|
name: "task_add", safe: false,
|
|
2385
|
-
description: "Write the plan FIRST for multi-step work (3+ steps) or several user tasks: every step its own item, every \"all N\" instance enumerated so none is dropped. Order is priority. The owner sees the list live, so it replaces restating the plan in prose. `
|
|
2386
|
-
parameters: { type: "object", properties: { text: { type: "string" }, tasks: { type: "array", items: { type: "string" } } } },
|
|
2337
|
+
description: "Write the plan FIRST for multi-step work (3+ steps) or several user tasks: every step its own item, every \"all N\" instance enumerated so none is dropped. Order is priority. The owner sees the list live, so it replaces restating the plan in prose. `tasks` takes one string per task; returns each id.",
|
|
2338
|
+
parameters: { type: "object", properties: { text: { type: "string" }, tasks: { type: "array", items: { type: "string" } } }, required: ["tasks"] },
|
|
2387
2339
|
run: taskAdd,
|
|
2388
2340
|
},
|
|
2389
2341
|
{
|
|
@@ -2406,10 +2358,10 @@ const TOOLS = [
|
|
|
2406
2358
|
},
|
|
2407
2359
|
{
|
|
2408
2360
|
name: "file_read", safe: true,
|
|
2409
|
-
contract: { v:
|
|
2361
|
+
contract: { v: 3, effects: ["read"], bins: ["osascript", "textutil", "unzip"] },
|
|
2410
2362
|
description: "Read a file, optionally a line range, with line numbers. Without offset/limit, only the first 2000 lines are returned — pass offset/limit to page through a larger file. For very long lines (minified code, one-line JSON or logs) page by character instead: start_char (and max_chars, up to 38000) returns the exact raw text with no line numbers.",
|
|
2411
2363
|
parameters: { type: "object", properties: {
|
|
2412
|
-
path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" },
|
|
2364
|
+
path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" }, force: { type: "boolean" },
|
|
2413
2365
|
start_char: { type: "number", description: "raw mode: character offset to start at (0-based); the reply names the next start_char" },
|
|
2414
2366
|
max_chars: { type: "number", description: "raw mode: characters to return (default and max 38000)" },
|
|
2415
2367
|
}, required: ["path"] },
|
|
@@ -2480,7 +2432,7 @@ const TOOLS = [
|
|
|
2480
2432
|
{
|
|
2481
2433
|
name: "search", safe: true,
|
|
2482
2434
|
contract: { v: 1, effects: ["read"], bins: ["rg", "grep"] },
|
|
2483
|
-
description: "Fast content search (ripgrep: parallel, .gitignore-aware, skips binaries) — prefer it over `find … | grep`. Scope with `path` (default: current dir). HARD REFUSAL: path may not be $HOME, /, /Users or another machine-wide root (they hang for minutes) — use find_files for names, a narrow subtree for content. `glob` filters filenames; files_with_matches returns just the paths (locate before you read).",
|
|
2435
|
+
description: "Fast content search (ripgrep: parallel, .gitignore-aware, skips binaries) — prefer it over `find … | grep`. Scope with `path` (default: current dir). HARD REFUSAL: path may not be $HOME, /, /Users or another machine-wide root (they hang for minutes) — use find_files (on demand) for names, a narrow subtree for content. `glob` filters filenames; files_with_matches returns just the paths (locate before you read).",
|
|
2484
2436
|
parameters: { type: "object", properties: {
|
|
2485
2437
|
pattern: { type: "string", description: "regex" },
|
|
2486
2438
|
path: { type: "string", description: "directory scope (default current dir; not $HOME or /)" },
|
|
@@ -2685,7 +2637,7 @@ const TOOLS = [
|
|
|
2685
2637
|
parameters: { type: "object", properties: {
|
|
2686
2638
|
image: { type: "string", description: "local path or http(s) url — an image, or a document (returned as text)" },
|
|
2687
2639
|
question: { type: "string", description: "default \"Describe this image in detail.\"" },
|
|
2688
|
-
max_tokens: { type: "number", description: "
|
|
2640
|
+
max_tokens: { type: "number", description: "answer cap (default 1024)" },
|
|
2689
2641
|
timeout_ms: { type: "number", description: "default 120000" },
|
|
2690
2642
|
as_image: { type: "boolean", description: "document: look at its first page as an image (layout, charts)" },
|
|
2691
2643
|
}, required: ["image"] },
|
|
@@ -2708,7 +2660,7 @@ const TOOLS = [
|
|
|
2708
2660
|
video: { type: "string", description: "local path or http(s) url" },
|
|
2709
2661
|
question: { type: "string", description: "default: describe what happens" },
|
|
2710
2662
|
frames: { type: "number", description: "2-16 (default 8)" },
|
|
2711
|
-
max_tokens: { type: "number", description: "
|
|
2663
|
+
max_tokens: { type: "number", description: "answer cap (default 1024)" },
|
|
2712
2664
|
timeout_ms: { type: "number", description: "default 180000" },
|
|
2713
2665
|
}, required: ["video"] },
|
|
2714
2666
|
run: videoAnalyze,
|
|
@@ -2749,12 +2701,15 @@ const TOOLS = [
|
|
|
2749
2701
|
},
|
|
2750
2702
|
{
|
|
2751
2703
|
name: "artifact_create",
|
|
2752
|
-
description: "Make a shareable hosted ARTIFACT
|
|
2704
|
+
description: "Make a shareable hosted ARTIFACT and get its share link. THE way to make an artifact: never write a local file instead. If the surface is unreachable, write a local file with file_create (.md for text) — not a PDF unless asked.",
|
|
2753
2705
|
parameters: { type: "object", properties: {
|
|
2754
|
-
content: { type: "string", description: "
|
|
2755
|
-
title: { type: "string"
|
|
2756
|
-
content_type: { type: "string", description: "html
|
|
2757
|
-
|
|
2706
|
+
content: { type: "string", description: "HTML, markdown, SVG or text (\"\" with paths)" },
|
|
2707
|
+
title: { type: "string" },
|
|
2708
|
+
content_type: { type: "string", description: "html|markdown|svg|text|canvas" },
|
|
2709
|
+
kind: { type: "string", description: "page|deck|doc|board|dashboard|app|image|video" },
|
|
2710
|
+
paths: { type: "array", items: { type: "string" }, description: "local files: images, video, assets" },
|
|
2711
|
+
visibility: { type: "string", description: "link|private|public" },
|
|
2712
|
+
}, required: ["content"] }, // a grammar-constrained model skips an optional argument: without this it publishes nothing, on repeat
|
|
2758
2713
|
run: artifactCreate,
|
|
2759
2714
|
},
|
|
2760
2715
|
{
|
|
@@ -3350,34 +3305,33 @@ function ownedMcpNote() {
|
|
|
3350
3305
|
// 150-char description per tool (~15K chars, ~4K tokens of the cached prefix duplicating the schemas); names
|
|
3351
3306
|
// alone keep the map at a tenth of that. Pass a merged map (native + connected MCP tools) to include those too;
|
|
3352
3307
|
// `lean` (a small-context model) skips the name list, which is also char-capped for a large merged map. `deferred`
|
|
3353
|
-
// (the `deferredTools` flag)
|
|
3354
|
-
// tool_search / tool_call.
|
|
3308
|
+
// (the `deferredTools` flag): only a core is attached, so the map names nothing — it says how to find the rest.
|
|
3355
3309
|
export function renderToolCatalogue(reg = registry, opts = {}) {
|
|
3356
|
-
const deferNote = opts.deferred?.size
|
|
3357
|
-
? `\nDeferred tools (no schema attached): find one with \`tool_search\`, run it with \`tool_call\`.`
|
|
3358
|
-
: "";
|
|
3359
3310
|
let head;
|
|
3360
|
-
if (opts.
|
|
3361
|
-
head = `Your
|
|
3311
|
+
if (opts.deferred) {
|
|
3312
|
+
head = `Your everyday tools are attached to every request. Many more are NOT attached — media, voice, browser and desktop control, ` +
|
|
3313
|
+
`memory, past sessions, skills, sub-agents, scheduling, ops, and every MCP tool: say what you need to \`tool_search\` ` +
|
|
3314
|
+
`(it returns the tool and its arguments), then run it with \`tool_call\`. A tool this prompt or a tool result names that is ` +
|
|
3315
|
+
`not attached ("on demand") runs through \`tool_call\` by that name, no search needed. Search before you say you cannot do something.`;
|
|
3316
|
+
}
|
|
3317
|
+
else if (opts.lean) {
|
|
3318
|
+
head = `Your tool schemas are attached to every request — they are the full list of what you can call; use a tool you HAVE, don't claim one you don't.`;
|
|
3362
3319
|
}
|
|
3363
3320
|
else {
|
|
3364
3321
|
const tools = [...reg.values()];
|
|
3365
3322
|
const names = [];
|
|
3366
|
-
const later = [];
|
|
3367
3323
|
let used = 0;
|
|
3368
3324
|
for (const t of tools) {
|
|
3369
3325
|
const name = `\`${t.name}\``;
|
|
3370
3326
|
if (used + name.length + 1 > CATALOGUE_LIST_CAP)
|
|
3371
3327
|
break;
|
|
3372
|
-
|
|
3328
|
+
names.push(name);
|
|
3373
3329
|
used += name.length + 1;
|
|
3374
3330
|
}
|
|
3375
|
-
const listed = names.length + later.length;
|
|
3376
3331
|
head =
|
|
3377
3332
|
`You act through TOOLS, not prose. Your ${tools.length} native tools, each already callable this session` +
|
|
3378
|
-
(
|
|
3379
|
-
` — how to call each is in its attached schema:\n` + names.join(" ")
|
|
3380
|
-
(later.length ? `${deferNote}\n` + later.join(" ") : "");
|
|
3333
|
+
(names.length < tools.length ? ` (first ${names.length} listed — the rest are in your attached tool schemas)` : "") +
|
|
3334
|
+
` — how to call each is in its attached schema:\n` + names.join(" ");
|
|
3381
3335
|
}
|
|
3382
3336
|
return (`\n\n## Your capabilities — the full surface (use a tool you HAVE; don't claim one you don't)\n` +
|
|
3383
3337
|
head +
|
|
@@ -3390,6 +3344,6 @@ export function renderToolCatalogue(reg = registry, opts = {}) {
|
|
|
3390
3344
|
`\n**Headless CLI modes** (how the owner runs you unattended — same engine + persona): \`operator run\` ` +
|
|
3391
3345
|
`(one task), \`operator loop\` (continuous), \`operator board\` / \`operator dream\` (autonomy), ` +
|
|
3392
3346
|
`\`operator media-robot\` (best-of-N media + vision-judge flywheel).` +
|
|
3393
|
-
`\n**Skills** — \`skill_list\` / \`skill_fetch\` / \`skill_save\` reach the 60k+ AXE skills catalogue ` +
|
|
3347
|
+
`\n**Skills** — \`skill_list\` / \`skill_fetch\` / \`skill_save\` (on demand) reach the 60k+ AXE skills catalogue ` +
|
|
3394
3348
|
`(curated + community); prefer applying an existing skill over rebuilding a capability from scratch.`);
|
|
3395
3349
|
}
|