@0perator/operator 0.2.1 → 0.2.2-next.1

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 (66) hide show
  1. package/README.md +1 -1
  2. package/dist/auth/byo.js +1 -1
  3. package/dist/auth/commands.js +8 -2
  4. package/dist/autonomy/agent-cli.js +1 -1
  5. package/dist/autonomy/headless.js +30 -6
  6. package/dist/autonomy/pr-isolation.js +92 -0
  7. package/dist/autonomy/pr-preflight.js +474 -0
  8. package/dist/autonomy/session-factory.js +2 -0
  9. package/dist/browser/capture.js +505 -0
  10. package/dist/browser/engine.js +4 -3
  11. package/dist/browser/page-capture.js +167 -0
  12. package/dist/browser/png.js +116 -0
  13. package/dist/browser/visual-compare.js +229 -0
  14. package/dist/bus/beam-drop.js +55 -0
  15. package/dist/bus/inbox.js +7 -1
  16. package/dist/cli.js +130 -26
  17. package/dist/config/managed.js +40 -1
  18. package/dist/config/persona.js +86 -41
  19. package/dist/config/product-hosts.js +2 -0
  20. package/dist/config/settings.js +30 -13
  21. package/dist/config/skills-index.js +37 -14
  22. package/dist/engine/agent.js +1 -1
  23. package/dist/engine/aurora.js +18 -9
  24. package/dist/engine/continuation.js +36 -0
  25. package/dist/engine/identity.js +42 -0
  26. package/dist/engine/moa.js +7 -0
  27. package/dist/engine/net-error.js +15 -0
  28. package/dist/engine/rolling-summary.js +142 -93
  29. package/dist/engine/waterfall.js +33 -0
  30. package/dist/gateway-cli.js +10 -1
  31. package/dist/memory/session-index.js +3 -3
  32. package/dist/permissions/index.js +2 -1
  33. package/dist/permissions/policy.js +9 -2
  34. package/dist/permissions/tier.js +9 -1
  35. package/dist/products/craft.js +90 -1
  36. package/dist/products/temple.js +20 -1
  37. package/dist/products/voice.js +112 -0
  38. package/dist/router/free-models.js +5 -9
  39. package/dist/router/models.js +58 -14
  40. package/dist/router/provider-models.js +78 -0
  41. package/dist/router/router.js +15 -3
  42. package/dist/selfimprove/lessons.js +23 -0
  43. package/dist/session.js +192 -87
  44. package/dist/skills/catalogue.js +5 -2
  45. package/dist/skills/finder.js +4 -4
  46. package/dist/skills/install-guard.js +1 -1
  47. package/dist/tools/beam.js +246 -0
  48. package/dist/tools/craft.js +23 -0
  49. package/dist/tools/deferred.js +7 -3
  50. package/dist/tools/doc-text.js +1 -1
  51. package/dist/tools/registry.js +55 -9
  52. package/dist/tools/sandbox.js +6 -6
  53. package/dist/ui/App.js +3 -3
  54. package/dist/ui/ApprovalPrompt.js +1 -1
  55. package/dist/ui/Composer.js +44 -2
  56. package/dist/ui/StatusRule.js +2 -1
  57. package/dist/ui/Transcript.js +5 -0
  58. package/dist/ui/modelPicker.js +10 -6
  59. package/dist/ui/phase.js +4 -2
  60. package/dist/ui/slashCommands.js +1 -0
  61. package/dist/ui/voice.js +185 -0
  62. package/dist/update.js +1 -2
  63. package/dist/util/audio-io.js +82 -0
  64. package/dist/util/slash.js +2 -2
  65. package/dist/vision/pairs.js +239 -0
  66. package/package.json +1 -1
@@ -11,6 +11,7 @@ import { SummaryCard } from "./SummaryCard.js";
11
11
  import { StatsCard } from "./StatsCard.js";
12
12
  import { ToolBatch } from "./ToolBatch.js";
13
13
  import { SB_MARK, SB_IN, SB_OUT } from "./brand.js";
14
+ import { beamDrop, beamDropHint, beamDropLine } from "../bus/beam-drop.js";
14
15
  import { termCols, termRows } from "./term.js";
15
16
  import { reportLine } from "./reportLine.js";
16
17
  import { theme } from "./theme.js";
@@ -94,6 +95,10 @@ function hhmm(at) {
94
95
  }
