@0perator/operator 0.1.360-next.1 → 0.2.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.
Files changed (54) hide show
  1. package/README.md +1 -1
  2. package/dist/autonomy/delegate-mode.js +159 -0
  3. package/dist/autonomy/delegate.js +1 -1
  4. package/dist/autonomy/session-factory.js +8 -2
  5. package/dist/background/index.js +26 -2
  6. package/dist/background/resume.js +125 -0
  7. package/dist/browser/engine.js +163 -0
  8. package/dist/browser/session.js +172 -134
  9. package/dist/cli.js +261 -70
  10. package/dist/config/settings.js +28 -7
  11. package/dist/config/skills-index.js +4 -0
  12. package/dist/engine/agent.js +1 -1
  13. package/dist/engine/aurora.js +22 -13
  14. package/dist/engine/compaction.js +1 -1
  15. package/dist/engine/moa.js +2 -1
  16. package/dist/engine/selfheal.js +1 -1
  17. package/dist/engine/speed-compaction.js +37 -0
  18. package/dist/engine/toolcalls.js +6 -6
  19. package/dist/gateway-cli.js +14 -5
  20. package/dist/index.js +3 -0
  21. package/dist/mcp/phone-server.js +30 -0
  22. package/dist/permissions/index.js +33 -17
  23. package/dist/permissions/signature.js +5 -0
  24. package/dist/phone-cli.js +65 -0
  25. package/dist/remote/host.js +31 -2
  26. package/dist/router/models.js +49 -25
  27. package/dist/selfimprove/index.js +1 -1
  28. package/dist/services/preflight.js +31 -8
  29. package/dist/session.js +96 -14
  30. package/dist/tools/deferred.js +1 -0
  31. package/dist/tools/device/android.js +227 -0
  32. package/dist/tools/device/classify.js +127 -0
  33. package/dist/tools/device/deps.js +69 -0
  34. package/dist/tools/device/desktop.js +82 -0
  35. package/dist/tools/device/harness.js +262 -0
  36. package/dist/tools/device/iphone.js +206 -0
  37. package/dist/tools/device/mirroring-jxa.js +146 -0
  38. package/dist/tools/device/setup.js +90 -0
  39. package/dist/tools/device/tools.js +70 -0
  40. package/dist/tools/device/types.js +19 -0
  41. package/dist/tools/registry.js +242 -48
  42. package/dist/tools/vision-media.js +162 -0
  43. package/dist/ui/App.js +4 -3
  44. package/dist/ui/ApprovalPrompt.js +10 -4
  45. package/dist/ui/BgPanel.js +2 -2
  46. package/dist/ui/UpdatePrompt.js +40 -0
  47. package/dist/ui/modelPicker.js +26 -8
  48. package/dist/ui/slashCommands.js +1 -0
  49. package/dist/update-check.js +134 -0
  50. package/dist/update.js +82 -13
  51. package/dist/util/slash.js +2 -2
  52. package/package.json +4 -2
  53. package/src/tools/device/NOTICE +37 -0
  54. package/dist/browser/cdp.js +0 -271
@@ -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/App.js CHANGED
@@ -30,6 +30,7 @@ import { SecretPrompt } from "./SecretPrompt.js";
30
30
  import { ArtifactPicker } from "./ArtifactPicker.js";
31
31
  import { SessionPicker } from "./SessionPicker.js";
32
32
  import { SkillFinder } from "./SkillFinder.js";
33
+ import { UpdatePrompt } from "./UpdatePrompt.js";
33
34
  import { pendingLines, turnKeySegs } from "./pending.js";
34
35
  import { nextStepLine } from "./nextStep.js";
35
36
  import { centreLayout, switcherLine } from "./conversations.js";
@@ -90,7 +91,7 @@ function ExpandKey({ onExpand, active }) {
90
91
  return null;
91
92
  }
