@0perator/operator 0.1.277 → 0.1.283

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.
@@ -0,0 +1,265 @@
1
+ // Session-owned child processes. The ONE place that knows which processes THIS Operator spawned, so that
2
+ // - exit kills exactly those — never the launchd-owned shared services (Aurora, autopilot), which are never registered here;
3
+ // - a crashed or killed Operator's leftovers are reaped by the next one, so a fresh `operator` never stacks on a previous
4
+ // one's orphans. Detached shells and background jobs (own session/group) survive a SIGKILL, a power-cut terminal, a crash.
5
+ //
6
+ // Every spawn site registers its child with `ownChild` (a tripwire test fails any new `spawn(` that neither registers nor says
7
+ // why it is exempt). Registration is mirrored to a per-session pidfile (`<home>/run/<operator pid>.json`, 0600, atomic).
8
+ // Reaping only ever touches a pidfile whose OWNER is dead (pid gone, or the pid reused by a process with a different start
9
+ // time), and only a child that is still the same process: same start time (±5s) and same executable. A recycled pid is
10
+ // never killed.
11
+ //
12
+ // Node-lazy (process.getBuiltinModule, no static `node:` import) so this stays loadable from the JSCore/browser bundle: there
13
+ // nothing is ever registered and every call is a no-op.
14
+ import { operatorPath } from "../config/home.js";
15
+ const unrefStream = (s) => { try {
16
+ s?.unref?.();
17
+ }
18
+ catch { /* not a socket */ } };
19
+ const entries = new Map();
20
+ let hooked = false;
21
+ const OWNER_STARTED = () => Math.round(Date.now() - process.uptime() * 1000);
22
+ let ownerStarted;
23
+ function builtins() {
24
+ try {
25
+ const proc = globalThis.process;
26
+ const fs = proc?.getBuiltinModule?.("node:fs");
27
+ const path = proc?.getBuiltinModule?.("node:path");
28
+ const cp = proc?.getBuiltinModule?.("node:child_process");
29
+ return fs && path && cp ? { fs, path, cp } : null;
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ const runDir = () => operatorPath("run");
36
+ const pidfileFor = (b, pid) => b.path.join(runDir(), `${pid}.json`);
37
+ /** Does `pid` exist? (EPERM = exists but is not ours: still alive.) */
38
+ function isAlive(pid) {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch (e) {
44
+ return e.code === "EPERM";
45
+ }
46
+ }
47
+ function sleepSync(ms) {
48
+ try {
49
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
50
+ }
51
+ catch { /* no SharedArrayBuffer: skip the grace */ }
52
+ }
53
+ function signal(e, sig) {
54
+ try {
55
+ process.kill(e.group ? -e.pid : e.pid, sig);
56
+ }
57
+ catch {
58
+ try {
59
+ process.kill(e.pid, sig);
60
+ }
61
+ catch { /* already gone */ }
62
+ }
63
+ }
64
+ /** Register a spawned child as session-owned. Safe to call with anything: a bad pid or a missing fs is simply ignored.
65
+ * The child is unref'd — being owned means we kill it at exit, so it must never be what keeps Operator alive after the
66
+ * session is over (a running background job used to freeze `operator` after /exit and orphan the job). */
67
+ export function ownChild(proc, label, opts = {}) {
68
+ try {
69
+ const pid = proc.pid;
70
+ if (!pid || pid <= 1 || pid === process.pid)
71
+ return;
72
+ entries.set(pid, { pid, label, cmd: (opts.cmd ?? label).slice(0, 240), startedAt: Date.now(), group: !!opts.group });
73
+ install();
74
+ persist();
75
+ proc.once?.("exit", () => disownChild(pid));
76
+ try {
77
+ proc.unref?.();
78
+ }
79
+ catch { /* not a real ChildProcess */ }
80
+ unrefStream(proc.stdin);
81
+ unrefStream(proc.stdout);
82
+ unrefStream(proc.stderr);
83
+ }
84
+ catch { /* tracking must never block or fail a spawn */ }
85
+ }
86
+ export function disownChild(pid) {
87
+ if (entries.delete(pid))
88
+ persist();
89
+ }
90
+ /** What this session currently owns (for /doctor-style surfaces and tests). */
91
+ export function ownedChildren() {
92
+ return [...entries.values()].map(({ pid, label, group }) => ({ pid, label, group }));
93
+ }
94
+ function persist() {
95
+ try {
96
+ const b = builtins();
97
+ if (!b)
98
+ return;
99
+ const file = pidfileFor(b, process.pid);
100
+ if (!entries.size) {
101
+ b.fs.rmSync(file, { force: true });
102
+ return;
103
+ }
104
+ b.fs.mkdirSync(b.path.dirname(file), { recursive: true, mode: 0o700 });
105
+ const tmp = `${file}.tmp`;
106
+ b.fs.writeFileSync(tmp, JSON.stringify({ owner: { pid: process.pid, startedAt: (ownerStarted ??= OWNER_STARTED()) }, children: [...entries.values()] }), { mode: 0o600 });
107
+ b.fs.renameSync(tmp, file); // atomic: a concurrent reaper never reads half a file
108
+ }
109
+ catch { /* best-effort */ }
110
+ }
111
+ /** Remove this session's pidfile (clean exit). Idempotent. */
112
+ export function removePidfile() {
113
+ try {
114
+ const b = builtins();
115
+ if (b)
116
+ b.fs.rmSync(pidfileFor(b, process.pid), { force: true });
117
+ }
118
+ catch { /* */ }
119
+ }
120
+ /** The universal backstop: however the process ends, whatever it still owns dies with it. Once, lazily, at the first spawn. */
121
+ function install() {
122
+ if (hooked)
123
+ return;
124
+ hooked = true;
125
+ process.once("exit", () => { killOwnedChildrenSync(); removePidfile(); });
126
+ }
127
+ /** Stop every owned child and WAIT for them: SIGTERM (to the process group for shells/jobs), up to `graceMs` for them to go,
128
+ * then SIGKILL whatever is left. Resolves with how many were stopped. Never throws. */
129
+ export async function killOwnedChildren(opts = {}) {
130
+ const victims = [...entries.values()];
131
+ for (const e of victims)
132
+ signal(e, "SIGTERM");
133
+ const deadline = Date.now() + (opts.graceMs ?? 1500);
134
+ // Node reaps its own children: an exited child fires 'exit', which disowns it — so "gone" == "no longer in the map".
135
+ while (victims.some((e) => entries.has(e.pid)) && Date.now() < deadline)
136
+ await new Promise((r) => setTimeout(r, 25));
137
+ for (const e of victims)
138
+ if (entries.has(e.pid))
139
+ signal(e, "SIGKILL");
140
+ const reaped = Date.now() + 500; // SIGKILL is prompt: wait for the exits so "torn down" means gone, not merely signalled
141
+ while (victims.some((e) => entries.has(e.pid)) && Date.now() < reaped)
142
+ await new Promise((r) => setTimeout(r, 10));
143
+ for (const e of victims)
144
+ entries.delete(e.pid);
145
+ persist();
146
+ return victims.length;
147
+ }
148
+ /** The same, for a context that cannot await (a `process.on("exit")` handler or a signal handler): SIGTERM, a short blocking
149
+ * grace, SIGKILL for survivors. */
150
+ export function killOwnedChildrenSync(graceMs = 250) {
151
+ const victims = [...entries.values()];
152
+ if (!victims.length)
153
+ return 0;
154
+ for (const e of victims)
155
+ signal(e, "SIGTERM");
156
+ const deadline = Date.now() + graceMs;
157
+ while (Date.now() < deadline && victims.some((e) => isAlive(e.pid)))
158
+ sleepSync(10);
159
+ for (const e of victims)
160
+ if (isAlive(e.pid))
161
+ signal(e, "SIGKILL");
162
+ entries.clear();
163
+ persist();
164
+ return victims.length;
165
+ }
166
+ // ---- reaping a dead session's leftovers -----------------------------------------------------------------------------
167
+ /** `ps` start time + command for a pid, or undefined when it does not exist. */
168
+ function psInfo(b, pid) {
169
+ try {
170
+ const out = b.cp.execFileSync("ps", ["-o", "lstart=,command=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim();
171
+ if (!out)
172
+ return undefined;
173
+ const startedAt = Date.parse(out.slice(0, 24).trim());
174
+ return Number.isFinite(startedAt) ? { startedAt, command: out.slice(24).trim() } : undefined;
175
+ }
176
+ catch {
177
+ return undefined;
178
+ }
179
+ }
180
+ const START_TOLERANCE_MS = 5000; // ps reports whole seconds, in local time
181
+ /** Is the live process still the one we recorded? Start time is the strong signal (a recycled pid starts later than the original
182
+ * ever ran); the command line is the second — compared loosely, because `bash -c 'sleep 777'` execs straight into `sleep 777`,
183
+ * so the recorded argv[0] may no longer be what ps shows. Any recorded non-flag token appearing in ps's command is enough. */
184
+ function looksSame(recordedCmd, psCommand, b) {
185
+ const tokens = recordedCmd.split(/\s+/).filter((t) => t && !t.startsWith("-")).map((t) => b.path.basename(t)).filter((t) => t.length >= 3);
186
+ return tokens.some((t) => psCommand.includes(t));
187
+ }
188
+ /** On start: find pidfiles whose owning Operator is dead and stop the children it left behind. A concurrent LIVE session is
189
+ * never touched (its owner pid exists with the recorded start time); a pid that has been reused by something else is never
190
+ * killed (start time and executable must both still match). Sync, cheap (a directory listing when there is nothing to do). */
191
+ export function reapStaleChildren() {
192
+ const report = { owners: 0, killed: [], skipped: 0 };
193
+ const skippedPids = [];
194
+ try {
195
+ const b = builtins();
196
+ if (!b || process.platform === "win32")
197
+ return report;
198
+ const dir = runDir();
199
+ let names;
200
+ try {
201
+ names = b.fs.readdirSync(dir);
202
+ }
203
+ catch {
204
+ return report;
205
+ }
206
+ for (const name of names) {
207
+ if (!/^\d+\.json$/.test(name))
208
+ continue;
209
+ const file = b.path.join(dir, name);
210
+ const ownerPid = Number(name.slice(0, -5));
211
+ if (ownerPid === process.pid)
212
+ continue;
213
+ let rec;
214
+ try {
215
+ rec = JSON.parse(b.fs.readFileSync(file, "utf8"));
216
+ }
217
+ catch { // unreadable: leave a fresh one (being written elsewhere); an old one is debris
218
+ try {
219
+ if (Date.now() - b.fs.statSync(file).mtimeMs > 3_600_000)
220
+ b.fs.rmSync(file, { force: true });
221
+ }
222
+ catch { /* */ }
223
+ continue;
224
+ }
225
+ const owner = rec.owner;
226
+ if (owner?.pid && isAlive(owner.pid)) {
227
+ const info = psInfo(b, owner.pid);
228
+ if (!info || typeof owner.startedAt !== "number" || Math.abs(info.startedAt - owner.startedAt) <= START_TOLERANCE_MS)
229
+ continue; // a live session (or ps unavailable: err on the side of NOT killing)
230
+ }
231
+ for (const c of rec.children ?? []) {
232
+ if (!c?.pid || c.pid <= 1 || c.pid === process.pid || !isAlive(c.pid)) {
233
+ report.skipped++;
234
+ continue;
235
+ }
236
+ const info = psInfo(b, c.pid);
237
+ if (!info || Math.abs(info.startedAt - c.startedAt) > START_TOLERANCE_MS || !looksSame(c.cmd ?? "", info.command, b)) {
238
+ report.skipped++;
239
+ skippedPids.push(c.pid);
240
+ continue;
241
+ } // pid reused: not ours
242
+ signal(c, "SIGTERM");
243
+ sleepSync(100);
244
+ if (isAlive(c.pid))
245
+ signal(c, "SIGKILL");
246
+ report.killed.push({ pid: c.pid, label: c.label, owner: ownerPid });
247
+ }
248
+ try {
249
+ b.fs.rmSync(file, { force: true });
250
+ report.owners++;
251
+ }
252
+ catch { /* */ }
253
+ }
254
+ if (report.killed.length) {
255
+ try {
256
+ const now = new Date().toISOString();
257
+ b.fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
258
+ b.fs.appendFileSync(b.path.join(dir, "reaped.log"), report.killed.map((k) => `${now} reaped pid=${k.pid} (${k.label}) left by dead session ${k.owner}`).join("\n") + "\n", { mode: 0o600 });
259
+ }
260
+ catch { /* */ }
261
+ }
262
+ }
263
+ catch { /* reaping is housekeeping: it must never stop Operator starting */ }
264
+ return report;
265
+ }
@@ -0,0 +1,47 @@
1
+ // Snapshot ephemeral screenshot temp files the instant they enter the prompt.
2
+ //
3
+ // macOS hands a dragged screenshot to the terminal as a path under a per-user temp root
4
+ // (/var/folders/.../TemporaryItems/NSIRD_screencaptureui_*/Screenshot ....png) that the OS
5
+ // DELETES within seconds -- long before the model reasons and calls image_analyze, which then
6
+ // fails with "could not read a file" (and, scrambling for a substitute, can analyze the wrong
7
+ // file twice). So we copy any such ephemeral image to a durable attachments dir at INPUT time
8
+ // and rewrite the reference to the copy. Local paths (Desktop/Downloads) are stable and pass
9
+ // through untouched. Pure, synchronous, model-agnostic input preprocessing -- the same seam and
10
+ // shape as expandFileMentions, run on the user's text before it reaches the model.
11
+ import { statSync, copyFileSync, mkdirSync } from "node:fs";
12
+ import { operatorPath } from "../config/home.js";
13
+ // A path under the macOS per-user temp root (/var/folders, optionally /private-prefixed) or /tmp,
14
+ // ending in an image extension. "\\ " matches a shell-escaped space so a dragged screenshot's
15
+ // spaced filename ("Screenshot 2026-10-11 at 9.00.10 PM.png") is captured whole; "\S" covers the
16
+ // rest. Lazy so it stops at the first image extension and never spans two paths.
17
+ const EPHEMERAL_IMG_RE = /(?:\/private)?\/(?:var\/folders|tmp)\/(?:\\ |\S)+?\.(?:png|jpe?g|gif|webp|bmp|heic|heif|tiff?)/gi;
18
+ const MAX_SNAPSHOT_BYTES = 64 * 1024 * 1024;
19
+ let seq = 0;
20
+ // Replace every ephemeral screenshot/image path in `text` that still exists on disk with a durable
21
+ // copy under the operator home's attachments dir. Anything that cannot be snapshotted (already
22
+ // deleted, unreadable, too large) is left exactly as written -- the tool then surfaces its own
23
+ // clear "could not read a file" error. Returns text unchanged when nothing matched.
24
+ export function snapshotEphemeralImages(text) {
25
+ // Cheap bail-out: only the macOS screenshot/temp shapes are worth scanning.
26
+ if (!text || !/\/var\/folders\/|TemporaryItems|NSIRD_|\/tmp\//i.test(text))
27
+ return text;
28
+ let changed = false;
29
+ const out = text.replace(EPHEMERAL_IMG_RE, (match) => {
30
+ const real = match.replace(/\\ /g, " "); // unescape shell-escaped spaces for the fs call
31
+ try {
32
+ const st = statSync(real);
33
+ if (!st.isFile() || st.size === 0 || st.size > MAX_SNAPSHOT_BYTES)
34
+ return match;
35
+ const ext = (real.split(".").pop() || "png").toLowerCase();
36
+ mkdirSync(operatorPath("attachments"), { recursive: true, mode: 0o700 });
37
+ const dest = operatorPath("attachments", "shot-" + Date.now() + "-" + seq++ + "." + ext);
38
+ copyFileSync(real, dest);
39
+ changed = true;
40
+ return dest; // clean, space-free path -- no downstream escaping needed
41
+ }
42
+ catch {
43
+ return match; // vanished / unreadable -- leave as-is; image_analyze reports it plainly
44
+ }
45
+ });
46
+ return changed ? out : text;
47
+ }
@@ -0,0 +1,64 @@
1
+ export class Teardown {
2
+ steps = [];
3
+ all;
4
+ seq = 0;
5
+ stepTimeoutMs;
6
+ onError;
7
+ constructor(opts = {}) {
8
+ this.stepTimeoutMs = opts.stepTimeoutMs ?? 3000;
9
+ this.onError = opts.onError ?? (() => { });
10
+ }
11
+ add(name, run, opts = {}) {
12
+ this.steps.push({ name, run, sync: opts.sync, order: opts.order ?? 50, seq: this.seq++, state: "idle" });
13
+ this.steps.sort((a, b) => a.order - b.order || a.seq - b.seq);
14
+ }
15
+ /** Names in execution order (tests, diagnostics). */
16
+ names() { return this.steps.map((s) => s.name); }
17
+ /** True once every registered step has finished. */
18
+ get finished() { return this.steps.length > 0 && this.steps.every((s) => s.state === "done"); }
19
+ /** Graceful teardown. Memoized: the first call does the work, every later call gets the same promise. Never rejects. */
20
+ run(reason) {
21
+ return (this.all ??= (async () => {
22
+ for (const s of [...this.steps]) {
23
+ if (s.state === "done")
24
+ continue;
25
+ s.state = "running";
26
+ let timer;
27
+ try {
28
+ await Promise.race([
29
+ Promise.resolve().then(() => s.run(reason)),
30
+ new Promise((_, rej) => { timer = setTimeout(() => rej(new Error(`step "${s.name}" timed out after ${this.stepTimeoutMs}ms`)), this.stepTimeoutMs); }),
31
+ ]);
32
+ s.state = "done";
33
+ }
34
+ catch (e) {
35
+ this.onError(s.name, e); // a hung step stays "running": runSync() will still try its sync half at process exit
36
+ }
37
+ finally {
38
+ clearTimeout(timer);
39
+ }
40
+ }
41
+ })());
42
+ }
43
+ /** Synchronous teardown for a signal handler or `process.on("exit")`. Runs the sync half of every step that has not finished
44
+ * (so a finished step is never repeated) and marks it done. */
45
+ runSync(reason) {
46
+ for (const s of [...this.steps]) {
47
+ if (s.state === "done")
48
+ continue;
49
+ try {
50
+ if (s.sync)
51
+ s.sync(reason);
52
+ else {
53
+ const r = s.run(reason);
54
+ if (r && typeof r.catch === "function")
55
+ r.catch(() => { });
56
+ }
57
+ }
58
+ catch (e) {
59
+ this.onError(s.name, e);
60
+ }
61
+ s.state = "done";
62
+ }
63
+ }
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.277",
3
+ "version": "0.1.283",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",
@@ -28,6 +28,8 @@
28
28
  "@zed-industries/agent-client-protocol": "^0.4.5",
29
29
  "chalk": "^5.6.2",
30
30
  "ink": "^5.0.1",
31
+ "marked": "^12.0.2",
32
+ "pdfkit": "^0.15.2",
31
33
  "qrcode": "^1.5.4",
32
34
  "react": "^18.3.1",
33
35
  "ws": "^8.18.0"
@@ -35,6 +37,7 @@
35
37
  "devDependencies": {
36
38
  "@biomejs/biome": "2.5.14",
37
39
  "@types/node": "^22.20.3",
40
+ "@types/pdfkit": "^0.13.9",
38
41
  "@types/qrcode": "^1.5.6",
39
42
  "@types/react": "^18.3.3",
40
43
  "ink-testing-library": "^3.0.0",