95
96
  function BusCard({ entry }) {
96
97
  const { msg, direction, at } = entry;
98
+ const drop = direction === "in" ? beamDrop(msg) : null;
99
+ if (drop) {
100
+ return (_jsx(Box, { marginBottom: 1, children: _jsxs(Text, { color: "cyan", children: [beamDropLine(drop), _jsx(Text, { dimColor: true, children: ` ${beamDropHint(drop)} · ${hhmm(at)}` })] }) }));
101
+ }
97
102
  const who = direction === "in" ? msg.from : msg.to;
98
103
  const arrow = direction === "in" ? SB_IN : SB_OUT;
99
104
  const lead = direction === "in" ? "" : "sent · ";
@@ -10,12 +10,16 @@ import { cellWidth, truncateToWidth } from "./StatusRule.js";
10
10
  import { approxTokens, fmtWait, fmtWhen, readSeconds } from "../router/read-rates.js";
11
11
  /** The last /model row: an action, never a ModelProfile — so the lists fed from the registry (the ACP dropdown, a
12
12
  * follower's model list) can never offer it. */
13
- export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, Nous, OpenAI, …)";
13
+ export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, OpenAI, …)";
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
- 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"];
16
+ export const FREE_ROW_PRESETS = ["operator"];
17
+ /** Sign-in providers whose rows /model reads from their own /models once signed in (router/provider-models.ts). Unlike
18
+ * 0perator Free they are listed under "+ Connect a provider key", where picking one points at the sign-in. */
19
+ export const PROVIDER_ROW_PRESETS = ["portal"];
20
+ /** The /model main rows, in this order; everything else sits behind MORE_ROW. operator-dense left 2026-11-30 (its
21
+ * gateway route was retired: the registry only offers what is served). */
22
+ export const MAIN_MODEL_IDS = ["operator-flash", "kimi-linear-48b"];
19
23
  /** The last main row: an action that opens the rest (other fleet rows, connected providers, free rows, MOA, connect). */
20
24
  export const MORE_ROW = "More models…";
21
25
  // fleet → connected providers → free rows → MOA. The built-ins already list the local row before the gateway rows.