92
93
  export function App(props) {
93
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, phase = null, fold = null, delegate = null, liveTools = [], route, ctxPct, ctxWindow, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], mainLane = null, mainServing, maxRunning, onBackground, tasks = [], planNow, onSubmit, onQueue, onSteer, pending = [], onEditQueued, onDropQueued, nextSteps, onPickNext, onDismissNext, agents = [], onAgentMessage, conversations = [], switcher, onSwitcher, onFocusSwitcher, conversationPane = null, onSendTo, actOffer = null, onActNow, finder = null, onOpenFinder, onInterrupt, onExpand, onCycleMode, onCycleContext, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, secretPrompt = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null } = props;
94
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, phase = null, fold = null, delegate = null, liveTools = [], route, ctxPct, ctxWindow, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, shellJobs = [], mainLane = null, mainServing, maxRunning, onBackground, tasks = [], planNow, onSubmit, onQueue, onSteer, pending = [], onEditQueued, onDropQueued, nextSteps, onPickNext, onDismissNext, agents = [], onAgentMessage, conversations = [], switcher, onSwitcher, onFocusSwitcher, conversationPane = null, onSendTo, actOffer = null, onActNow, finder = null, onOpenFinder, onInterrupt, onExpand, onCycleMode, onCycleContext, opMode, rcConnected = false, rcActive = false, caffeinated = false, approval = null, onApprovalDecide, question = null, modelPicker = null, secretPrompt = null, planExitPicker = null, artifactsPicker = null, sessionsPicker = null, update = null } = props;
94
95
  const cols = useTerminalSize().cols; // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
95
96
  const thinking = status === "thinking" || status === "streaming";
96
97
  // Tool rows exist before their calls run (TUI plan #8): from the first streamed argument (drafting) through waiting
@@ -107,12 +108,12 @@ export function App(props) {
107
108
  // arrives under it (an approval, an ask_user, the plan review) is drawn, waiting, and answered only once the overlay
108
109
  // closes, so nothing typed into the overlay can answer it. With no overlay open a pending prompt owns the keyboard and
109
110
  // the composer gives way, its next-step strip with it. Overlays open only from the composer, so never over a prompt.
110
- const promptUp = !!approval || !!question || !!modelPicker || !!secretPrompt || !!planExitPicker || !!artifactsPicker || !!sessionsPicker;
111
+ const promptUp = !!approval || !!question || !!modelPicker || !!secretPrompt || !!planExitPicker || !!artifactsPicker || !!sessionsPicker || !!update;
111
112
  const owner = finder ? "finder" : switcher?.focused ? "switcher" : promptUp ? "prompt" : "composer";
112
113
  const held = owner === "finder" || owner === "switcher";
113
114
  const waiting = owner === "finder" ? "esc closes the finder, then answer here" : "↑ hands the keyboard back, then answer here";
114
115
  // Prompts are kept out of the fullscreen clip region so they can't be scrolled off.
115
- const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }), suspended: held, waiting: waiting }), _jsx(QuestionPrompt, { pending: question, suspended: held, waiting: waiting }), _jsx(QuestionPrompt, { pending: modelPicker, suspended: held, waiting: waiting }), _jsx(SecretPrompt, { pending: secretPrompt, suspended: held }), _jsx(QuestionPrompt, { pending: planExitPicker, suspended: held, waiting: waiting }), _jsx(ArtifactPicker, { pending: artifactsPicker, suspended: held }), _jsx(SessionPicker, { pending: sessionsPicker, suspended: held }), _jsx(SkillFinder, { pending: finder })] }));
116
+ const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }), suspended: held, waiting: waiting }), _jsx(QuestionPrompt, { pending: question, suspended: held, waiting: waiting }), _jsx(QuestionPrompt, { pending: modelPicker, suspended: held, waiting: waiting }), _jsx(SecretPrompt, { pending: secretPrompt, suspended: held }), _jsx(QuestionPrompt, { pending: planExitPicker, suspended: held, waiting: waiting }), _jsx(ArtifactPicker, { pending: artifactsPicker, suspended: held }), _jsx(SessionPicker, { pending: sessionsPicker, suspended: held }), _jsx(UpdatePrompt, { pending: update, suspended: held }), _jsx(SkillFinder, { pending: finder })] }));
116
117
  // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
117
118
  // The mode line: the mode on the left, the conversation switcher in the centre, remote control on the right. The centre
118
119
  // gets what the two sides leave, so the row stays at cols−1.
