@0perator/operator 0.1.263 → 0.1.274

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.
@@ -143,7 +143,14 @@ async function bringUp() {
143
143
  if (all.out === CONTAINER) {
144
144
  return (await docker(["start", CONTAINER])).code === 0;
145
145
  }
146
- // fresh run
146
+ // fresh run — pull the image FIRST with generous headroom. A cold `docker run` pulls inline, and the
147
+ // first-ever ~376MB SearXNG pull routinely exceeds a 60s run timeout on a normal/slow link → the setup
148
+ // Operator does FOR the user would fail silently on install. Pull explicitly (10 min) when the image is
149
+ // absent, then run against the now-local image under the short timeout.
150
+ if ((await docker(["image", "inspect", "--format", "{{.Id}}", image()], 8_000)).code !== 0) {
151
+ if ((await docker(["pull", image()], 600_000)).code !== 0)
152
+ return false;
153
+ }
147
154
  const dir = await ensureSettingsDir();
148
155
  const run = await docker([
149
156
  "run", "-d", "--name", CONTAINER, "--restart", "unless-stopped",
package/dist/ui/App.js CHANGED
@@ -4,7 +4,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
4
4
  // src/engine, src/tools, or src/router.
5
5
  import { useEffect, useRef, useState } from "react";
6
6
  import { Box, Text, measureElement } from "ink";
7
- import { termRows } from "./term.js";
7
+ import { useTerminalSize } from "./term.js";
8
8
  import { caps } from "./capabilities.js";
9
9
  import { MouseProvider, useOnWheel, useMouse } from "./MouseProvider.js";
10
10
  import { StatusRule } from "./StatusRule.js";
@@ -25,7 +25,8 @@ import { ArtifactPicker } from "./ArtifactPicker.js";
25
25
  // calls at once; anything past the cap is summarized as a count instead of another row.
26
26
  const MAX_LIVE_TOOL_ROWS = 6;
27
27
  export function App(props) {
28
- const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, onInterrupt, onCycleMode, opMode, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null } = props;
28
+ const { messages, live = null, status, thinkingVerb, verbs, stepLabel, liveTools = [], route, ctxPct, version, build, fullscreen = false, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, tasks = [], onSubmit, onQueue, queuedPreview = "", onInterrupt, onCycleMode, opMode, rcConnected = false, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null } = props;
29
+ useTerminalSize(); // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
29
30
  const thinking = status === "thinking" || status === "streaming";
30
31
  // A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
31
32
  // a lone call isn't worth a bordered block, the braille spinner + name already says enough.
@@ -39,7 +40,7 @@ export function App(props) {
39
40
  // be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
40
41
  const prompts = (_jsxs(_Fragment, { children: [_jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(QuestionPrompt, { pending: planExitPicker }), _jsx(ArtifactPicker, { pending: artifactsPicker })] }));
41
42
  // The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
42
- const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker }), _jsx(InputRule, {}), opMode && (_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "◆ Autonomous" : opMode === "manual" ? "◈ Manual" : "◔ Plan"} · shift+tab to cycle` }))] }));
43
+ const bottom = (_jsxs(_Fragment, { children: [_jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), queuedPreview ? (_jsx(Text, { color: "yellow", children: `⏎ queued · sends when this turn ends (Esc to send now): ${queuedPreview.replace(/\n/g, " / ").slice(0, 120)}${queuedPreview.length > 120 ? "…" : ""}` })) : null, _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, onCycleMode: onCycleMode, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker || !!planExitPicker || !!artifactsPicker }), _jsx(InputRule, {}), opMode && (_jsxs(Box, { justifyContent: "space-between", children: [_jsx(Text, { dimColor: true, children: ` ${opMode === "auto" ? "⎈ Autonomous" : opMode === "manual" ? "⊙ Manual" : "◑ Plan"} · shift+tab to cycle` }), _jsx(Text, { color: rcConnected ? "green" : "gray", bold: rcConnected, children: `${rcConnected ? "▮" : "▯"} rc ` })] }))] }));
43
44
  // Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
44
45
  // region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
45
46
  // no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
@@ -83,7 +84,7 @@ const WHEEL_STEP = 3;
83
84
  // any new output snaps straight back to it — you never get stranded in history while the answer grows.
84
85
  // Split out from App because useOnWheel must run inside the provider App itself returns.
85
86
  function FullscreenBody({ messages, live, activity, prompts, bottom }) {
86
- const rows = termRows();
87
+ const rows = useTerminalSize().rows; // reactive: the fullscreen body re-lays-out when the window resizes
87
88
  const [scrollBack, setScrollBack] = useState(0);
88
89
  // New settled output resets the view to the live bottom (messages.length only grows as entries settle).
89
90
  useEffect(() => { setScrollBack(0); }, [messages.length]);
@@ -5,6 +5,18 @@ import { theme } from "./theme.js";
5
5
  const GLYPH = { queued: "◌", working: "●", idle: "✓", stopped: "✗" };
6
6
  const COLOR = { queued: theme.muted, working: theme.running, idle: theme.success, stopped: theme.error };
7
7
  const DISPLAY_STATUS = { queued: "queued", working: "running", idle: "done", stopped: "errored" };
8
+ // Per-agent accent — each concurrent sub-agent gets its OWN stable colour so you can tell them apart at a glance
9
+ // when several run at once (grandmaster: a team you can read). The status glyph stays status-coloured (working /
10
+ // done / errored), so a row shows BOTH which agent (label hue) and how it's doing (glyph). Named ANSI colours
11
+ // render on every terminal level; red/green/yellow are omitted here so an agent's hue never reads as a status.
12
+ const AGENT_PALETTE = ["cyan", "magenta", "blue", "cyanBright", "magentaBright", "blueBright", "white"];
13
+ function agentColor(a) {
14
+ const key = a.id || a.label;
15
+ let h = 0;
16
+ for (let i = 0; i < key.length; i++)
17
+ h = (h * 31 + key.charCodeAt(i)) >>> 0;
18
+ return AGENT_PALETTE[h % AGENT_PALETTE.length];
19
+ }
8
20
  const toks = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
9
21
  // Live per-agent metrics: tokens generated + elapsed. While working, elapsed is derived from
10
22
  // startedAt at render time (updates each round tick); once finished, the wall time is frozen.
@@ -101,5 +113,5 @@ export function BgPanel({ agents, title = "sub-agents" }) {
101
113
  // frame SHORT — BG_MAX_VISIBLE caps rows, activity lines are capped — so the box stays a few rows tall.
102
114
  // If stray border rows ever reappear on a very long turn, drop `borderStyle`/`borderColor` for the
103
115
  // borderless column (the label line alone still heads it).
104
- return (_jsxs(Box, { flexDirection: "column", marginTop: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { dimColor: true, children: label }), shown.map((a) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", a.label, a.round != null ? ` · round ${a.round}` : "", a.status === "working" && roundActivity(a) ? _jsxs(Text, { color: theme.accent, children: [" \u00B7 ", cap(roundActivity(a), 28)] }) : null] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); const ds = DISPLAY_STATUS[a.status]; return m ? `${m} · ${ds}` : ds; })() })] }), _jsx(ActivityLines, { a: a }), _jsx(GrandmasterLine, { a: a }), a.status === "idle" && _jsx(Box, { paddingLeft: 2, children: _jsx(Text, { dimColor: true, children: "result posted \u2014 scroll up or /agents to review" }) }), a.status === "stopped" && _jsx(Box, { paddingLeft: 2, children: _jsx(Text, { dimColor: true, children: "errored \u2014 check transcript for details" }) })] }, a.id))), hidden > 0 ? _jsx(Text, { dimColor: true, children: ` +${hidden} more running` }) : null] }));
116
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsx(Text, { dimColor: true, children: label }), shown.map((a) => (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Box, { justifyContent: "space-between", children: [_jsxs(Text, { children: [a.status === "working" ? _jsx(OrbitGlyph, {}) : _jsx(Text, { color: COLOR[a.status], children: GLYPH[a.status] }), " ", _jsx(Text, { color: agentColor(a), bold: true, children: a.label }), a.round != null ? ` · round ${a.round}` : "", a.status === "working" && roundActivity(a) ? _jsxs(Text, { color: theme.accent, children: [" \u00B7 ", cap(roundActivity(a), 28)] }) : null] }), _jsx(Text, { dimColor: true, children: (() => { const m = metrics(a); const ds = DISPLAY_STATUS[a.status]; return m ? `${m} · ${ds}` : ds; })() })] }), _jsx(ActivityLines, { a: a }), _jsx(GrandmasterLine, { a: a }), a.status === "idle" && _jsx(Box, { paddingLeft: 2, children: _jsx(Text, { dimColor: true, children: "result posted \u2014 scroll up or /agents to review" }) }), a.status === "stopped" && _jsx(Box, { paddingLeft: 2, children: _jsx(Text, { dimColor: true, children: "errored \u2014 check transcript for details" }) })] }, a.id))), hidden > 0 ? _jsx(Text, { dimColor: true, children: ` +${hidden} more running` }) : null] }));
105
117
  }
@@ -17,10 +17,12 @@ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
17
17
  import { useEffect, useRef, useState } from "react";
18
18
  import { Box, Text, useInput, useStdin } from "ink";
19
19
  import { InputHistory } from "./useInputHistory.js";
20
+ import { matchSlashCommands } from "./slashCommands.js";
20
21
  const PASTE_START = "\x1b[200~";
21
22
  const PASTE_END = "\x1b[201~";
22
23
  export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended, onCycleMode, prompt = "› " }) {
23
24
  const [value, setValue] = useState("");
25
+ const [selIdx, setSelIdx] = useState(0); // highlighted row in the "/" command menu
24
26
  const pasteCountRef = useRef(0);
25
27
  const pasteBufRef = useRef(null); // non-null while inside a bracketed paste
26
28
  const pasteGuardRef = useRef(false); // true for the ENTIRE tick a paste is being committed — useInput must not echo
@@ -31,6 +33,11 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
31
33
  historyRef.current = new InputHistory();
32
34
  const { stdin, isRawModeSupported } = useStdin();
33
35
  useEffect(() => { void historyRef.current.load(); }, []);
36
+ // "/" command menu: matches recompute each render (cheap, pure), so useInput + the render below both see
37
+ // the current set. Editing the filter text resets the highlight to the top (done in the keystroke
38
+ // handlers below); ↑/↓ move it without touching the draft.
39
+ const menuMatches = matchSlashCommands(value);
40
+ const menuSel = menuMatches.length ? Math.min(selIdx, menuMatches.length - 1) : 0;
34
41
  useEffect(() => {
35
42
  if (!isRawModeSupported || !stdin)
36
43
  return;
@@ -128,6 +135,13 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
128
135
  onCycleMode?.();
129
136
  return;
130
137
  }
138
+ // Plain Tab completes the "/" menu to the highlighted command (with a trailing space, ready for args).
139
+ // Always swallow a lone Tab so a literal tab character can never land in the draft.
140
+ if (key.tab) {
141
+ if (menuMatches.length)
142
+ setValue(`/${menuMatches[menuSel].name} `);
143
+ return;
144
+ }
131
145
  // ESC / Ctrl+C: apply the pure interruptPlan. ESC mid-turn with a pending draft flushes it into
132
146
  // the queue (so it goes through right after the interrupt, via the turn-finally drain), then
133
147
  // interrupts; an empty-draft ESC and every Ctrl+C are plain interrupts. See interruptPlan below.
@@ -160,6 +174,13 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
160
174
  onSubmit(text);
161
175
  return;
162
176
  }
177
+ // ↑/↓ navigate the "/" menu when it's open — takes priority over history recall so arrows move the
178
+ // highlight instead of clobbering the "/command" draft. Wraps around.
179
+ if ((key.upArrow || key.downArrow) && menuMatches.length > 0) {
180
+ const n = menuMatches.length;
181
+ setSelIdx((i) => (key.upArrow ? (i - 1 + n) % n : (i + 1) % n));
182
+ return;
183
+ }
163
184
  // History recall (shell-style): only on a single-line buffer, so ↑/↓ stay free for navigating
164
185
  // a multi-line draft instead of clobbering it. See useInputHistory.ts for the ring/draft model.
165
186
  if ((key.upArrow || key.downArrow) && !value.includes("\n")) {
@@ -169,6 +190,7 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
169
190
  return;
170
191
  }
171
192
  if (key.backspace || key.delete) {
193
+ setSelIdx(0); // editing the filter text re-homes the menu highlight
172
194
  setValue((v) => {
173
195
  const next = v.slice(0, -1);
174
196
  if (historyRef.current.recalling)
@@ -178,6 +200,7 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
178
200
  return;
179
201
  }
180
202
  if (ch) {
203
+ setSelIdx(0); // editing the filter text re-homes the menu highlight
181
204
  setValue((v) => {
182
205
  const next = v + ch;
183
206
  if (historyRef.current.recalling)
@@ -190,7 +213,11 @@ export function Composer({ onSubmit, onInterrupt, onQueue, disabled, suspended,
190
213
  // Surface any image/video paths in the draft as attachment chips so the user can see multiple
191
214
  // media are attached (dragged/pasted paths land in the text). De-duped, basename only.
192
215
  const attachments = Array.from(new Set(value.match(MEDIA_RE) ?? []));
193
- return (_jsxs(Box, { flexDirection: "column", children: [lines.map((line, i) => (_jsxs(Text, { children: [i === 0 ? prompt : " ", line, i === lines.length - 1 ? "▌" : ""] }, i))), attachments.length > 0 && (_jsx(Text, { dimColor: true, children: " " + attachments.map((a) => `${VIDEO_RE.test(a) ? "▷ vid" : "◇ img"}:${a.split("/").pop()}`).join(" ") }))] }));
216
+ return (_jsxs(Box, { flexDirection: "column", children: [lines.map((line, i) => (_jsxs(Text, { children: [i === 0 ? prompt : " ", line, i === lines.length - 1 ? "▌" : ""] }, i))), attachments.length > 0 && (_jsx(Text, { dimColor: true, children: " " + attachments.map((a) => `${VIDEO_RE.test(a) ? "▷ vid" : "◇ img"}:${a.split("/").pop()}`).join(" ") })), menuMatches.length > 0 && (_jsxs(Box, { flexDirection: "column", children: [menuMatches.slice(0, 10).map((c, i) => {
217
+ const on = i === menuSel;
218
+ const label = `/${c.name}${c.args ? " " + c.args : ""}`.padEnd(24);
219
+ return (_jsxs(Text, { children: [_jsx(Text, { color: on ? "green" : undefined, bold: on, children: (on ? "▸ " : " ") + label }), _jsx(Text, { dimColor: true, children: c.description })] }, c.name));
220
+ }), menuMatches.length > 10 && _jsx(Text, { dimColor: true, children: ` …and ${menuMatches.length - 10} more` })] }))] }));
194
221
  }
195
222
  // Recognize media file paths in the draft. IMAGE covers the common still formats, VIDEO the moving
196
223
  // ones; a path matching VIDEO is chipped as video, otherwise image. Extensions only — no I/O.
@@ -70,5 +70,5 @@ export function ToolStep({ step }) {
70
70
  // lands. Only RUNNING media rows get the bar — everything else renders exactly as before.
71
71
  const isRunningMedia = toolKind(step.name) === "media" && step.status === "running";
72
72
  const mediaFraction = isRunningMedia && elapsed != null ? mediaProgressFraction(elapsed, mediaEtaMs(step.name, step.args)) : undefined;
73
- return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: step.status === "running" ? KIND_HUE[toolKind(step.name)] : COLOR[step.status], bold: true, children: glyphFor(step.name, step.status, frame) }), " ", step.status === "running" ? _jsx(ShimmerText, { text: step.name, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : step.name, "(", argsPreview(step.args), ")", mediaFraction != null ? (_jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderBar(mediaFraction) }), " ", Math.round(mediaFraction * 100), "%"] })) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), step.summary ? _jsxs(Text, { dimColor: true, children: [" ", step.summary] }) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
73
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: step.status === "running" ? KIND_HUE[toolKind(step.name)] : COLOR[step.status], bold: true, children: glyphFor(step.name, step.status, frame) }), " ", step.status === "running" ? _jsx(ShimmerText, { text: step.name, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : step.name, "(", argsPreview(step.args), ")", mediaFraction != null ? (_jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderBar(mediaFraction) }), " ", Math.round(mediaFraction * 100), "%"] })) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), step.summary ? step.summary.split("\n").map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", l] }, `sm${i}`))) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
74
74
  }
package/dist/ui/format.js CHANGED
@@ -10,3 +10,21 @@ export function formatDuration(ms) {
10
10
  export function isErrorResult(s) {
11
11
  return /^(error|loop guard|\[interrupted)/i.test(s.trim());
12
12
  }
13
+ // The at-a-glance preview of a tool's output, under its row. The old behaviour showed ONLY the first
14
+ // physical line, which for `ls -la`/`du`/`git status` is a header (`total 1672`, a blank line, a banner)
15
+ // — noise, not content. This drops a leading `total N`/blank header and returns the first few MEANINGFUL
16
+ // lines (each clipped), with a "+N more" tail so the preview reflects what the command actually returned.
17
+ // Shared by the live per-call row (ui/liveTools.ts) and the settled-transcript push (cli.tsx) so both read
18
+ // the same. maxLines keeps the batch view from ballooning when many tools settle at once.
19
+ export function resultPreview(s, maxLines = 5) {
20
+ const all = s.replace(/\s+$/, "").split("\n");
21
+ let start = 0;
22
+ while (start < all.length && (all[start].trim() === "" || /^total \d+$/.test(all[start].trim())))
23
+ start++;
24
+ const body = all.slice(start);
25
+ const shown = body.slice(0, maxLines).map((l) => (l.length > 160 ? l.slice(0, 159) + "…" : l));
26
+ const remaining = body.length - shown.length;
27
+ if (remaining > 0)
28
+ shown.push(`… +${remaining} more line${remaining === 1 ? "" : "s"}`);
29
+ return shown.join("\n");
30
+ }
@@ -1,4 +1,4 @@
1
- import { isErrorResult } from "./format.js";
1
+ import { isErrorResult, resultPreview } from "./format.js";
2
2
  /** Seed one live row per call, all "running" from the same instant — the batch was just dispatched
3
3
  * together, so that's the honest starting state even though safe calls run concurrently and mutating
4
4
  * ones run sequentially (the UI can't see that split; each row's own elapsed timer still ticks
@@ -15,10 +15,7 @@ export function settleLiveTool(rows, id, result, now = Date.now()) {
15
15
  if (r.id !== id || r.status !== "running")
16
16
  return r;
17
17
  changed = true;
18
- return { ...r, status: isErrorResult(result) ? "error" : "done", endedAt: now, summary: firstLine(result) };
18
+ return { ...r, status: isErrorResult(result) ? "error" : "done", endedAt: now, summary: resultPreview(result) };
19
19
  });
20
20
  return changed ? next : rows;
21
21
  }
22
- function firstLine(s) {
23
- return (s.split("\n")[0] ?? "").slice(0, 100);
24
- }
package/dist/ui/qr.js ADDED
@@ -0,0 +1,10 @@
1
+ // Terminal QR for the /pair flow: the desktop prints a scannable QR (+ the operator://pair link) that the
2
+ // Operator mobile app reads off-screen to start driving this session. `small: true` packs two QR modules
3
+ // into each character row (▀▄ half-blocks) so a ~45-char operator://pair URL fits in ~17 lines — small
4
+ // enough to sit in the terminal, dense enough for a phone camera. 'M' error correction tolerates the
5
+ // glyph aliasing of a terminal render without bloating the module count.
6
+ import QRCode from "qrcode";
7
+ export async function qrToTerminal(text) {
8
+ const out = await QRCode.toString(text, { type: "terminal", small: true, errorCorrectionLevel: "M" });
9
+ return out.replace(/\n$/, ""); // trim the trailing newline so sys() doesn't add a blank row under it
10
+ }
@@ -0,0 +1,160 @@
1
+ import { cellWidth } from "./StatusRule.js";
2
+ // Resize-safe stdout for the INLINE Ink frame. Ink redraws by erasing the previous frame with
3
+ // ansi-escapes' eraseLines(n), where n is the number of LOGICAL lines it last wrote. That is only the number
4
+ // of terminal rows while no line wraps. When the window SHRINKS, the terminal reflows what is already on
5
+ // screen: every line wider than the new width (the status rule, bottom rule and footer are all ~full-width)
6
+ // now spans 2+ rows, so the frame is physically taller than Ink thinks and eraseLines(n) climbs too few rows
7
+ // — the top of the old frame (status line + "› " prompt) stays behind and the new frame is drawn below it.
8
+ // A drag fires a resize event per step and each one redraws, so each step strands another copy: the
9
+ // status/mode line spamming down the screen. (The earlier fix cleared on a 16ms debounce, which can't help:
10
+ // Ink's own clear() erases by the same stale count, and a fast drag never lets the debounce fire.)
11
+ //
12
+ // So: wrap the stream Ink writes to, and do two things.
13
+ // 1. Count rows truthfully. We remember the last frame Ink wrote and the width it was written at; when the
14
+ // terminal has since gotten NARROWER and a redraw's erase prefix undercounts the rows that frame now
15
+ // occupies, swap it for the true count. At an unchanged (or wider) width the write is passed through
16
+ // byte-for-byte — normal rendering is untouched.
17
+ // 2. Redraw once per drag, not once per step. Resize listeners registered through the wrapper (Ink's own
18
+ // layout pass, useTerminalSize) fire after the window has been quiet for RESIZE_SETTLE_MS. Redrawing every
19
+ // step makes a scrolled terminal creep: each step the old frame reflows taller (pushing the transcript up
20
+ // a row), the redraw shrinks it back and leaves a blank row at the bottom, so the cursor climbs the
21
+ // viewport until the top of the frame is in scrollback — out of reach of any erase.
22
+ // Public Ink API only (the `stdout` render option); nothing is patched. Assumes the terminal reflows on resize
23
+ // (iTerm2, Terminal.app, Ghostty, kitty, WezTerm, VS Code do — and the duplicates in the field prove the
24
+ // reporter's does).
25
+ const ESC = "\x1b";
26
+ const ERASE_LINE = `${ESC}[2K`;
27
+ const CURSOR_UP = `${ESC}[1A`;
28
+ const CURSOR_LEFT = `${ESC}[G`;
29
+ // How log-update opens a redraw: eraseLines(n) = n × erase-line joined by cursor-up, then cursor-left.
30
+ const ERASE_PREFIX = new RegExp(`^(?:${ESC}\\[2K${ESC}\\[1A)*${ESC}\\[2K${ESC}\\[G`);
31
+ // CSI (colors, cursor) and OSC (hyperlinks) — zero-width in the frame, must not count toward row math.
32
+ const ANSI = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]|${ESC}\\][^\\x07${ESC}]*(?:\\x07|${ESC}\\\\)`, "g");
33
+ const CLEAR_SCREEN = `${ESC}[2J`; // Ink's full-redraw path (frame as tall as the window) starts with this
34
+ /** Quiet time after the last resize event before listeners fire — long enough to ride out one drag (events
35
+ * arrive every ~16ms), short enough that a single resize still redraws before you notice. */
36
+ export const RESIZE_SETTLE_MS = 80;
37
+ /** The erase Ink's log-update emits for `n` rows — the cursor ends on the top row, column 0. */
38
+ export function eraseLines(n) {
39
+ let out = "";
40
+ for (let i = 0; i < n; i++)
41
+ out += ERASE_LINE + (i < n - 1 ? CURSOR_UP : "");
42
+ return n > 0 ? out + CURSOR_LEFT : out;
43
+ }
44
+ /** Terminal rows ONE logical line occupies at width `cols`: placed cell by cell the way a terminal does, so a
45
+ * double-width glyph that doesn't fit the last column wraps whole to the next row. Always ≥ 1 (a blank line
46
+ * still takes a row). Measured with StatusRule's cellWidth — the repo's model of the real terminal, which
47
+ * counts the dingbats macOS renders double-width as 2. Here over-counting is the safe side: it erases one
48
+ * spare row (usually the blank spacer above the frame), while under-counting strands a copy of the frame. */
49
+ export function wrappedRows(line, cols) {
50
+ if (cols <= 0)
51
+ return 1;
52
+ let rows = 1;
53
+ let col = 0;
54
+ for (const ch of line.replace(ANSI, "")) {
55
+ const w = cellWidth(ch);
56
+ if (col + w > cols) {
57
+ rows++;
58
+ col = 0;
59
+ }
60
+ col += w;
61
+ }
62
+ return rows;
63
+ }
64
+ /** Rows a frame occupies at width `cols`, counting the empty row the cursor rests on after the frame's
65
+ * trailing newline — exactly what Ink's own eraseLines(lines + 1) assumes when nothing wraps. */
66
+ export function frameRows(lines, cols) {
67
+ let rows = 1;
68
+ for (const line of lines)
69
+ rows += wrappedRows(line, cols);
70
+ return rows;
71
+ }
72
+ /** Wrap `stream` (the real stdout) for Ink's `stdout` render option. `write` and 'resize' listeners are
73
+ * intercepted; everything else is delegated to the real stream. */
74
+ export function createResizeSafeStdout(stream = process.stdout, settleMs = RESIZE_SETTLE_MS) {
75
+ // The last text Ink wrote, as lines, and the width it was written at. Ink writes the frame LAST in every
76
+ // redraw (static output and patched console output go first), so "the last newline-terminated text
77
+ // written" is the frame on screen.
78
+ let frame;
79
+ function rewrite(s) {
80
+ const prefix = ERASE_PREFIX.exec(s);
81
+ const text = prefix ? s.slice(prefix[0].length) : s;
82
+ // A minimized/detached window reports 0 columns: the terminal hasn't reflowed anything we can reason about,
83
+ // so make no correction then. Ink lays the frame out at 80 in that state, which is what we record.
84
+ const live = stream.columns > 0 ? stream.columns : 0;
85
+ const cols = live || 80;
86
+ let out = s;
87
+ if (prefix && frame && live > 0 && live < frame.cols) {
88
+ const erased = prefix[0].split(ERASE_LINE).length - 1;
89
+ // Only act when Ink's count is what we expect for the frame we saw — if the two ever disagree we don't
90
+ // know what is on screen, so leave Ink's erase alone rather than guess.
91
+ if (erased === frame.lines.length + 1) {
92
+ const rows = Math.min(frameRows(frame.lines, live), stream.rows > 0 ? stream.rows : Infinity);
93
+ if (rows > erased)
94
+ out = eraseLines(rows) + text;
95
+ }
96
+ }
97
+ if (text.includes(CLEAR_SCREEN) || (prefix && !text.endsWith("\n"))) {
98
+ frame = undefined; // Ink's full-clear redraw, or an erase-only write (its clear()): nothing we can vouch for is on screen
99
+ }
100
+ else if (text.endsWith("\n")) {
101
+ frame = { lines: text.slice(0, -1).split("\n"), cols };
102
+ } // else: a bare control write (cursor show/hide…) — the frame on screen is unchanged
103
+ return out;
104
+ }
105
+ const write = (chunk, ...rest) => stream.write.call(stream, typeof chunk === "string" ? rewrite(chunk) : chunk, ...rest);
106
+ // 'resize' listeners registered through the wrapper share ONE debounced subscription to the real stream.
107
+ const resizeListeners = new Set();
108
+ let settleTimer;
109
+ const onRawResize = () => {
110
+ clearTimeout(settleTimer);
111
+ settleTimer = setTimeout(() => {
112
+ settleTimer = undefined;
113
+ // Latest-registered first: components (useTerminalSize) re-render at the new width before Ink's own
114
+ // layout pass (registered at construction) redraws, so the one redraw is the finished frame.
115
+ for (const fn of [...resizeListeners].reverse())
116
+ fn();
117
+ }, settleMs);
118
+ settleTimer.unref?.();
119
+ };
120
+ const addResizeListener = (fn) => {
121
+ if (!resizeListeners.size)
122
+ stream.on("resize", onRawResize);
123
+ resizeListeners.add(fn);
124
+ };
125
+ const removeResizeListener = (fn) => {
126
+ resizeListeners.delete(fn);
127
+ if (!resizeListeners.size) {
128
+ stream.off("resize", onRawResize);
129
+ clearTimeout(settleTimer);
130
+ settleTimer = undefined;
131
+ }
132
+ };
133
+ const wrapper = new Proxy(stream, {
134
+ get(target, prop) {
135
+ if (prop === "write")
136
+ return write;
137
+ if (prop === "on" || prop === "addListener") {
138
+ return (event, fn) => {
139
+ if (event === "resize")
140
+ addResizeListener(fn);
141
+ else
142
+ target.on(event, fn);
143
+ return wrapper;
144
+ };
145
+ }
146
+ if (prop === "off" || prop === "removeListener") {
147
+ return (event, fn) => {
148
+ if (event === "resize")
149
+ removeResizeListener(fn);
150
+ else
151
+ target.off(event, fn);
152
+ return wrapper;
153
+ };
154
+ }
155
+ const value = Reflect.get(target, prop, target);
156
+ return typeof value === "function" ? value.bind(target) : value;
157
+ },
158
+ });
159
+ return wrapper;
160
+ }
@@ -0,0 +1,43 @@
1
+ // Ordered to mirror the /help text so the menu and `/help` read the same way.
2
+ export const SLASH_COMMANDS = [
3
+ { name: "help", description: "list available commands" },
4
+ { name: "login", description: "sign in: /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>), or /login <token>", args: "[email|code|token]" },
5
+ { name: "logout", description: "sign out and clear stored credentials" },
6
+ { name: "whoami", description: "show the signed-in identity" },
7
+ { name: "model", description: "pick a model: operator-1m · operator-128k · qwen connectors · moa", args: "[id]" },
8
+ { name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
9
+ { name: "endpoints", description: "show the Operator endpoint + live health" },
10
+ { name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng)", args: "[stop]" },
11
+ { name: "mcp", description: "fleet MCP tools: status · switch the layer on/off", args: "[on|off]" },
12
+ { name: "skills", description: "list installed skills (all, or matching a query)", args: "[query]" },
13
+ { name: "deep-research", description: "research a question across the web — cited, multi-source", args: "<question>" },
14
+ { name: "remote", description: "remote control: let a follower attach and drive this session", args: "[on|off]" },
15
+ { name: "pair", description: "pair a phone to drive this session — shows a QR for the Operator app (end-to-end encrypted)" },
16
+ { name: "plan", description: "plan mode: read-only research + propose a plan (/plan again executes)" },
17
+ { name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
18
+ { name: "think", description: "toggle extended reasoning (think before answering)" },
19
+ { name: "ultrathink", description: "toggle deep, exhaustive reasoning for hard problems" },
20
+ { name: "agents", description: "detailed sub-agent status: running/queued/done/errored + metrics" },
21
+ { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
22
+ { name: "monitor", description: "toggle the live event stream (tool decisions, turns, control)" },
23
+ { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
24
+ { name: "stats", description: "session dashboard: turns · tools · tokens · throughput · context fill" },
25
+ { name: "dashboard", description: "launch the live swarm console (watches every Operator session)" },
26
+ { name: "artifacts", description: "browse + attach your Compose artifacts: search · attach · copy url · delete" },
27
+ { name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
28
+ { name: "memory", description: "show remembered notes (all, or matching a query)", args: "[query]" },
29
+ { name: "compact", description: "force-compact the conversation now" },
30
+ { name: "new", description: "start a fresh conversation" },
31
+ { name: "clear", description: "clear the screen (keeps the conversation)" },
32
+ { name: "exit", description: "leave operator (alias: /quit)" },
33
+ ];
34
+ // Pure, testable: given the current draft, return the commands the "/" menu should offer — or [] when
35
+ // the draft isn't a bare "/command" token (a space, a newline, or a second "/" as in a pasted path all
36
+ // close the menu). Kept side-effect free like the other Composer helpers (pasteChip, interruptPlan).
37
+ export function matchSlashCommands(value) {
38
+ const m = /^\/([\w-]*)$/.exec(value); // allow '-' so hyphenated commands (deep-research) filter in the menu
39
+ if (!m)
40
+ return [];
41
+ const q = m[1].toLowerCase();
42
+ return SLASH_COMMANDS.filter((c) => c.name.startsWith(q));
43
+ }
package/dist/ui/term.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { useState, useEffect } from "react";
2
+ import { useStdout } from "ink";
1
3
  // Terminal dimensions, floored to a sane minimum — the ONE place layout reads the window size.
2
4
  // process.stdout.columns/rows report 0 (not undefined) when the window is minimized, hidden, or the
3
5
  // stream is momentarily detached, and `process.stdout.columns ?? 80` does NOT catch 0 (?? only falls
@@ -14,3 +16,23 @@ export function termRows(fallback = 24) {
14
16
  const r = process.stdout.rows;
15
17
  return typeof r === "number" && r > 0 ? r : fallback;
16
18
  }
19
+ // Reactive terminal size. termCols()/termRows() read the live size AT RENDER TIME, so the pinned UI only
20
+ // reflows when something ELSE re-renders — Ink's own resize pass re-lays-out the existing tree but never
21
+ // re-runs a component, so the width-dependent rules would sit at the old width until the next keystroke or
22
+ // tick. A component that calls this hook re-renders when the window changes, so the status rule / composer /
23
+ // footer resize correctly when the terminal grows or shrinks. It subscribes through Ink's stdout (not
24
+ // process.stdout) so that in the inline layout it rides the debounced listener of the resize-safe stdout
25
+ // (resize.ts) — one redraw per drag instead of one per step.
26
+ export function useTerminalSize() {
27
+ const { stdout } = useStdout();
28
+ const [size, setSize] = useState(() => ({ cols: termCols(), rows: termRows() }));
29
+ useEffect(() => {
30
+ const onResize = () => setSize((prev) => {
31
+ const next = { cols: termCols(), rows: termRows() };
32
+ return next.cols === prev.cols && next.rows === prev.rows ? prev : next; // skip no-op renders
33
+ });
34
+ stdout.on?.("resize", onResize);
35
+ return () => { stdout.off?.("resize", onResize); };
36
+ }, [stdout]);
37
+ return size;
38
+ }
@@ -5,7 +5,7 @@ const KNOWN = new Set([
5
5
  "help", "model", "route", "endpoints", "services", "audit", "dashboard", "plan", "mode",
6
6
  "think", "ultrathink", "compact", "remember", "memory", "mcp", "whoami", "agents", "monitor",
7
7
  "bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol", "rc",
8
- "artifacts",
8
+ "artifacts", "skills", "deep-research", "deepresearch", "research", "pair",
9
9
  ]);
10
10
  export function isSlashCommand(text) {
11
11
  const t = text.trim();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.263",
3
+ "version": "0.1.274",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",
@@ -28,12 +28,14 @@
28
28
  "@zed-industries/agent-client-protocol": "^0.4.5",
29
29
  "chalk": "^5.6.2",
30
30
  "ink": "^5.0.1",
31
+ "qrcode": "^1.5.4",
31
32
  "react": "^18.3.1",
32
33
  "ws": "^8.18.0"
33
34
  },
34
35
  "devDependencies": {
35
36
  "@biomejs/biome": "2.5.14",
36
37
  "@types/node": "^22.20.3",
38
+ "@types/qrcode": "^1.5.6",
37
39
  "@types/react": "^18.3.3",
38
40
  "ink-testing-library": "^3.0.0",
39
41
  "tsx": "^4.19.1",