@0perator/operator 0.1.277 → 0.1.282
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +8 -3
- package/dist/auth/commands.js +1 -0
- package/dist/autonomy/delegate.js +6 -11
- package/dist/autonomy/keepawake.js +2 -0
- package/dist/browser/cdp.js +5 -0
- package/dist/cli.js +103 -20
- package/dist/config/persona.js +24 -5
- package/dist/config/scaffold.js +1 -1
- package/dist/engine/agent.js +12 -0
- package/dist/engine/aurora.js +6 -0
- package/dist/engine/grandmaster.js +29 -4
- package/dist/mcp/stdio.js +2 -0
- package/dist/permissions/audit.js +29 -0
- package/dist/permissions/index.js +25 -13
- package/dist/remote/host.js +106 -5
- package/dist/services/preflight.js +1 -0
- package/dist/session-teardown.js +11 -0
- package/dist/session.js +42 -2
- package/dist/telemetry/events.js +22 -2
- package/dist/telemetry/ingest.js +574 -0
- package/dist/telemetry/lifecycle.js +35 -0
- package/dist/telemetry/sha256.js +75 -0
- package/dist/tools/document.js +203 -0
- package/dist/tools/registry.js +30 -2
- package/dist/tools/sandbox.js +3 -1
- package/dist/tools/shell-session.js +2 -0
- package/dist/ui/App.js +2 -2
- package/dist/util/owned-children.js +265 -0
- package/dist/util/screenshots.js +47 -0
- package/dist/util/teardown.js +64 -0
- package/package.json +4 -1
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// sha256 of a UTF-8 string as lowercase hex. Sync by design: the permission wrapper hashes tool args on the hot
|
|
2
|
+
// path and must not await. Two paths, one digest: Node's native hash when reachable (process.getBuiltinModule —
|
|
3
|
+
// no static `node:` import, so this stays loadable in the JSCore/browser bundle, same discipline as config/home.ts)
|
|
4
|
+
// and a pure-JS implementation for hosts that have no node builtins.
|
|
5
|
+
const K = new Uint32Array([
|
|
6
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
7
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
8
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
9
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
10
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
11
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
12
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
13
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
|
|
14
|
+
]);
|
|
15
|
+
/** Pure-JS SHA-256 over raw bytes. Exported for the cross-check against node:crypto in the tests. */
|
|
16
|
+
export function sha256PureBytes(msg) {
|
|
17
|
+
const h = new Uint32Array([0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]);
|
|
18
|
+
const len = msg.length;
|
|
19
|
+
const padded = new Uint8Array(((len + 9 + 63) >> 6) << 6);
|
|
20
|
+
padded.set(msg);
|
|
21
|
+
padded[len] = 0x80;
|
|
22
|
+
const dv = new DataView(padded.buffer);
|
|
23
|
+
dv.setUint32(padded.length - 8, Math.floor((len * 8) / 0x100000000));
|
|
24
|
+
dv.setUint32(padded.length - 4, (len * 8) >>> 0);
|
|
25
|
+
const w = new Uint32Array(64);
|
|
26
|
+
for (let off = 0; off < padded.length; off += 64) {
|
|
27
|
+
for (let i = 0; i < 16; i++)
|
|
28
|
+
w[i] = dv.getUint32(off + i * 4);
|
|
29
|
+
for (let i = 16; i < 64; i++) {
|
|
30
|
+
const a = w[i - 15], b = w[i - 2];
|
|
31
|
+
const s0 = ((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3);
|
|
32
|
+
const s1 = ((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10);
|
|
33
|
+
w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
|
|
34
|
+
}
|
|
35
|
+
let a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
|
36
|
+
for (let i = 0; i < 64; i++) {
|
|
37
|
+
const S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
|
|
38
|
+
const ch = (e & f) ^ (~e & g);
|
|
39
|
+
const t1 = (hh + S1 + ch + K[i] + w[i]) >>> 0;
|
|
40
|
+
const S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
|
|
41
|
+
const maj = (a & b) ^ (a & c) ^ (b & c);
|
|
42
|
+
const t2 = (S0 + maj) >>> 0;
|
|
43
|
+
hh = g;
|
|
44
|
+
g = f;
|
|
45
|
+
f = e;
|
|
46
|
+
e = (d + t1) >>> 0;
|
|
47
|
+
d = c;
|
|
48
|
+
c = b;
|
|
49
|
+
b = a;
|
|
50
|
+
a = (t1 + t2) >>> 0;
|
|
51
|
+
}
|
|
52
|
+
h[0] += a;
|
|
53
|
+
h[1] += b;
|
|
54
|
+
h[2] += c;
|
|
55
|
+
h[3] += d;
|
|
56
|
+
h[4] += e;
|
|
57
|
+
h[5] += f;
|
|
58
|
+
h[6] += g;
|
|
59
|
+
h[7] += hh;
|
|
60
|
+
}
|
|
61
|
+
return Array.from(h, (x) => x.toString(16).padStart(8, "0")).join("");
|
|
62
|
+
}
|
|
63
|
+
function sha256Native(s) {
|
|
64
|
+
try {
|
|
65
|
+
const proc = globalThis.process;
|
|
66
|
+
const crypto = proc?.getBuiltinModule?.("node:crypto");
|
|
67
|
+
return crypto?.createHash("sha256").update(s, "utf8").digest("hex");
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function sha256Hex(s) {
|
|
74
|
+
return sha256Native(s) ?? sha256PureBytes(new TextEncoder().encode(s));
|
|
75
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// document_generate — turn markdown (or plain text) into a real, downloadable PDF, with NO external
|
|
2
|
+
// renderer (no Chrome/pandoc/wkhtmltopdf). Pure-JS via pdfkit + marked, so it works on any machine
|
|
3
|
+
// Operator runs on (the owner's box AND an end-user download alike). Produces a clean, professional
|
|
4
|
+
// report/brief/deck-notes PDF: title page, headings, paragraphs with inline bold/italic/code/links,
|
|
5
|
+
// bullet + numbered lists, blockquotes, code blocks, tables, horizontal rules, and local images.
|
|
6
|
+
//
|
|
7
|
+
// Lazy-imports pdfkit/marked/node:fs INSIDE the handler so merely importing this module stays cheap and
|
|
8
|
+
// node-pure (registry.ts is node-only, but we keep the same discipline the rest of the tools use).
|
|
9
|
+
const INK = "#111111";
|
|
10
|
+
const MUTE = "#6b7280";
|
|
11
|
+
const RULE = "#d1d5db";
|
|
12
|
+
const LINK = "#2563eb";
|
|
13
|
+
const CODE_BG = "#f3f4f6";
|
|
14
|
+
export async function documentGenerate(args) {
|
|
15
|
+
const content = String(args.content ?? "").trim();
|
|
16
|
+
if (!content)
|
|
17
|
+
return "error: document_generate needs `content` (markdown or plain text)";
|
|
18
|
+
const title = String(args.title ?? "").trim();
|
|
19
|
+
const subtitle = String(args.subtitle ?? "").trim();
|
|
20
|
+
const PDFDocument = (await import("pdfkit")).default;
|
|
21
|
+
const { marked } = await import("marked");
|
|
22
|
+
const fs = await import("node:fs");
|
|
23
|
+
const path = await import("node:path");
|
|
24
|
+
const { operatorPath } = await import("../config/home.js");
|
|
25
|
+
// Resolve the output path: honor an explicit `out`, else a durable attachments copy.
|
|
26
|
+
let out = String(args.out ?? "").trim();
|
|
27
|
+
if (!out) {
|
|
28
|
+
const dir = operatorPath("attachments");
|
|
29
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
30
|
+
const slug = (title || "document").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "document";
|
|
31
|
+
out = path.join(dir, `${slug}-${Date.now()}.pdf`);
|
|
32
|
+
}
|
|
33
|
+
else if (!out.toLowerCase().endsWith(".pdf")) {
|
|
34
|
+
out = out + ".pdf";
|
|
35
|
+
}
|
|
36
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
37
|
+
const doc = new PDFDocument({ size: "LETTER", margins: { top: 64, bottom: 64, left: 64, right: 64 }, bufferPages: true, info: { Title: title || "Operator document" } });
|
|
38
|
+
const stream = fs.createWriteStream(out);
|
|
39
|
+
doc.pipe(stream);
|
|
40
|
+
const LEFT = doc.page.margins.left;
|
|
41
|
+
const WIDTH = doc.page.width - doc.page.margins.left - doc.page.margins.right;
|
|
42
|
+
// --- cover / title ---
|
|
43
|
+
if (title) {
|
|
44
|
+
doc.moveDown(2);
|
|
45
|
+
doc.fillColor(INK).font("Helvetica-Bold").fontSize(28).text(title, { align: "left" });
|
|
46
|
+
if (subtitle)
|
|
47
|
+
doc.moveDown(0.4).fillColor(MUTE).font("Helvetica").fontSize(13).text(subtitle);
|
|
48
|
+
doc.moveDown(0.8);
|
|
49
|
+
doc.strokeColor(RULE).lineWidth(1).moveTo(LEFT, doc.y).lineTo(LEFT + WIDTH, doc.y).stroke();
|
|
50
|
+
doc.moveDown(1);
|
|
51
|
+
doc.fillColor(INK);
|
|
52
|
+
}
|
|
53
|
+
const tokens = marked.lexer(content);
|
|
54
|
+
for (const t of tokens)
|
|
55
|
+
renderBlock(doc, t, LEFT, WIDTH);
|
|
56
|
+
// --- footer page numbers ---
|
|
57
|
+
const range = doc.bufferedPageRange();
|
|
58
|
+
for (let i = range.start; i < range.start + range.count; i++) {
|
|
59
|
+
doc.switchToPage(i);
|
|
60
|
+
const y = doc.page.height - 40;
|
|
61
|
+
doc.fillColor(MUTE).font("Helvetica").fontSize(9)
|
|
62
|
+
.text(`${i - range.start + 1} / ${range.count}`, LEFT, y, { width: WIDTH, align: "center" });
|
|
63
|
+
}
|
|
64
|
+
doc.end();
|
|
65
|
+
await new Promise((resolve, reject) => {
|
|
66
|
+
stream.on("finish", () => resolve());
|
|
67
|
+
stream.on("error", reject);
|
|
68
|
+
});
|
|
69
|
+
const bytes = fs.statSync(out).size;
|
|
70
|
+
return `created PDF → ${out} (${(bytes / 1024).toFixed(0)} KB, ${range.count} page${range.count === 1 ? "" : "s"})`;
|
|
71
|
+
}
|
|
72
|
+
function renderBlock(doc, t, left, width) {
|
|
73
|
+
switch (t.type) {
|
|
74
|
+
case "heading": {
|
|
75
|
+
const sizes = { 1: 20, 2: 16, 3: 13, 4: 12, 5: 11, 6: 11 };
|
|
76
|
+
doc.moveDown(0.6).fillColor(INK).font("Helvetica-Bold").fontSize(sizes[t.depth || 2] || 13);
|
|
77
|
+
renderInline(doc, t.tokens || [{ type: "text", text: t.text }], left, width);
|
|
78
|
+
doc.moveDown(0.3);
|
|
79
|
+
break;
|
|
80
|
+
}
|
|
81
|
+
case "paragraph": {
|
|
82
|
+
doc.fillColor(INK).font("Helvetica").fontSize(11);
|
|
83
|
+
renderInline(doc, t.tokens || [{ type: "text", text: t.text }], left, width);
|
|
84
|
+
doc.moveDown(0.6);
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
case "list": {
|
|
88
|
+
const ordered = !!t.ordered;
|
|
89
|
+
let n = typeof t.start === "number" ? t.start : 1;
|
|
90
|
+
for (const item of t.items || []) {
|
|
91
|
+
const marker = ordered ? `${n++}.` : "•";
|
|
92
|
+
doc.font("Helvetica").fontSize(11).fillColor(INK);
|
|
93
|
+
doc.text(marker, left, doc.y, { continued: true, width: 20 });
|
|
94
|
+
const itemInline = (item.tokens && item.tokens[0] && item.tokens[0].tokens) || [{ type: "text", text: item.text }];
|
|
95
|
+
renderInline(doc, itemInline, left + 18, width - 18, left + 18);
|
|
96
|
+
doc.moveDown(0.2);
|
|
97
|
+
}
|
|
98
|
+
doc.moveDown(0.4);
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
case "code": {
|
|
102
|
+
doc.font("Courier").fontSize(9.5).fillColor(INK);
|
|
103
|
+
const txt = t.text || "";
|
|
104
|
+
const h = doc.heightOfString(txt, { width: width - 20 }) + 12;
|
|
105
|
+
const y = doc.y;
|
|
106
|
+
doc.rect(left, y, width, h).fill(CODE_BG);
|
|
107
|
+
doc.fillColor(INK).text(txt, left + 10, y + 6, { width: width - 20 });
|
|
108
|
+
doc.moveDown(0.6);
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
case "blockquote": {
|
|
112
|
+
const y0 = doc.y;
|
|
113
|
+
doc.font("Helvetica-Oblique").fontSize(11).fillColor(MUTE);
|
|
114
|
+
doc.text((t.text || "").trim(), left + 14, doc.y, { width: width - 14 });
|
|
115
|
+
doc.strokeColor(RULE).lineWidth(3).moveTo(left + 2, y0).lineTo(left + 2, doc.y).stroke();
|
|
116
|
+
doc.moveDown(0.6).fillColor(INK);
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "hr": {
|
|
120
|
+
doc.moveDown(0.3).strokeColor(RULE).lineWidth(1).moveTo(left, doc.y).lineTo(left + width, doc.y).stroke();
|
|
121
|
+
doc.moveDown(0.6);
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
case "table": {
|
|
125
|
+
renderTable(doc, t, left, width);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
case "space":
|
|
129
|
+
doc.moveDown(0.4);
|
|
130
|
+
break;
|
|
131
|
+
default:
|
|
132
|
+
if (t.text) {
|
|
133
|
+
doc.font("Helvetica").fontSize(11).fillColor(INK).text(t.text, { width });
|
|
134
|
+
doc.moveDown(0.4);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function renderInline(doc, tokens, x, width, indentX) {
|
|
139
|
+
if (!tokens.length) {
|
|
140
|
+
doc.text(" ", { width });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
tokens.forEach((t, i) => {
|
|
144
|
+
const last = i === tokens.length - 1;
|
|
145
|
+
const base = { continued: !last, width };
|
|
146
|
+
if (i === 0 && indentX !== undefined) {
|
|
147
|
+
base.indent = 0;
|
|
148
|
+
}
|
|
149
|
+
switch (t.type) {
|
|
150
|
+
case "strong":
|
|
151
|
+
doc.font("Helvetica-Bold").text(t.text || "", base);
|
|
152
|
+
doc.font("Helvetica");
|
|
153
|
+
break;
|
|
154
|
+
case "em":
|
|
155
|
+
doc.font("Helvetica-Oblique").text(t.text || "", base);
|
|
156
|
+
doc.font("Helvetica");
|
|
157
|
+
break;
|
|
158
|
+
case "codespan":
|
|
159
|
+
doc.font("Courier").fillColor("#b91c1c").text(t.text || "", base);
|
|
160
|
+
doc.font("Helvetica").fillColor(INK);
|
|
161
|
+
break;
|
|
162
|
+
case "link":
|
|
163
|
+
doc.fillColor(LINK).text(t.text || t.href || "", { ...base, link: t.href, underline: true });
|
|
164
|
+
doc.fillColor(INK);
|
|
165
|
+
break;
|
|
166
|
+
case "br":
|
|
167
|
+
doc.text("\n", base);
|
|
168
|
+
break;
|
|
169
|
+
default: doc.text(t.text ?? t.raw ?? "", base);
|
|
170
|
+
}
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
function renderTable(doc, t, left, width) {
|
|
174
|
+
const header = (t.header || []).map((h) => h.text);
|
|
175
|
+
const rows = (t.rows || []).map((r) => r.map((c) => c.text));
|
|
176
|
+
const cols = header.length || (rows[0]?.length ?? 0);
|
|
177
|
+
if (!cols)
|
|
178
|
+
return;
|
|
179
|
+
const colW = width / cols;
|
|
180
|
+
const pad = 5;
|
|
181
|
+
const rowH = (cells, bold) => {
|
|
182
|
+
doc.font(bold ? "Helvetica-Bold" : "Helvetica").fontSize(10);
|
|
183
|
+
let max = 14;
|
|
184
|
+
for (const c of cells)
|
|
185
|
+
max = Math.max(max, doc.heightOfString(c || "", { width: colW - pad * 2 }) + 8);
|
|
186
|
+
const y = doc.y;
|
|
187
|
+
cells.forEach((c, i) => {
|
|
188
|
+
const x = left + i * colW;
|
|
189
|
+
if (bold) {
|
|
190
|
+
doc.rect(x, y, colW, max).fill(CODE_BG);
|
|
191
|
+
doc.fillColor(INK);
|
|
192
|
+
}
|
|
193
|
+
doc.strokeColor(RULE).lineWidth(0.5).rect(x, y, colW, max).stroke();
|
|
194
|
+
doc.fillColor(INK).text(c || "", x + pad, y + 4, { width: colW - pad * 2 });
|
|
195
|
+
});
|
|
196
|
+
doc.y = y + max;
|
|
197
|
+
};
|
|
198
|
+
if (header.length)
|
|
199
|
+
rowH(header, true);
|
|
200
|
+
for (const r of rows)
|
|
201
|
+
rowH(r, false);
|
|
202
|
+
doc.moveDown(0.6);
|
|
203
|
+
}
|
package/dist/tools/registry.js
CHANGED
|
@@ -9,10 +9,12 @@ import { MemoryStore } from "../memory/index.js";
|
|
|
9
9
|
import { indexSessions, readSession, searchSessions } from "../memory/session-index.js";
|
|
10
10
|
import { listLocalSkills, localSkillsDir as profileSkillsDir, resolveSkillFile } from "../config/skills-index.js";
|
|
11
11
|
import { operatorPath } from "../config/home.js";
|
|
12
|
+
import { ownChild } from "../util/owned-children.js";
|
|
12
13
|
import { pexecFile } from "./exec.js";
|
|
13
14
|
import { formatGitStatus } from "./git-status.js";
|
|
14
15
|
import { expandPath } from "./paths.js";
|
|
15
16
|
import { runMemoryTool } from "./memory.js";
|
|
17
|
+
import { documentGenerate } from "./document.js";
|
|
16
18
|
import { runCronTool } from "../autonomy/cron.js";
|
|
17
19
|
import { runDelegateTask } from "../autonomy/delegate.js";
|
|
18
20
|
import { runSessionRewind } from "../memory/session-rewind.js";
|
|
@@ -978,7 +980,11 @@ async function shellBackground(args) {
|
|
|
978
980
|
const { spawn } = await nodeImport("node:child_process");
|
|
979
981
|
const { file, args: argv } = await wrapShell(command); // same OS sandbox wrap as shell_exec
|
|
980
982
|
const id = `sh${++bgSeq}`;
|
|
981
|
-
|
|
983
|
+
// Its own process group, so the WHOLE job tree (`npm run dev` → node → …) can be stopped, not just the top shell. It used to be
|
|
984
|
+
// "not detached: the job dies with Operator" — it did not: a running job outlived /exit, held the event loop open (Operator froze
|
|
985
|
+
// after /exit) and was orphaned. Owned now: killed at exit, reaped by the next Operator if this one crashes.
|
|
986
|
+
const p = spawn(file, argv, { cwd, detached: true });
|
|
987
|
+
ownChild(p, `background job ${id}`, { cmd: `${file} ${argv.join(" ")}`, group: true });
|
|
982
988
|
const job = { proc: p, buf: "", done: false, code: null, started: Date.now(), cmd: command };
|
|
983
989
|
const cap = (d) => { job.buf += d.toString("utf8"); if (job.buf.length > BG_BUF_CAP)
|
|
984
990
|
job.buf = job.buf.slice(-BG_BUF_CAP); };
|
|
@@ -1027,7 +1033,17 @@ async function bashKill(args) {
|
|
|
1027
1033
|
if (job.done)
|
|
1028
1034
|
return `job ${id} already finished (exit ${job.code})`;
|
|
1029
1035
|
try {
|
|
1030
|
-
job.proc.
|
|
1036
|
+
const pid = job.proc.pid;
|
|
1037
|
+
if (pid) {
|
|
1038
|
+
try {
|
|
1039
|
+
process.kill(-pid, "SIGTERM");
|
|
1040
|
+
}
|
|
1041
|
+
catch {
|
|
1042
|
+
job.proc.kill("SIGTERM");
|
|
1043
|
+
}
|
|
1044
|
+
} // the whole job group, falling back to the top process
|
|
1045
|
+
else
|
|
1046
|
+
job.proc.kill("SIGTERM");
|
|
1031
1047
|
return `sent SIGTERM to background job ${id}`;
|
|
1032
1048
|
}
|
|
1033
1049
|
catch (e) {
|
|
@@ -1787,6 +1803,7 @@ async function voiceSpeak(args) {
|
|
|
1787
1803
|
if (play && process.platform === "darwin") {
|
|
1788
1804
|
try {
|
|
1789
1805
|
const { spawn } = await nodeImport("node:child_process");
|
|
1806
|
+
// owned-exempt: short-lived playback, deliberately detached so it finishes after the turn
|
|
1790
1807
|
spawn("afplay", [out], { detached: true, stdio: "ignore" }).unref(); // fire-and-forget; don't block the turn on playback
|
|
1791
1808
|
played = true;
|
|
1792
1809
|
}
|
|
@@ -2218,6 +2235,17 @@ const TOOLS = [
|
|
|
2218
2235
|
}, required: ["content"] },
|
|
2219
2236
|
run: artifactCreate,
|
|
2220
2237
|
},
|
|
2238
|
+
{
|
|
2239
|
+
name: "document_generate",
|
|
2240
|
+
description: "Generate a real, downloadable PDF from markdown (or plain text) — a report, brief, client deliverable, or presentation handout — with NO external renderer (no Chrome/pandoc needed; works on any machine Operator runs). Pass `content` as markdown: headings, **bold**/*italic*, `code`, bullet + numbered lists, tables, code blocks, blockquotes, links, and local images all render with clean typography + page numbers. Optional `title`/`subtitle` add a cover header; `out` sets the path (default a durable attachments/ file). Returns the PDF path to open or send. Use THIS for a downloadable document/deck FILE; use artifact_create for a hosted, shareable HTML page URL.",
|
|
2241
|
+
parameters: { type: "object", properties: {
|
|
2242
|
+
content: { type: "string", description: "the document body as markdown (or plain text)" },
|
|
2243
|
+
title: { type: "string", description: "optional title, rendered as a cover header" },
|
|
2244
|
+
subtitle: { type: "string", description: "optional subtitle / byline under the title" },
|
|
2245
|
+
out: { type: "string", description: "output .pdf path (default a durable attachments/<slug>-<ts>.pdf)" },
|
|
2246
|
+
}, required: ["content"] },
|
|
2247
|
+
run: documentGenerate,
|
|
2248
|
+
},
|
|
2221
2249
|
{
|
|
2222
2250
|
name: "skill_list", safe: true,
|
|
2223
2251
|
description: "List or search AXE skills from the Operator registry (operator.axe.onl /v1/skills) — reusable playbooks for code review, security audit, debugging, architecture, and more. With no query it lists the curated skills; pass a query to search the full catalogue (community skills too). Read-only.",
|
package/dist/tools/sandbox.js
CHANGED
|
@@ -70,7 +70,9 @@ const SECRET_READ_FILES = [`${HOME}/.netrc`, `${HOME}/.git-credentials`];
|
|
|
70
70
|
// evidence — so the sandbox treats these exactly like ~/.ssh. Resolved per call (KODE_HOME / KODE_PROFILE
|
|
71
71
|
// can differ per process); ordinary state (memories, skills, sessions) stays writable.
|
|
72
72
|
const OP_WRITE_PROTECTED_FILES = ["settings.json", "settings.local.json", "managed-settings.json", "identity.json", "home.json", "credentials.json", "byo.json", "events.jsonl"];
|
|
73
|
-
|
|
73
|
+
// `run` holds the per-session pidfiles util/owned-children.ts reaps from: Operator (unsandboxed) trusts them to stop processes, so the agent
|
|
74
|
+
// must not be able to plant one naming a process it wants dead.
|
|
75
|
+
const OP_WRITE_PROTECTED_DIRS = ["vault", "audit", "run"];
|
|
74
76
|
const OP_SECRET_FILES = ["credentials.json", "byo.json"];
|
|
75
77
|
const OP_SECRET_DIRS = ["vault"];
|
|
76
78
|
const opPaths = (names) => names.map((n) => resolve(`${get_operator_home()}/${n}`));
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
//
|
|
15
15
|
// node-only; imported lazily from the tool layer so the neutral (mobile) bundle never pulls it.
|
|
16
16
|
import { wrapInteractiveShell } from "./sandbox.js";
|
|
17
|
+
import { ownChild } from "../util/owned-children.js";
|
|
17
18
|
// Variable-specifier dynamic import: esbuild --platform=neutral (the mobile/JSCore purity gate)
|
|
18
19
|
// STATICALLY resolves a string-literal `import("node:...")` and errors on it, but cannot resolve a
|
|
19
20
|
// variable specifier, so the Node builtin stays out of the neutral bundle. Same idiom as
|
|
@@ -45,6 +46,7 @@ export class ShellSession {
|
|
|
45
46
|
stdio: ["pipe", "pipe", "pipe"],
|
|
46
47
|
detached: true, // own process group, so killShell() can reap grandchildren (`&` jobs), not just bash
|
|
47
48
|
});
|
|
49
|
+
ownChild(p, "shell session", { cmd: `${file} ${args.join(" ")}`, group: true }); // killed at exit, reaped if we crash (it is its own session: it would outlive us)
|
|
48
50
|
p.stdout.setEncoding("utf8");
|
|
49
51
|
p.stderr.setEncoding("utf8");
|
|
50
52
|
const onData = (d) => { this.buf += d; };
|
package/dist/ui/App.js
CHANGED
|
@@ -25,7 +25,7 @@ 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, queuedPreview = "", onInterrupt, onCycleMode, opMode, rcConnected = false, 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, rcActive = false, approval = null, onApprovalDecide, question = null, modelPicker = null, planExitPicker = null, artifactsPicker = null } = props;
|
|
29
29
|
useTerminalSize(); // subscribe so the inline pinned UI (status rule, composer, footer) reflows the instant the terminal resizes
|
|
30
30
|
const thinking = status === "thinking" || status === "streaming";
|
|
31
31
|
// A parallel batch (2+ live rows) gets its own per-call view instead of the single-line StepSpinner —
|
|
@@ -40,7 +40,7 @@ export function App(props) {
|
|
|
40
40
|
// be scrolled off. The Composer is `suspended` (keystrokes route to the decision, not the draft).
|
|
41
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 })] }));
|
|
42
42
|
// The pinned bottom band: status rule, composer, bottom rule, then the mode/cycle FOOTER below the rule.
|
|
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 ? "▮" : "▯"}
|
|
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" : rcActive ? "yellow" : "gray", bold: rcConnected || rcActive, dimColor: !rcConnected && !rcActive, children: `${rcConnected ? "▮ rc live" : rcActive ? "▮ rc on" : "▯ rc"} ` })] }))] }));
|
|
44
44
|
// Fullscreen (opt-in): a full-terminal-height column. The transcript fills a clipped, bottom-anchored
|
|
45
45
|
// region (non-Static tail) so the newest output sits just above a composer pinned to the very bottom —
|
|
46
46
|
// no dead space. Off by default: inline keeps the terminal's native scrollback (mouse-scroll + copy).
|
|
@@ -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
|
+
}
|