@@ -15,6 +15,10 @@ function summarize(name, args) {
15
15
  case "computer_key": return `key: ${s(args.key)}${Array.isArray(args.modifiers) && args.modifiers.length ? ` +${args.modifiers.join("+")}` : ""}`;
16
16
  case "computer_click": return `click at ${s(args.x)},${s(args.y)}`;
17
17
  case "computer_screenshot": return "capture the screen to a file";
18
+ case "phone_tap": return `${args.device ? `${s(args.device)}: ` : ""}tap ${typeof args.text === "string" ? `"${s(args.text)}"` : `${s(args.x)},${s(args.y)}`}`;
19
+ case "phone_type": return `${args.device ? `${s(args.device)}: ` : ""}type ${String(args.text ?? "").length} characters${args.submit === true ? " and press enter" : ""}`;
20
+ case "phone_key": return `${args.device ? `${s(args.device)}: ` : ""}press ${s(args.key)}`;
21
+ case "phone_open_app": return `${args.device ? `${s(args.device)}: ` : ""}open ${s(args.name)}`;
18
22
  case "shell_exec": return `$ ${s(args.command, 120)}`;
19
23
  case "file_write": return `write ${s(args.path)}`;
20
24
  case "file_edit": return `edit ${s(args.path)}`;
@@ -33,15 +37,17 @@ export function ApprovalPrompt({ approval, onDecide, suspended = false, waiting
33
37
  onDecide(false, false); // Ctrl-C at the prompt = deny (bail out safely)
34
38
  else if (c === "a" || key.return)
35
39
  onDecide(true, false); // allow once
36
- else if (c === "s")
37
- onDecide(true, true); // allow always (this session)
40
+ else if (c === "s" && !approval.ctx?.once)
41
+ onDecide(true, true); // allow always (this session); never for a phone signature line
38
42
  else if (c === "d" || key.escape)
39
43
  onDecide(false, false); // deny
40
44
  }, { isActive: !!approval && !suspended });
41
45
  if (!approval)
42
46
  return null;
43
47
  const detail = summarize(approval.name, approval.args);
44
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [_jsxs(Text, { color: "yellow", bold: true, children: ["⚠ Operator wants to run ", _jsx(Text, { color: "magenta", children: approval.name })] }), detail ? _jsx(Text, { dimColor: true, children: " " + detail }) : null, suspended
48
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "yellow", paddingX: 1, children: [_jsxs(Text, { color: "yellow", bold: true, children: ["⚠ Operator wants to run ", _jsx(Text, { color: "magenta", children: approval.name })] }), detail ? _jsx(Text, { dimColor: true, children: " " + detail }) : null, approval.ctx ? _jsx(Text, { color: "red", bold: true, children: ` ${approval.ctx.line} — a human signs this one, every time` }) : null, approval.ctx?.preview ? _jsx(Text, { children: " the screen it will act on: " + approval.ctx.preview }) : null, suspended
45
49
  ? _jsx(Text, { dimColor: true, children: " waiting · " + (waiting ?? "another prompt has the keyboard") })
46
- : _jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "[a]" }), " allow once ", _jsx(Text, { color: "cyan", children: "[s]" }), " allow always ", _jsx(Text, { color: "red", children: "[d]" }), " deny ", _jsx(Text, { dimColor: true, children: "(Enter=allow \u00B7 Esc=deny)" })] })] }));
50
+ : approval.ctx?.once
51
+ ? _jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "[a]" }), " allow once ", _jsx(Text, { color: "red", children: "[d]" }), " deny ", _jsx(Text, { dimColor: true, children: "(Enter=allow \u00B7 Esc=deny)" })] })
52
+ : _jsxs(Text, { children: [" ", _jsx(Text, { color: "green", children: "[a]" }), " allow once ", _jsx(Text, { color: "cyan", children: "[s]" }), " allow always ", _jsx(Text, { color: "red", children: "[d]" }), " deny ", _jsx(Text, { dimColor: true, children: "(Enter=allow \u00B7 Esc=deny)" })] })] }));
47
53
  }
@@ -69,7 +69,7 @@ export function ledgerLine(a) {
69
69
  a.commands ? `ran ${a.commands}` : "",
70
70
  ].filter(Boolean).join(" · ");
71
71
  const verify = a.verified == null ? "" : a.verified ? "✓ verified" : `✗ unverified${a.verifyDetail ? `: ${cap(a.verifyDetail, 30)}` : ""}`;