@@ -128,8 +132,8 @@ export function connectedAccounts(has, presets = BYO_PRESETS) {
128
132
  /** The provider rows, from the presets in their order — never listByoAccounts, which sees only the file tier:
129
133
  * `<label>`, plus " ✓ connected" for an account in `connected`. */
130
134
  export function providerPickerView(connected, presets = BYO_PRESETS) {
131
- const choices = Object.entries(presets).filter(([, p]) => !p.signIn).map(([preset, p]) => ({ preset, p }));
132
- return { rows: choices.map(({ p }) => `${p.label}${connected.has(p.account) ? " ✓ connected" : ""}`), choices };
135
+ const choices = Object.entries(presets).filter(([preset, p]) => !p.signIn || PROVIDER_ROW_PRESETS.includes(preset)).map(([preset, p]) => ({ preset, p }));
136
+ return { rows: choices.map(({ p }) => `${p.label}${connected.has(p.account) ? (p.signIn ? " ✓ signed in" : " ✓ connected") : ""}`), choices };
133
137
  }
134
138
  /** What a QuestionPrompt answer means for a picker whose rows were drawn from `entries`: the row picked (by index), the
135
139
  * owner's typed reply, or null — the empty reply / ctrl+c that resolves DISCUSS is never applied as a choice. */
package/dist/ui/phase.js CHANGED
@@ -88,8 +88,10 @@ export function phaseLine(v, cols, frame = 0) {
88
88
  const phase = wrote ? [seg([`writing the summary · ${wrote}`, `writing · ${wrote}`], 3, true)]
89
89
  : r && r.done >= r.fresh ? [seg(`summarizer read ${fmtTok(r.fresh)} new`, 4), seg(["writing the summary", "writing"], 3, true)]
90
90
  : r ? [seg([r.cache > 0 ? `summarizer reading ${fmtTok(r.done)} new (${fmtTok(r.cache)} reused)` : `summarizer reading ${fmtTok(r.done)} of ${fmtTok(r.fresh)} new`, `summarizer ${Math.round(r.fraction * 100)}%`], 3)]
91
- : [];
92
- return fit([seg(`compacting ${fmtTok(c.before)} tokens`), ...phase]);
91
+ : c.reading ? [seg(`reading ${fmtTok(c.reading)} new`, 3)]
92
+ : [];
93
+ const covered = c.covered ? [seg([`${fmtTok(c.covered)} already summarized`, `${fmtTok(c.covered)} done`], 2)] : [];
94
+ return fit([seg(`compacting ${fmtTok(c.before)} tokens`), ...covered, ...phase]);
93
95
  }
94
96
  default: // waiting
95
97
  return fit([seg("waiting for the model"), v.expect ? seg(v.expect, 3, true) : seg("nothing back yet", 4)]);
@@ -23,6 +23,7 @@ export const SLASH_COMMANDS = [
23
23
  { name: "agents", description: "detailed sub-agent status: running/queued/done/errored + metrics" },
24
24
  { name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
25
25
  { name: "jobs", description: "background shell jobs: list, or stop one (ctrl+b moves a running command here)", args: "[stop id]" },
26
+ { name: "voice", description: "voice mode: ctrl+t to talk, the answer is spoken back (esc stops it)", args: "[on|off|status]" },
26
27
  { name: "monitor", description: "toggle the live event stream (tool decisions, turns, control)" },
27
28
  { name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
28
29
  { name: "stats", description: "session dashboard: turns · tools · tokens · throughput · context fill" },
@@ -0,0 +1,185 @@
1
+ // /voice — voice mode for the terminal session. Speech is a way IN and a way OUT of the same conversation: ctrl+t
2
+ // records, the transcript is sent as the owner's turn (as text, so the transcript stays a normal conversation), the
3
+ // session's own model answers with its tools, and a short spoken-friendly version of that answer is played. A terminal
4
+ // reports no key-up, so talk is press-to-start, press-again-to-send (or a pause, when the recorder can hear one).
5
+ // Everything here is pure or injected: the state machine, the speakable-text reducer, and a controller whose
6
+ // microphone, speaker and speech routes arrive as functions (util/audio-io.ts, products/voice.ts).
7
+ const TABLE = {
8
+ off: { on: { state: "idle", effects: [] } },
9
+ idle: {
10
+ key: { state: "recording", effects: ["record"] },
11
+ answer: { state: "speaking", effects: ["speak"] },
12
+ off: { state: "off", effects: [] },
13
+ },
14
+ recording: {
15
+ key: { state: "recording", effects: ["stopRecording"] },
16
+ recorded: { state: "transcribing", effects: ["transcribe"] },
17
+ esc: { state: "idle", effects: ["cancelRecording"] },
18
+ failed: { state: "idle", effects: [] },
19
+ off: { state: "off", effects: ["cancelRecording"] },
20
+ },
21
+ transcribing: {
22
+ key: { state: "transcribing", effects: [] },
23
+ heard: { state: "idle", effects: [] },
24
+ failed: { state: "idle", effects: [] },
25
+ esc: { state: "idle", effects: ["drop"] },
26
+ off: { state: "off", effects: ["drop"] },
27
+ },
28
+ speaking: {
29
+ key: { state: "recording", effects: ["stopPlayback", "record"] },
30
+ answer: { state: "speaking", effects: ["stopPlayback", "speak"] },
31
+ played: { state: "idle", effects: [] },
32
+ failed: { state: "idle", effects: [] },
33
+ esc: { state: "idle", effects: ["stopPlayback"] },
34
+ off: { state: "off", effects: ["stopPlayback"] },
35
+ },
36
+ };
37
+ /** The next state and what to do, or null when the event means nothing here (Esc while idle keeps its usual meaning;
38
+ * an answer that lands while the owner is talking is not spoken over them). */
39
+ export function voiceStep(state, event) {
40
+ return TABLE[state][event] ?? null;
41
+ }
42
+ /** ctrl+t — talk. Bound nowhere else in the composer; in raw mode the terminal's status key (SIGINFO) never sees it. */
43
+ export function isVoiceKey(ch, key) {
44
+ return !!key.ctrl && ch === "t";
45
+ }
46
+ /** `/voice`, `/voice on|off|status`: what the argument asks for given the current state; null = not understood. */
47
+ export function voiceIntent(arg, on) {
48
+ const a = arg.trim().toLowerCase();
49
+ if (a === "")
50
+ return on ? "off" : "on";
51
+ return a === "on" || a === "off" || a === "status" ? a : null;
52
+ }
53
+ /** The line above the composer while voice mode is on. `note` replaces the default wording (a cold model load). */
54
+ export function voiceLine(state, o = {}) {
55
+ if (state === "off")
56
+ return null;
57
+ if (o.note)
58
+ return `◌ ${o.note}`;
59
+ if (state === "recording")
60
+ return `● recording — ctrl+t sends${o.autoStop ? " (or pause)" : ""} · esc cancels`;
61
+ if (state === "transcribing")
62
+ return "◌ transcribing… · esc drops it";
63
+ if (state === "speaking")
64
+ return "♪ speaking — esc stops · ctrl+t talks over it";
65
+ return "voice on · ctrl+t to talk · /voice off";
66
+ }
67
+ export const SPEAK_CAP = 600;
68
+ const CODE_NOTE = "The code is on screen.";
69
+ const REST_NOTE = "The rest is on screen.";
70
+ /** An answer as something worth hearing: code blocks and tables dropped (and said so), markdown marks removed, links
71
+ * reduced to their text, capped at a sentence end. "" when nothing is left to say. */
72
+ export function speakable(markdown, cap = SPEAK_CAP) {
73
+ let code = false;
74
+ const prose = markdown.replace(/```[\s\S]*?(```|$)/g, () => { code = true; return "\n"; });
75
+ const lines = prose.split("\n")
76
+ .filter((l) => !/^\s*\|.*\|\s*$/.test(l) && !/^\s*([-*_]\s*){3,}$/.test(l))
77
+ .map((l) => l
78
+ .replace(/^\s{0,3}(#{1,6}|>+|[-*+]|\d+[.)])\s+/, "")
79
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, "")
80
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
81
+ .replace(/https?:\/\/\S+/g, "a link")
82
+ .replace(/`([^`]*)`/g, "$1")
83
+ .replace(/\*+|~~/g, "")
84
+ .trim())
85
+ .filter(Boolean)
86
+ .map((l) => (/[.!?:;,]$/.test(l) ? l : `${l}.`));
87
+ let text = lines.join(" ").replace(/\s+/g, " ").trim();
88
+ if (text.length > cap) {
89
+ const head = text.slice(0, cap);
90
+ const end = Math.max(head.lastIndexOf(". "), head.lastIndexOf("! "), head.lastIndexOf("? "));
91
+ text = `${end >= cap / 2 ? head.slice(0, end + 1) : `${head.slice(0, Math.max(0, head.lastIndexOf(" ")))}…`} ${REST_NOTE}`;
92
+ }
93
+ return code ? `${text} ${CODE_NOTE}`.trim() : text;
94
+ }
95
+ /** Speech must never run a command: a transcript is always sent as words. */
96
+ export function heardAsText(text) {
97
+ return text.trim().replace(/^\/+\s*/, "");
98
+ }
99
+ const LOADING = (s) => `voice model loading… ${s}s`;
100
+ const why = (e) => String(e?.message ?? e);
101
+ /** The controller: runs the state machine's effects through `deps`. Anything started is tagged with a generation;
102
+ * stopping, cancelling or dropping moves the generation on, so a late result from before is ignored. */
103
+ export function createVoice(deps) {
104
+ let state = "off";
105
+ let gen = 0;
106
+ let recording;
107
+ let playing;
108
+ let wav = null;
109
+ let toSay = "";
110
+ const fail = (g, line) => { if (g === gen) {
111
+ fire("failed");
112
+ deps.onError(line);
113
+ } };
114
+ const effects = {
115
+ record: () => {
116
+ const g = ++gen;
117
+ try {
118
+ recording = deps.record();
119
+ recording.done.then((audio) => { if (g !== gen)
120
+ return; wav = audio; if (audio)
121
+ fire("recorded");
122
+ else
123
+ fail(g, "nothing was recorded — check the microphone and this terminal's microphone permission"); }, (e) => fail(g, why(e)));
124
+ }
125
+ catch (e) {
126
+ fail(g, why(e));
127
+ }
128
+ },
129
+ stopRecording: () => recording?.stop(),
130
+ cancelRecording: () => { gen++; recording?.cancel(); recording = undefined; },
131
+ transcribe: () => {
132
+ const g = gen, audio = wav;
133
+ wav = null;
134
+ if (!audio)
135
+ return fail(g, "nothing was recorded");
136
+ deps.transcribe(audio, (s) => { if (g === gen)
137
+ deps.onState(state, LOADING(s)); }).then((text) => {
138
+ if (g !== gen)
139
+ return;
140
+ fire("heard");
141
+ const words = heardAsText(text);
142
+ if (words)
143
+ deps.onHeard(words);
144
+ else
145
+ deps.onError("no speech heard");
146
+ }, (e) => fail(g, why(e)));
147
+ },
148
+ drop: () => { gen++; },
149
+ speak: () => {
150
+ const g = ++gen, text = toSay;
151
+ deps.speak(text, (s) => { if (g === gen)
152
+ deps.onState(state, LOADING(s)); }).then((audio) => {
153
+ if (g !== gen)
154
+ return;
155
+ deps.onState(state);
156
+ playing = deps.play(audio);
157
+ playing.done.then(() => { if (g === gen)
158
+ fire("played"); }, () => { if (g === gen)
159
+ fire("played"); });
160
+ }).catch((e) => fail(g, why(e)));
161
+ },
162
+ stopPlayback: () => { gen++; playing?.stop(); playing = undefined; },
163
+ };
164
+ function fire(event) {
165
+ const step = voiceStep(state, event);
166
+ if (!step)
167
+ return false;
168
+ state = step.state;
169
+ deps.onState(state);
170
+ for (const e of step.effects)
171
+ effects[e]();
172
+ return true;
173
+ }
174
+ return {
175
+ state: () => state,
176
+ on: () => fire("on"), off: () => fire("off"), key: () => fire("key"), esc: () => fire("esc"),
177
+ answer: (markdown) => {
178
+ const text = speakable(markdown);
179
+ if (!text || !voiceStep(state, "answer"))
180
+ return false;
181
+ toSay = text;
182
+ return fire("answer");
183
+ },
184
+ };
185
+ }
package/dist/update.js CHANGED
@@ -245,13 +245,12 @@ export function installedVersion(pkgJson = fileURLToPath(new URL("../package.jso
245
245
  return undefined;
246
246
  }
247
247
  }
248
- export async function runUpdate(args = [], pkgJson = fileURLToPath(new URL("../package.json", import.meta.url))) {
248
+ export async function runUpdate(args = [], pkgJson = fileURLToPath(new URL("../package.json", import.meta.url)), repo = findRepoRoot()) {
249
249
  const pick = updateChannel(args, versionAt(pkgJson));
250
250
  if ("error" in pick) {
251
251
  process.stderr.write(pick.error);
252
252
  return 2;
253
253
  }
254
- const repo = findRepoRoot();
255
254
  if (repo && pick.explicit) {
256
255
  process.stderr.write(`operator update: --${pick.channel} picks an npm channel, but this operator runs from the source checkout at ${repo}, ` +
257
256
  `which updates by git. To install the ${pick.channel} channel instead: npm install -g ${PKG}@${pick.channel}\n`);
@@ -0,0 +1,82 @@
1
+ // Microphone in, speaker out, for the terminal — with the command-line tools the machine already has. No native
2
+ // dependency: a recorder and a player are DETECTED on PATH (never assumed), each runs as one owned child process, and
3
+ // stopping one signals that exact child. Recordings are 16 kHz mono WAV, capped at MAX_RECORD_SECONDS.
4
+ import { spawn } from "node:child_process";
5
+ import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { resolveBinSync } from "../autonomy/agent-cli.js";
8
+ import { ownChild } from "./owned-children.js";
9
+ export const MAX_RECORD_SECONDS = 120;
10
+ const WAV_HEADER_BYTES = 44;
11
+ const onPath = (bin) => resolveBinSync(bin) !== null;
12
+ /** The first recorder present, in order of preference: sox's `rec` (stops on a pause), ALSA's `arecord`, `ffmpeg`. */
13
+ export function pickRecorder(has = onPath, platformName = process.platform) {
14
+ const cap = String(MAX_RECORD_SECONDS);
15
+ if (has("rec"))
16
+ return { bin: "rec", autoStop: true, args: (f) => ["-q", "-c", "1", "-r", "16000", "-b", "16", f, "trim", "0", cap, "silence", "1", "0.1", "2%", "1", "2.0", "2%"] };
17
+ if (platformName === "linux" && has("arecord"))
18
+ return { bin: "arecord", args: (f) => ["-q", "-f", "S16_LE", "-c", "1", "-r", "16000", "-d", cap, f] };
19
+ if (has("ffmpeg")) {
20
+ const input = platformName === "darwin" ? ["-f", "avfoundation", "-i", ":default"] : ["-f", "alsa", "-i", "default"];
21
+ return { bin: "ffmpeg", args: (f) => ["-hide_banner", "-loglevel", "error", "-nostdin", ...input, "-ac", "1", "-ar", "16000", "-t", cap, "-y", f] };
22
+ }
23
+ return null;
24
+ }
25
+ /** The first player present: macOS `afplay`, ALSA's `aplay`, sox's `play`, `ffplay`. */
26
+ export function pickPlayer(has = onPath) {
27
+ if (has("afplay"))
28
+ return { bin: "afplay", args: (f) => [f] };
29
+ if (has("aplay"))
30
+ return { bin: "aplay", args: (f) => ["-q", f] };
31
+ if (has("play"))
32
+ return { bin: "play", args: (f) => ["-q", f] };
33
+ if (has("ffplay"))
34
+ return { bin: "ffplay", args: (f) => ["-nodisp", "-autoexit", "-loglevel", "quiet", f] };
35
+ return null;
36
+ }
37
+ /** What to install when a tool is missing, named for this platform. */
38
+ export function installHint(kind, platformName = process.platform) {
39
+ const how = platformName === "darwin" ? "brew install sox (or brew install ffmpeg)" : "install sox (rec/play), alsa-utils (arecord/aplay) or ffmpeg";
40
+ return kind === "recorder" ? `no microphone recorder found (looked for rec, arecord, ffmpeg) — ${how}` : `no audio player found (looked for afplay, aplay, play, ffplay) — ${how}`;
41
+ }
42
+ const run = (bin, args) => {
43
+ const child = spawn(bin, args, { stdio: "ignore", detached: false });
44
+ ownChild(child, `voice-${bin}`, { cmd: bin }); // killed at exit, reaped if we crash
45
+ return child;
46
+ };
47
+ const ended = (child) => new Promise((resolve) => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
48
+ const signal = (child, sig) => { try {
49
+ child.kill(sig);
50
+ }
51
+ catch { /* already gone */ } };
52
+ const remove = (file) => { try {
53
+ rmSync(file, { force: true });
54
+ }
55
+ catch { /* best-effort */ } };
56
+ let seq = 0;
57
+ /** Start recording into `dir`. `stop` ends it and keeps the audio (SIGINT: the recorder closes its WAV); `cancel`
58
+ * discards it. `done` is the WAV, or null when nothing usable was captured; the file is removed either way. */
59
+ export function recordWav(tool, dir, spawnFn = run) {
60
+ const file = join(dir, `in-${process.pid}-${++seq}.wav`);
61
+ const child = spawnFn(tool.bin, tool.args(file));
62
+ let keep = true;
63
+ const done = ended(child).then(() => {
64
+ try {
65
+ return keep && statSync(file).size > WAV_HEADER_BYTES ? new Uint8Array(readFileSync(file)) : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ finally {
71
+ remove(file);
72
+ }
73
+ });
74
+ return { stop: () => signal(child, "SIGINT"), cancel: () => { keep = false; signal(child, "SIGTERM"); }, done };
75
+ }
76
+ /** Play WAV bytes. `stop` silences it at once; `done` settles when it ends, however it ends. */
77
+ export function playWav(tool, dir, wav, spawnFn = run) {
78
+ const file = join(dir, `out-${process.pid}-${++seq}.wav`);
79
+ writeFileSync(file, wav, { mode: 0o600 });
80
+ const child = spawnFn(tool.bin, tool.args(file));
81
+ return { stop: () => signal(child, "SIGTERM"), done: ended(child).then(() => remove(file)) };
82
+ }
@@ -6,7 +6,7 @@ const KNOWN = new Set([
6
6
  "think", "ultrathink", "compact", "remember", "memory", "mcp", "whoami", "agents", "jobs", "monitor",
7
7
  "bg", "new", "clear", "exit", "quit", "stats", "login", "logout", "remote", "remotecontrol", "rc",
8
8
  "artifacts", "sessions", "skills", "skill", "allow", "caffeinate", "caffeine", "deep-research", "deepresearch",
9
- "research", "pair", "delegate",
9
+ "research", "pair", "delegate", "voice",
10
10
  ]);
11
11
  export const KNOWN_COMMANDS = KNOWN;
12
12
  export function isSlashCommand(text) {
@@ -22,7 +22,7 @@ export function isSlashCommand(text) {
22
22
  * — it is staged and runs on its own when the turn ends. Every KNOWN command has a class; a new command must pick one. */
23
23
  export const MIDTURN = {
24
24
  help: "now", agents: "now", jobs: "now", stats: "now", endpoints: "now", audit: "now", memory: "now", skills: "now",
25
- skill: "now", whoami: "now", monitor: "now", remember: "now", caffeinate: "now", caffeine: "now", bg: "now", dashboard: "now",
25
+ skill: "now", whoami: "now", monitor: "now", remember: "now", caffeinate: "now", caffeine: "now", bg: "now", dashboard: "now", voice: "now",
26
26
  remote: "now", remotecontrol: "now", rc: "now", pair: "now",
27
27
  think: "next", ultrathink: "next", context: "next", ctx: "next", mode: "next", plan: "next", allow: "next", delegate: "next",
28
28
  model: "after", new: "after", compact: "after", clear: "after", route: "after", mcp: "after", login: "after", logout: "after",
@@ -0,0 +1,239 @@
1
+ // Vision training pairs (spec: knowledge-docker _ai-docs/2026-11-24-vision-pairs-spec.md, "vision-pair/1"). Every
2
+ // useful look Operator takes at a public page becomes an (image, target) pair for the owned vision model; Skylark
3
+ // ships the spool to the dataset. Pairs follow the Skylark switches (knowledge-docker
4
+ // _ai-docs/2026-11-24-skylark-session-farming.md): written to the user's OWN space while `skylark.enabled` is on, and
5
+ // marked shareable with AXE's pool only when `skylark.share` is on. One writer for every producer (page_capture, visual_compare, image_analyze):
6
+ // it owns the spool layout, the sha256 image dedupe, the atomic write and the privacy rules. The rules fail
7
+ // closed: anything unsure (a setting it cannot read, a host it cannot classify) writes nothing. Never throws.
8
+ import { createHash, randomUUID } from "node:crypto";
9
+ import { lookup } from "node:dns/promises";
10
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { dirname, join, sep } from "node:path";
13
+ import { isIP } from "node:net";
14
+ const MAX_IMAGE_BYTES = 8 * 1024 * 1024;
15
+ const DEFAULT_MB_PER_DAY = 200;
16
+ const NOTICE = "vision pairs: Operator keeps a small record of public pages it studies in your own Operator folder (up to 200 MB a day) to teach a vision model. Nothing leaves this machine unless skylark.share is on. Turn it off with visionPairs.enabled = false.";
17
+ // Which hosts and checkouts are never captured is the user's policy, not shipped source: `visionPairs.denyHosts`
18
+ // (client domains, subdomains included) and `visionPairs.denyPaths` (folder-name patterns, `*` wildcard) in settings.
19
+ /** On by default (`skylark.enabled` and `visionPairs.enabled` both default true); either set false turns pairs off.
20
+ * `OPERATOR_VISION_PAIRS=0|1` wins, except that 1 never overrides an org's managed policy. */
21
+ export function pairsEnabled(settings, env) {
22
+ const e = env.OPERATOR_VISION_PAIRS;
23
+ if (e === "0")
24
+ return false;
25
+ const configured = !!settings && settings.skylark?.enabled !== false && settings.visionPairs?.enabled !== false;
26
+ if (e === "1")
27
+ return configured || settings?.managed?.status !== "ok";
28
+ return configured;
29
+ }
30
+ /** True when any folder of `cwd` matches a `visionPairs.denyPaths` pattern (case-insensitive, `*` matches anything). */
31
+ /** A folder carries its own protection: `.operator/no-capture` in the working directory or any parent means nothing from
32
+ * a session there is ever captured, on whoever's machine it is opened. Bounded walk; any error means "not marked". */
33
+ export function hasNoCaptureMarker(cwd) {
34
+ try {
35
+ let dir = cwd;
36
+ for (let i = 0; i < 40; i++) {
37
+ if (existsSync(join(dir, ".operator", "no-capture")))
38
+ return true;
39
+ const up = dirname(dir);
40
+ if (up === dir)
41
+ break;
42
+ dir = up;
43
+ }
44
+ }
45
+ catch { /* unreadable: not marked */ }
46
+ return false;
47
+ }
48
+ export function isClientCwd(cwd, denyPaths = []) {
49
+ const res = denyPaths.filter((p) => p.trim()).map((p) => new RegExp(`^${p.trim().replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`, "i"));
50
+ return cwd.split(sep).some((seg) => seg !== "" && res.some((re) => re.test(seg)));
51
+ }
52
+ function privateHost(host) {
53
+ const h = host.replace(/^\[|\]$/g, "").toLowerCase();
54
+ if (h === "localhost" || h.endsWith(".localhost") || h.endsWith(".local") || h.endsWith(".internal") || h.endsWith(".lan"))
55
+ return true;
56
+ const kind = isIP(h);
57
+ if (kind === 4) {
58
+ const [a, b, c] = h.split(".").map(Number);
59
+ return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) ||
60
+ (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || (a === 198 && (b === 18 || b === 19)) ||
61
+ (a === 192 && b === 0 && c === 0) || a >= 224;
62
+ }
63
+ if (kind === 6) {
64
+ if (h === "::1" || h === "::")
65
+ return true;
66
+ const mapped = h.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
67
+ if (mapped)
68
+ return privateHost(mapped[1]);
69
+ const hex = h.match(/^(?:64:ff9b::|2002:)([0-9a-f]{1,4}):?([0-9a-f]{1,4})?/); // NAT64 and 6to4 carry an IPv4 address
70
+ if (hex && (h.startsWith("64:ff9b::") || h.startsWith("2002:"))) {
71
+ const [x, y] = h.startsWith("2002:") ? [parseInt(h.split(":")[1] ?? "0", 16), parseInt(h.split(":")[2] ?? "0", 16)] : [parseInt(hex[1] ?? "0", 16), parseInt(hex[2] ?? "0", 16)];
72
+ return privateHost(`${x >> 8}.${x & 255}.${y >> 8}.${y & 255}`);
73
+ }
74
+ return /^f[cd]/.test(h) || /^fe[89ab]/.test(h);
75
+ }
76
+ return !h.includes("."); // a single-label name is an intranet host
77
+ }
78
+ /** The pair's source URL, or why it may not be recorded: http(s) only, query and fragment stripped, never a
79
+ * private/loopback/link-local host or a denied one (a denied domain covers its subdomains). */
80
+ export function cleanSourceUrl(raw, denyHosts = []) {
81
+ let u;
82
+ try {
83
+ u = new URL(raw);
84
+ }
85
+ catch {
86
+ return { reason: "source url does not parse" };
87
+ }
88
+ if (u.protocol !== "http:" && u.protocol !== "https:")
89
+ return { reason: `source scheme ${u.protocol} is not http(s)` };
90
+ if (u.username || u.password)
91
+ return { reason: "source url carries credentials" };
92
+ const host = u.hostname.toLowerCase();
93
+ if (privateHost(host))
94
+ return { reason: `source host ${host} is local or private` };
95
+ const deny = [...denyHosts].map((d) => d.toLowerCase().replace(/^\.+/, ""));
96
+ if (deny.some((d) => d && (host === d || host.endsWith(`.${d}`))))
97
+ return { reason: `source host ${host} is on the deny list` };
98
+ u.search = "";
99
+ u.hash = "";
100
+ return { url: u.toString() };
101
+ }
102
+ /** A name is judged by what it resolves to, not by how it looks: an intranet or VPN site on a public-looking name
103
+ * resolves to a private address. Fails closed when nothing resolves. */
104
+ async function resolvesPublic(host, resolve) {
105
+ if (isIP(host.replace(/^\[|\]$/g, "")))
106
+ return null; // a literal was already judged by privateHost
107
+ let addrs;
108
+ try {
109
+ addrs = resolve ? await resolve(host) : (await lookup(host, { all: true, verbatim: true })).map((a) => a.address);
110
+ }
111
+ catch {
112
+ return `source host ${host} does not resolve`;
113
+ }
114
+ if (!addrs.length)
115
+ return `source host ${host} does not resolve`;
116
+ const bad = addrs.find((a) => privateHost(a));
117
+ return bad ? `source host ${host} resolves to a private address` : null;
118
+ }
119
+ function operatorVersion() {
120
+ try {
121
+ return JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
122
+ }
123
+ catch {
124
+ return "unknown";
125
+ }
126
+ }
127
+ /** `$KODE_HOME/vision-pairs` when set (a profile or a test home is honoured), else `$OPERATOR_HOME` or `~/.operator`. */
128
+ function defaultRoot(env) {
129
+ return join(env.KODE_HOME || env.OPERATOR_HOME || join(homedir(), ".operator"), "vision-pairs");
130
+ }
131
+ function atomicWrite(path, data) {
132
+ const tmp = `${path}.tmp-${process.pid}-${randomUUID().slice(0, 8)}`;
133
+ writeFileSync(tmp, data, { mode: 0o600 });
134
+ renameSync(tmp, path);
135
+ }
136
+ /** Write one pair to the spool, or explain why not. Images are stored once by sha256; the pair file is atomic. */
137
+ export async function writePair(input, opts = {}) {
138
+ try {
139
+ const env = opts.env ?? process.env;
140
+ let settings = opts.settings;
141
+ if (!settings) {
142
+ try {
143
+ const mod = "../config/settings.js";
144
+ const { loadSettings } = await import(/* webpackIgnore: true */ mod);
145
+ const all = loadSettings();
146
+ settings = { skylark: all.skylark, visionPairs: all.visionPairs, managed: all.managed };
147
+ }
148
+ catch {
149
+ settings = undefined;
150
+ } // unreadable settings: off, unless the env says 1
151
+ }
152
+ if (!pairsEnabled(settings, env))
153
+ return { written: false, reason: "vision pairs are off" };
154
+ if (isClientCwd(opts.cwd ?? process.cwd(), settings?.visionPairs?.denyPaths ?? []))
155
+ return { written: false, reason: "client checkout: nothing is captured" };
156
+ if (hasNoCaptureMarker(opts.cwd ?? process.cwd()))
157
+ return { written: false, reason: "this folder is marked no-capture (client work): nothing is captured" };
158
+ if (!input.images.length)
159
+ return { written: false, reason: "no images" };
160
+ if (!/^(dom|generator|model:\S+)$/.test(input.labelOrigin))
161
+ return { written: false, reason: `label origin ${input.labelOrigin} is not dom, generator or model:<id>` };
162
+ if (input.labelOrigin.startsWith("model:") && !input.teacher)
163
+ return { written: false, reason: "a teacher label needs its teacher" };
164
+ let sourceUrl;
165
+ if (input.source.type === "public-web") {
166
+ const c = cleanSourceUrl(input.source.url ?? "", settings?.visionPairs?.denyHosts ?? []);
167
+ if ("reason" in c)
168
+ return { written: false, reason: c.reason };
169
+ sourceUrl = c.url;
170
+ const bad = await resolvesPublic(new URL(c.url).hostname, opts.resolve);
171
+ if (bad)
172
+ return { written: false, reason: bad };
173
+ }
174
+ else if (input.source.type !== "generated")
175
+ return { written: false, reason: "unknown source type" };
176
+ else if (input.source.url)
177
+ return { written: false, reason: "a generated page has no source url" };
178
+ const blobs = input.images.map((im) => (typeof im.png === "string" ? new Uint8Array(readFileSync(im.png)) : im.png));
179
+ for (const b of blobs) {
180
+ if (b.length > MAX_IMAGE_BYTES)
181
+ return { written: false, reason: `an image is over ${MAX_IMAGE_BYTES / 1048576} MB` };
182
+ if (!(b[0] === 137 && b[1] === 80 && b[2] === 78 && b[3] === 71))
183
+ return { written: false, reason: "an image is not a PNG" };
184
+ }
185
+ const root = opts.root ?? defaultRoot(env);
186
+ const now = opts.now ?? new Date();
187
+ const day = now.toISOString().slice(0, 10);
188
+ const imagesDir = join(root, "images");
189
+ const dayDir = join(root, "pairs", day);
190
+ mkdirSync(imagesDir, { recursive: true, mode: 0o700 });
191
+ mkdirSync(dayDir, { recursive: true, mode: 0o700 });
192
+ const shas = blobs.map((b) => createHash("sha256").update(b).digest("hex"));
193
+ const fresh = blobs.map((b, i) => ({ b, sha: shas[i] })).filter(({ sha }, i) => !existsSync(join(imagesDir, `${sha}.png`)) && shas.indexOf(sha) === i);
194
+ const usageFile = join(dayDir, ".bytes");
195
+ let used = 0;
196
+ try {
197
+ used = Number(readFileSync(usageFile, "utf8")) || 0;
198
+ }
199
+ catch { /* first write today */ }
200
+ const pair = {
201
+ schema: "vision-pair/1",
202
+ id: randomUUID(),
203
+ created: now.toISOString().replace(/\.\d{3}Z$/, "Z"),
204
+ kind: input.kind,
205
+ images: input.images.map((im, i) => ({
206
+ sha256: shas[i], width: im.width, height: im.height,
207
+ ...(im.viewport ? { viewport: im.viewport } : {}), ...(im.tile != null ? { tile: im.tile } : {}),
208
+ })),
209
+ source: sourceUrl ? { type: input.source.type, url: sourceUrl } : { type: input.source.type },
210
+ prompt: input.prompt,
211
+ target: input.target,
212
+ label_origin: input.labelOrigin,
213
+ teacher: input.teacher ?? null,
214
+ producer: { tool: input.tool, operator_version: operatorVersion() },
215
+ space: "own",
216
+ shareable: settings?.skylark?.share === true,
217
+ };
218
+ const body = `${JSON.stringify(pair)}\n`;
219
+ const adding = fresh.reduce((n, f) => n + f.b.length, 0) + body.length;
220
+ const cap = (settings?.visionPairs?.maxMBPerDay ?? DEFAULT_MB_PER_DAY) * 1048576;
221
+ if (used + adding > cap)
222
+ return { written: false, reason: `today's ${settings?.visionPairs?.maxMBPerDay ?? DEFAULT_MB_PER_DAY} MB cap is reached` };
223
+ for (const f of fresh)
224
+ atomicWrite(join(imagesDir, `${f.sha}.png`), f.b);
225
+ const path = join(dayDir, `${pair.id}.json`);
226
+ atomicWrite(path, body);
227
+ atomicWrite(usageFile, String(used + adding));
228
+ const noticeFile = join(root, ".notice");
229
+ let notice;
230
+ if (!existsSync(noticeFile)) {
231
+ atomicWrite(noticeFile, "shown\n");
232
+ notice = NOTICE;
233
+ }
234
+ return { written: true, path, ...(notice ? { notice } : {}) };
235
+ }
236
+ catch (e) {
237
+ return { written: false, reason: `write failed: ${e?.message ?? e}` };
238
+ }
239
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.2.1",
3
+ "version": "0.2.2-next.1",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",