72
- return [a.title ?? "assistant", a.model, done || (a.status === "working" ? "nothing written yet" : ""), verify, a.malformed ? "⚠ malformed" : ""]
72
+ return [a.title ?? "assistant", a.resumed ? "resumed" : "", a.model, done || (a.status === "working" ? "nothing written yet" : ""), verify, a.malformed ? "⚠ malformed" : ""]
73
73
  .filter(Boolean).join(" · ");
74
74
  }
75
75
  /** The third row (pure, testable): a stuck agent shows WHY and the exact commands to re-steer or stop it; a working one
@@ -167,7 +167,7 @@ export function mainLaneOf(m) {
167
167
  /** One sub-agent as a lane: its round and mission, who holds the slot it waits for, why it stopped. Pure. */
168
168
  export function agentLaneOf(a, now, ctx = {}) {
169
169
  const elapsedMs = a.status === "working" ? (a.startedAt !== undefined ? now - a.startedAt : undefined) : a.durationMs;
170
- const base = { key: a.id, name: a.name ?? a.id, role: a.title ?? "sub-agent", elapsedMs, tokens: a.tokens };
170
+ const base = { key: a.id, name: a.name ?? a.id, role: `${a.title ?? "sub-agent"}${a.resumed ? " · resumed" : ""}`, elapsedMs, tokens: a.tokens };
171
171
  const ledger = [a.written?.length ? `wrote ${a.written.length}` : "", a.reads ? `read ${a.reads}` : "", a.commands ? `ran ${a.commands}` : ""].filter(Boolean).join(" · ");
172
172
  const join = (...xs) => xs.filter(Boolean).join(" · ");
173
173
  if (a.status === "queued")
@@ -0,0 +1,40 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // The update-available prompt (update-check.ts): shown before the first turn when the startup check found a newer build.
3
+ // It owns the keyboard while up (App.tsx promptUp suspends the composer). Enter takes the highlighted choice, a digit takes
4
+ // its row, Esc or ctrl+c skips this launch.
5
+ import { useState } from "react";
6
+ import { Box, Text, useInput } from "ink";
7
+ const CHOICES = ["update", "skip", "skip-version"];
8
+ export function choiceLabels(p) {
9
+ return [`Update now (runs \`${p.command}\`)`, "Skip", "Skip until next version"];
10
+ }
11
+ /** Pure keystroke reducer: the next highlight, or the choice made. */
12
+ export function updateKey(sel, input, key) {
13
+ if (key.escape || (key.ctrl && input.toLowerCase() === "c"))
14
+ return { choice: "skip" };
15
+ if (key.return)
16
+ return { choice: CHOICES[sel] };
17
+ if (key.upArrow)
18
+ return { sel: (sel + CHOICES.length - 1) % CHOICES.length };
19
+ if (key.downArrow)
20
+ return { sel: (sel + 1) % CHOICES.length };
21
+ const n = Number(input);
22
+ if (Number.isInteger(n) && n >= 1 && n <= CHOICES.length)
23
+ return { choice: CHOICES[n - 1] };
24
+ return {};
25
+ }
26
+ export function UpdatePrompt({ pending, suspended = false }) {
27
+ const [sel, setSel] = useState(0);
28
+ useInput((input, key) => {
29
+ if (!pending)
30
+ return;
31
+ const r = updateKey(sel, input, key);
32
+ if (r.choice)
33
+ pending.resolve(r.choice);
34
+ else if (r.sel !== undefined)
35
+ setSel(r.sel);
36
+ }, { isActive: !!pending && !suspended });
37
+ if (!pending)
38
+ return null;
39
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsxs(Text, { bold: true, children: ["Update available · ", _jsx(Text, { dimColor: true, children: pending.current }), " → ", _jsx(Text, { color: "green", children: pending.version })] }), _jsx(Text, { dimColor: true, children: "Release notes: " + pending.notes }), _jsx(Text, { children: " " }), choiceLabels(pending).map((label, i) => (_jsxs(Text, { children: [i === sel ? _jsx(Text, { color: "cyan", bold: true, children: "› " }) : " ", _jsx(Text, { bold: i === sel, children: `${i + 1}. ${label}` })] }, label))), _jsx(Text, { children: " " }), _jsx(Text, { dimColor: true, children: suspended ? "waiting · another prompt has the keyboard" : "enter continue · esc skip" })] }));
40
+ }
@@ -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", "operator-dense"];
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
- const rows = ordered.map((m) => {
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 row is
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)];
@@ -19,6 +19,7 @@ export const SLASH_COMMANDS = [
19
19
  { name: "mode", description: "set operating mode: autonomous · manual · plan · gated", args: "[auto|manual|plan|gated]" },
20
20
  { name: "think", description: "toggle extended reasoning (think before answering)" },
21
21
  { name: "ultrathink", description: "toggle deep, exhaustive reasoning for hard problems" },
22
+ { name: "delegate", description: "any /model id as the MoA planner or the sub-agents; guard: no push, deploys or writes outside this repo", args: "[planner <model> [executor]|subagents <model>|guard on|off|push on|off|off]" },
22
23
  { name: "agents", description: "detailed sub-agent status: running/queued/done/errored + metrics" },
23
24
  { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
24
25
  { name: "jobs", description: "background shell jobs: list, or stop one (ctrl+b moves a running command here)", args: "[stop id]" },
@@ -0,0 +1,134 @@
1
+ // The update-available prompt (ui/UpdatePrompt.tsx): an interactive start of a packaged install asks the public download
2
+ // URL (update.ts) which version each channel holds, in the background, and offers a newer one before the first turn.
3
+ // Never for a subcommand (`operator run`, acp, mcp, update…), a non-TTY, CI, a source checkout (it updates by git), or
4
+ // with settings.updates.check false / OPERATOR_NO_UPDATE_CHECK=1. The answer is cached ~20 h in the Operator home's
5
+ // state folder, with the version "skip until next version" chose. Every failure is silent: no offer.
6
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { dirname } from "node:path";
8
+ import { operatorPath } from "./config/home.js";
9
+ import { channelOf, distBase, distTagsAsync, installedVersion, installPackaged, isOlder, isReleaseInstall, platformLabel, VERSION } from "./update.js";
10
+ export const CHECK_TTL_MS = 20 * 3600_000;
11
+ const FETCH_MS = 1500;
12
+ const REGISTRY_MS = 5000;
13
+ const NOTES = {
14
+ latest: "https://github.com/axetechnologies/kode/blob/main/CHANGELOG.md",
15
+ next: "https://github.com/axetechnologies/kode/blob/develop/CHANGELOG.md",
16
+ };
17
+ export const statePath = () => operatorPath("state", "update-check.json");
18
+ const on = (v) => !!v && v !== "0" && v.toLowerCase() !== "false";
19
+ /** Whether this launch checks at all. `argv` is process.argv: any subcommand (a bare word after the binary) is not an
20
+ * interactive start. */
21
+ export function checkEnabled(o) {
22
+ const sub = o.argv[2];
23
+ if (sub && !sub.startsWith("-"))
24
+ return false;
25
+ if (o.argv.includes("--version") || o.argv.includes("-V") || o.argv.includes("--help"))
26
+ return false;
27
+ if (!o.tty || on(o.env.CI) || on(o.env.OPERATOR_NO_UPDATE_CHECK) || on(o.env.KODE_NO_UPDATE_CHECK))
28
+ return false;
29
+ return o.settings.updates?.check !== false && !o.sourceCheckout;
30
+ }
31
+ /** What to offer: a newer build on the install's own channel; a next build also sees latest and gets the newer of the
32
+ * two (a release that has passed the prerelease it runs). Never an older or equal one (update.ts isOlder). */
33
+ export function pickOffer(current, found) {
34
+ const own = channelOf(current);
35
+ let best = null;
36
+ for (const channel of own === "next" ? ["next", "latest"] : ["latest"]) {
37
+ const v = found[channel];
38
+ if (!v || !isOlder(current, v) || (best && !isOlder(best.version, v)))
39
+ continue;
40
+ best = { version: v, channel };
41
+ }
42
+ return best;
43
+ }
44
+ /** The channel files at the public URL; when none answers (and not for an install.sh install, whose update never uses
45
+ * the registry) the registry's dist-tags of the same names. Unreachable everywhere = {}. */
46
+ export async function fetchVersions(own, o = {}) {
47
+ const want = own === "next" ? ["next", "latest"] : ["latest"];
48
+ const base = o.base ?? distBase();
49
+ const read = async (ch) => {
50
+ try {
51
+ const res = await fetch(`${base}/${ch}.txt`, { signal: AbortSignal.timeout(FETCH_MS) });
52
+ const v = res.ok ? (await res.text()).trim() : "";
53
+ return VERSION.test(v) ? v : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ };
59
+ const got = {};
60
+ await Promise.all(want.map(async (ch) => { const v = await read(ch); if (v)
61
+ got[ch] = v; }));
62
+ if (Object.keys(got).length || o.registry === false)
63
+ return got;
64
+ const t = await (o.tags ?? distTagsAsync)(REGISTRY_MS);
65
+ if ("error" in t)
66
+ return got;
67
+ for (const ch of want)
68
+ if (VERSION.test(t.tags[ch] ?? ""))
69
+ got[ch] = t.tags[ch];
70
+ return got;
71
+ }
72
+ export function readState(path = statePath()) {
73
+ try {
74
+ const s = JSON.parse(readFileSync(path, "utf8"));
75
+ return s && typeof s === "object" && !Array.isArray(s) ? s : {};
76
+ }
77
+ catch {
78
+ return {};
79
+ }
80
+ }
81
+ function writeState(state, path) {
82
+ mkdirSync(dirname(path), { recursive: true });
83
+ const tmp = `${path}.${process.pid}.tmp`;
84
+ writeFileSync(tmp, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
85
+ renameSync(tmp, path);
86
+ }
87
+ /** The offer for this launch, or null. A check younger than CHECK_TTL_MS is reused; a fresh one is written only when
88
+ * something answered, so a launch without network asks again next time. */
89
+ export async function checkForUpdate(current, o = {}) {
90
+ try {
91
+ const now = o.now ?? Date.now(), path = o.path ?? statePath();
92
+ const state = readState(path);
93
+ const fresh = typeof state.checkedAt === "number" && now >= state.checkedAt && now - state.checkedAt < CHECK_TTL_MS;
94
+ let found = { latest: state.latest, next: state.next };
95
+ if (!fresh) {
96
+ found = await (o.fetch ?? ((own) => fetchVersions(own, { registry: !isReleaseInstall() })))(channelOf(current));
97
+ if (found.latest || found.next)
98
+ writeState({ ...readState(path), checkedAt: now, latest: found.latest, next: found.next }, path);
99
+ }
100
+ const pick = pickOffer(current, found);
101
+ if (!pick || pick.version === state.skipVersion)
102
+ return null;
103
+ const command = pick.channel === channelOf(current) ? "operator update" : `operator update --${pick.channel}`;
104
+ return { current, ...pick, notes: NOTES[pick.channel], command };
105
+ }
106
+ catch {
107
+ return null;
108
+ }
109
+ }
110
+ /** "Skip until next version": this exact version is not offered again; a newer one is. */
111
+ export function skipVersion(version, path = statePath()) {
112
+ try {
113
+ writeState({ ...readState(path), skipVersion: version }, path);
114
+ }
115
+ catch { /* best-effort: it is asked again next launch */ }
116
+ }
117
+ /** "Update now", after the TUI has closed: the same packaged update `operator update` runs, then the version the next
118
+ * `operator` starts, read back. Success is said only when that read matches. */
119
+ export async function runOfferedUpdate(offer, o = {}) {
120
+ const say = o.write ?? ((s) => { process.stdout.write(s); });
121
+ say(`Updating Operator via \`${offer.command}\`...\n`);
122
+ say(`==> Updating Operator from ${offer.current} to ${offer.version}\n`);
123
+ say(`==> Detected platform: ${platformLabel()}\n`);
124
+ say(`==> Resolved version: ${offer.version}\n`);
125
+ const code = await installPackaged(offer.channel, true, o.pkgJson);
126
+ const now = installedVersion(o.pkgJson);
127
+ if (code === 0 && now === offer.version) {
128
+ say(`Operator ${now} installed successfully.\n`);
129
+ say("Update ran successfully. Please restart Operator.\n");
130
+ return 0;
131
+ }
132
+ say(`Operator ${offer.version} was not installed: \`operator\` still starts v${now ?? "?"}. Run \`${offer.command}\` to try again.\n`);
133
+ return code || 1;
134
+ }