omni-notify-mcp 1.3.471 → 1.3.472

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.
@@ -1,59 +1,59 @@
1
- "use strict";
2
-
3
- const fs = require("fs");
4
- const path = require("path");
5
- const { spawn } = require("child_process");
6
-
7
- const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
-
9
- function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
- return [
11
- deploy,
12
- "--domain", domain,
13
- ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
- // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
- "--project-root", projectRoot ?? home,
16
- "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
- "--notify-dir", doorsDir,
18
- ];
19
- }
20
-
21
- function runDeploy({ node, args, cwd, env, onOutput }) {
22
- return new Promise((resolve, reject) => {
23
- const child = spawn(node, args, { windowsHide: true, cwd, env });
24
- child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
- child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
- child.on("error", reject);
27
- child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
- });
29
- }
30
-
31
- const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
-
33
- function writeRecord(file, record) {
34
- const staged = `${file}.${process.pid}.tmp`;
35
- fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
- try {
37
- fs.renameSync(staged, file);
38
- } catch (err) {
39
- fs.rmSync(staged, { force: true });
40
- throw err;
41
- }
42
- }
43
-
44
- async function runRecorded(recordFile, recordText) {
45
- const record = { ...JSON.parse(recordText), pid: process.pid };
46
- const log = recordFile.replace(/\.json$/, ".log");
47
- const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
- try {
49
- const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
- write({ endedAt: new Date().toISOString(), ...ended });
51
- } catch (err) {
52
- // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
- write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
- }
55
- }
56
-
57
- if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
-
59
- module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { spawn } = require("child_process");
6
+
7
+ const DOMAIN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i;
8
+
9
+ function deployArgs({ deploy, domain, preview, projectRoot, home, doorsDir }) {
10
+ return [
11
+ deploy,
12
+ "--domain", domain,
13
+ ...(preview ? ["--new-install", "--dry-run"] : ["--new-install"]),
14
+ // NULL-OK: field projectRoot is OPTIONAL and therefore it is ok to check for NULL
15
+ "--project-root", projectRoot ?? home,
16
+ "--security-dir", path.join(home, ".notify-mcp", "gateway", "security"),
17
+ "--notify-dir", doorsDir,
18
+ ];
19
+ }
20
+
21
+ function runDeploy({ node, args, cwd, env, onOutput }) {
22
+ return new Promise((resolve, reject) => {
23
+ const child = spawn(node, args, { windowsHide: true, cwd, env });
24
+ child.stdout.on("data", (chunk) => onOutput(String(chunk)));
25
+ child.stderr.on("data", (chunk) => onOutput(String(chunk)));
26
+ child.on("error", reject);
27
+ child.on("exit", (exitCode, signal) => resolve({ exitCode, signal }));
28
+ });
29
+ }
30
+
31
+ const PROMPT_ON_THE_PC = "The elevated helper is not running as this build's copy, so installing would raise one Windows administrator prompt on the PC itself, which only a person at the PC can accept. Run Set up public access from VS Code on the PC (or accept the prompt there); with the helper running, this button installs without a prompt. Preview needs no administrator.";
32
+
33
+ function writeRecord(file, record) {
34
+ const staged = `${file}.${process.pid}.tmp`;
35
+ fs.writeFileSync(staged, JSON.stringify(record, null, 2));
36
+ try {
37
+ fs.renameSync(staged, file);
38
+ } catch (err) {
39
+ fs.rmSync(staged, { force: true });
40
+ throw err;
41
+ }
42
+ }
43
+
44
+ async function runRecorded(recordFile, recordText) {
45
+ const record = { ...JSON.parse(recordText), pid: process.pid };
46
+ const log = recordFile.replace(/\.json$/, ".log");
47
+ const write = (fields) => writeRecord(recordFile, { ...record, ...fields });
48
+ try {
49
+ const ended = await runDeploy({ node: process.execPath, args: record.args, cwd: record.cwd, onOutput: (text) => fs.appendFileSync(log, text) });
50
+ write({ endedAt: new Date().toISOString(), ...ended });
51
+ } catch (err) {
52
+ // OWNER: the detached run's trigger root — a deploy that could not be launched is written into the run's record, which the page and the MCP tool read back.
53
+ write({ endedAt: new Date().toISOString(), exitCode: null, failure: `the deploy could not be launched: ${err.message}` });
54
+ }
55
+ }
56
+
57
+ if (require.main === module) void runRecorded(process.argv[2], process.argv[3]);
58
+
59
+ module.exports = { DOMAIN, deployArgs, runDeploy, runRecorded, writeRecord, PROMPT_ON_THE_PC };
package/dist/mcpHosts.cjs CHANGED
@@ -273,7 +273,22 @@ function createHostWriters(env) {
273
273
  return { path: claudePath, state: "scoped" };
274
274
  }
275
275
 
276
- const CODEX_WORKSPACE_HELPER = 'node -e "process.stdout.write(JSON.stringify({\\"x-bullseye-project\\":process.cwd()}))"';
276
+ // #215 — the ONE helper every Codex server entry on this machine resolves its workspace with: the folder the session's own
277
+ // process runs in. A literal header naming a single folder — what the Codex app wrote into this file for each of these
278
+ // servers — answers every session about that ONE folder whichever workspace it runs in, so the pinned header is removed
279
+ // from every entry here and the helper is written from this one function.
280
+ const codexWorkspaceHelper = (header) => `node -e "process.stdout.write(JSON.stringify({\\"${header}\\":process.cwd()}))"`;
281
+ const CODEX_WORKSPACE_SERVERS = [
282
+ { server: "bn", header: "x-bullseye-project" },
283
+ { server: "bullseye-backlog", header: "x-bullseye-project" },
284
+ { server: "deepagent", header: "x-deepagent-project" },
285
+ ];
286
+
287
+ // GATE: how deep a `notify` array's closing bracket may sit below its own key before this file leaves it entirely alone — Codex's own writer keeps it on one line, and a file this deep is one we do not understand.
288
+ const NOTIFY_ARRAY_LINES = 8;
289
+ // The Codex app's own home is an MSIX package under this folder, whose FILES Windows does not let this process tell from files
290
+ // that are gone — a live `AppxManifest.xml` there answers ENOENT. The PACKAGE FOLDER itself answers honestly.
291
+ const WINDOWS_APPS_FOLDER = "windowsapps";
277
292
 
278
293
  function setTomlKey(lines, start, end, key, value) {
279
294
  const at = lines.findIndex((l, i) => i > start && i < end && new RegExp(`^\\s*"?${key.replace(/[-]/g, "\\-")}"?\\s*=`).test(l));
@@ -295,13 +310,116 @@ function createHostWriters(env) {
295
310
  function tomlTable(lines, header) {
296
311
  const headers = tomlHeaders(lines);
297
312
  const own = headers.filter((h) => h.path === header);
298
- if (own.length > 1) throw new Error(`~/.codex/config.toml declares [${header}] ${own.length} times, so it is not valid TOML — the bn entry was NOT written; fix that file and reload the window`);
313
+ if (own.length > 1) throw new Error(`~/.codex/config.toml declares [${header}] ${own.length} times, so it is not valid TOML — nothing was written to it; fix that file and reload the window`);
299
314
  // NULL-OK: field mcp_servers.bn table is OPTIONAL and therefore it is ok to check for NULL
300
315
  if (own.length === 0) return undefined;
301
316
  const next = headers.find((h) => h.index > own[0].index);
302
317
  return { start: own[0].index, end: next === undefined ? lines.length : next.index };
303
318
  }
304
319
 
320
+ /**
321
+ * One Codex server's own table given the shared helper and no single pinned folder, in place. A server this file does not
322
+ * declare is left undeclared — `bullseye-backlog` and `deepagent` are registered by Codex and DeepAgent, never by this
323
+ * extension — and only bn's headers table is ever created, because only bn's entry is this extension's to write.
324
+ */
325
+ function scopeCodexServerToSessionFolder(lines, { server, header }) {
326
+ let own = tomlTable(lines, `mcp_servers.${server}`);
327
+ if (own === undefined) return;
328
+ // An inline headers table is not ours to rewrite: bn's own is replaced whole (its bearer goes straight back), but splicing a
329
+ // line out of another app's entry would delete a header of theirs — a bearer included — with nothing put in its place, so a
330
+ // server that carries one inline is left exactly as its own writer wrote it.
331
+ const inline = lines.findIndex((l, i) => i > own.start && i < own.end && /^\s*http_headers\s*=/.test(l));
332
+ if (inline >= 0 && server !== "bn") return;
333
+ if (inline >= 0) lines.splice(inline, 1);
334
+ own = tomlTable(lines, `mcp_servers.${server}`);
335
+ setTomlKey(lines, own.start, own.end, "http_headers_helper", `'${codexWorkspaceHelper(header)}'`);
336
+ let headers = tomlTable(lines, `mcp_servers.${server}.http_headers`);
337
+ if (headers === undefined && server === "bn") {
338
+ own = tomlTable(lines, `mcp_servers.${server}`);
339
+ lines.splice(own.end, 0, ...(lines[own.end - 1] === "" ? [] : [""]), `[mcp_servers.${server}.http_headers]`, ...(own.end < lines.length ? [""] : []));
340
+ headers = tomlTable(lines, `mcp_servers.${server}.http_headers`);
341
+ }
342
+ if (headers === undefined) return;
343
+ const pinned = lines.findIndex((l, i) => i > headers.start && i < headers.end && new RegExp(`^\\s*"?${header}"?\\s*=`).test(l));
344
+ if (pinned >= 0) lines.splice(pinned, 1);
345
+ // A headers table whose only key WAS the pinned folder, with nothing else written in it, holds nothing of anybody's: it goes
346
+ // with the key it carried. A comment left in it is somebody's words about that table, so the table stays and keeps them.
347
+ const left = tomlTable(lines, `mcp_servers.${server}.http_headers`);
348
+ if (left !== undefined && lines.slice(left.start + 1, left.end).every((l) => l.trim() === "")) {
349
+ const from = lines[left.start - 1] === "" ? left.start - 1 : left.start;
350
+ lines.splice(from, left.start - from + 1);
351
+ }
352
+ }
353
+
354
+ /** Every server of {@link CODEX_WORKSPACE_SERVERS} in this file, each resolving its workspace from the session's own folder. */
355
+ function withCodexWorkspaceHelpers(text) {
356
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
357
+ const lines = text.split(/\r?\n/);
358
+ while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
359
+ for (const server of CODEX_WORKSPACE_SERVERS) scopeCodexServerToSessionFolder(lines, server);
360
+ return `${lines.join(eol)}${eol}`;
361
+ }
362
+
363
+ /**
364
+ * Where the file's TOP-LEVEL `notify` array starts, or -1. Anything that opens a table or a multi-line string before it — and
365
+ * therefore any `notify` that follows one — is somebody else's text and is never touched, so a `[desktop]` header, a `"""`
366
+ * block, and even a `'''` hiding inside a basic string all stop this file short of the key.
367
+ */
368
+ function topLevelNotifyAt(lines) {
369
+ for (let index = 0; index < lines.length; index++) {
370
+ if (/^notify\s*=\s*\[/.test(lines[index])) return index;
371
+ if (/^\s*\[/.test(lines[index]) || /"""|'''/.test(lines[index])) return -1;
372
+ }
373
+ return -1;
374
+ }
375
+
376
+ /**
377
+ * Whether the program a `notify` array names is provably gone: the MSIX package folder its own path runs through is no
378
+ * longer there. A program outside such a folder is never removed — this process cannot tell a file it is not allowed to read
379
+ * from a file that is not there, and deleting a working hook would be worse than leaving a dead one.
380
+ */
381
+ function gonePackageFolder(program) {
382
+ const parts = program.split(/[\\/]+/);
383
+ const at = parts.findIndex((part, index) => index > 0 && part.toLowerCase() === WINDOWS_APPS_FOLDER);
384
+ if (at < 0 || at + 1 >= parts.length) return false;
385
+ try {
386
+ fs.statSync(parts.slice(0, at + 2).join("\\"));
387
+ } catch (err) {
388
+ return err.code === "ENOENT";
389
+ }
390
+ return false;
391
+ }
392
+
393
+ /**
394
+ * #215 — a `notify` program this file names but this machine no longer has: Codex runs it on EVERY turn end, so a dead one
395
+ * writes `codex_core::hook_runtime: after_agent hook failed; ... hook_name=legacy_notify error=The system cannot find the
396
+ * path specified. (os error 3)` into Codex.log for the life of the install. The Codex app ships as an MSIX package, and its
397
+ * files answer ENOENT whether they are there or not — which is why only {@link gonePackageFolder} decides here. A bare name
398
+ * Codex resolves on its own PATH, a first element that is not a plain quoted path, and a working program are left as they are.
399
+ */
400
+ function withoutDeadNotify(text) {
401
+ const lines = text.split(/\r?\n/);
402
+ const at = topLevelNotifyAt(lines);
403
+ if (at < 0) return text;
404
+ let end = at;
405
+ while (end < lines.length && end - at <= NOTIFY_ARRAY_LINES && !/\]/.test(lines[end])) end++;
406
+ if (end >= lines.length || end - at > NOTIFY_ARRAY_LINES) return text;
407
+ const array = /^notify\s*=\s*\[([\s\S]*)\]/.exec(lines.slice(at, end + 1).join("\n"));
408
+ if (array === null) return text;
409
+ // The program is the array's OWN first element and a plain quoted string — `["python3", …]` is Codex's own documented shape
410
+ // too, but that name is resolved on Codex's PATH and never here, so only an absolute path can be judged at all.
411
+ const first = /^\s*(['"])((?:\\[\s\S]|(?!\1)[\s\S])*)\1\s*(?:,|\])/.exec(array[1]);
412
+ if (first === null) return text;
413
+ // A TOML basic string escapes its own backslashes and a literal string escapes nothing; a mis-read path would be a program
414
+ // this file only THINKS is missing.
415
+ const program = first[1] === '"' ? first[2].replace(/\\(["\\])/g, "$1") : first[2];
416
+ if (!/^[A-Za-z]:[\\/]/.test(program) || !gonePackageFolder(program)) return text;
417
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
418
+ const kept = lines.filter((_, i) => i < at || i > end);
419
+ while (kept.length > 0 && kept[kept.length - 1] === "") kept.pop();
420
+ return `${kept.join(eol)}${eol}`;
421
+ }
422
+
305
423
  function withCodexGatewayEntry(text, url, token) {
306
424
  const eol = text.includes("\r\n") ? "\r\n" : "\n";
307
425
  const lines = text.split(/\r?\n/);
@@ -315,29 +433,31 @@ function createHostWriters(env) {
315
433
  if (inline >= 0) lines.splice(inline, 1);
316
434
  own = tomlTable(lines, "mcp_servers.bn");
317
435
  setTomlKey(lines, own.start, own.end, "url", JSON.stringify(url));
318
- own = tomlTable(lines, "mcp_servers.bn");
319
- setTomlKey(lines, own.start, own.end, "http_headers_helper", `'${CODEX_WORKSPACE_HELPER}'`);
320
436
  let headers = tomlTable(lines, "mcp_servers.bn.http_headers");
321
437
  if (headers === undefined) {
322
438
  own = tomlTable(lines, "mcp_servers.bn");
323
439
  lines.splice(own.end, 0, ...(lines[own.end - 1] === "" ? [] : [""]), "[mcp_servers.bn.http_headers]", ...(own.end < lines.length ? [""] : []));
324
440
  headers = tomlTable(lines, "mcp_servers.bn.http_headers");
325
441
  }
326
- const fixed = lines.findIndex((l, i) => i > headers.start && i < headers.end && /^\s*"?x-bullseye-project"?\s*=/.test(l));
327
- if (fixed >= 0) lines.splice(fixed, 1);
328
442
  headers = tomlTable(lines, "mcp_servers.bn.http_headers");
329
443
  setTomlKey(lines, headers.start, headers.end, "Authorization", JSON.stringify(`Bearer ${token}`));
330
- return `${lines.join(eol)}${eol}`;
444
+ return withCodexWorkspaceHelpers(`${lines.join(eol)}${eol}`);
331
445
  }
332
446
 
447
+ /**
448
+ * Every repair this machine's Codex config needs from us, whether or not a gateway door is configured here: the servers that
449
+ * name their workspace by the session's own folder, and a `notify` program this box no longer has. With a gateway token the
450
+ * bn door is written as well; without one the repairs alone are written, because neither depends on the token.
451
+ */
333
452
  function configureCodexScopedGateway() {
334
453
  const codexPath = path.join(env.home(), ".codex", "config.toml");
335
454
  const read = contentOf(codexPath);
455
+ if (!fs.existsSync(codexPath)) return { path: codexPath, state: "untouched" };
336
456
  const gateway = env.gateway() || {};
337
- if (typeof gateway.token !== "string" || gateway.token.length === 0 || !fs.existsSync(codexPath)) return { path: codexPath, state: "untouched" };
338
457
  const url = `http://127.0.0.1:${typeof gateway.port === "number" ? gateway.port : 7470}/mcp`;
458
+ const token = typeof gateway.token === "string" ? gateway.token : "";
339
459
  const raw = fs.readFileSync(codexPath, "utf8");
340
- const next = withCodexGatewayEntry(raw, url, gateway.token);
460
+ const next = withoutDeadNotify(token.length === 0 ? withCodexWorkspaceHelpers(raw) : withCodexGatewayEntry(raw, url, token));
341
461
  if (next === raw) return { path: codexPath, state: "configured" };
342
462
  atomicWrite(codexPath, next, read);
343
463
  return { path: codexPath, state: "scoped" };
@@ -9,6 +9,7 @@ import * as path from "node:path";
9
9
  import { createInterface } from "node:readline";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import { Duplex } from "node:stream";
12
+ import { Worker } from "node:worker_threads";
12
13
  import { CLUSTER_OWNER, OwnershipUnreadable, startOwnerOf } from "./providerOwnership.js";
13
14
  import { AutoStartUnread, autoStartOnAt, sameRoot, savedAutoStart, workspacesHere } from "./workspaceList.js";
14
15
  export function isProcessAlive(pid) {
@@ -1831,13 +1832,52 @@ export class ProcessTableUnreadable extends Error {
1831
1832
  function throwProcessRead() {
1832
1833
  throw new ProcessTableUnreadable("the process table could not be read");
1833
1834
  }
1835
+ function serveTableReader() {
1836
+ const { parentPort: port, workerData: launch } = require("node:worker_threads");
1837
+ const { spawn } = require("node:child_process");
1838
+ // GATE: the worker claims state 0 before spawning; a stop that has already changed it closes the port without starting a child.
1839
+ if (Atomics.compareExchange(launch.launchState, 0, 0, 1) !== 0) {
1840
+ port.close();
1841
+ return;
1842
+ }
1843
+ const child = spawn(launch.file, [...launch.args], {
1844
+ cwd: launch.cwd,
1845
+ env: launch.env ?? process.env,
1846
+ windowsHide: true,
1847
+ stdio: ["pipe", "pipe", "ignore"],
1848
+ });
1849
+ const send = (reply) => port.postMessage(reply);
1850
+ const fail = (error) => {
1851
+ send({ error });
1852
+ port.close();
1853
+ };
1854
+ let output = "";
1855
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
1856
+ output += chunk;
1857
+ const end = output.indexOf(launch.end);
1858
+ if (end !== -1) {
1859
+ send({ output: output.slice(0, end) });
1860
+ output = "";
1861
+ }
1862
+ });
1863
+ child.once("exit", (code, signal) => fail(`the process table reader exited before it answered (${signal ?? `exit code ${code}`})`));
1864
+ child.once("error", (err) => fail(`the process table reader could not be started — ${err.message}`));
1865
+ child.stdin.on("error", (err) => fail(`the request could not be written to the process table reader — ${err.message}`));
1866
+ port.on("message", (request) => {
1867
+ if (request === null)
1868
+ port.close();
1869
+ else
1870
+ child.stdin.write(`${request}\n`);
1871
+ });
1872
+ port.once("close", () => { child.kill(); });
1873
+ }
1834
1874
  /** #14288 — the Windows table reader, bound to the process it serves: it ends the moment that process is gone, whoever still holds its input. */
1835
1875
  export function windowsTableLaunch(ownerPid) {
1836
1876
  return { file: "powershell", args: ["-NoProfile", "-NonInteractive", "-Command", "Invoke-Expression $env:AGENT_SESSION_WINDOWS_TABLE"], env: { ...process.env, AGENT_SESSION_WINDOWS_TABLE: windowsTableScript(ownerPid) } };
1837
1877
  }
1838
1878
  export class TableReader {
1839
1879
  launch;
1840
- child;
1880
+ reader;
1841
1881
  queue = Promise.resolve();
1842
1882
  phase = "open";
1843
1883
  bound;
@@ -1847,9 +1887,9 @@ export class TableReader {
1847
1887
  }
1848
1888
  close() {
1849
1889
  this.phase = "closed";
1850
- // NULL-OK: field child is OPTIONAL and therefore it is ok to check for NULL
1851
- if (this.child !== undefined) {
1852
- this.stop(this.child);
1890
+ // NULL-OK: field reader is OPTIONAL and therefore it is ok to check for NULL
1891
+ if (this.reader !== undefined) {
1892
+ this.stop(this.reader);
1853
1893
  }
1854
1894
  }
1855
1895
  read(request) {
@@ -1880,82 +1920,65 @@ export class TableReader {
1880
1920
  if (this.phase === "closed") {
1881
1921
  return Promise.reject(new ProcessTableUnreadable("the process table reader was closed with the build that owned it"));
1882
1922
  }
1883
- const child = this.child ?? await this.start();
1923
+ const reader = this.reader ?? await this.start();
1924
+ const { worker } = reader;
1884
1925
  return new Promise((resolve, reject) => {
1885
- let out = "";
1886
1926
  const settle = () => {
1887
1927
  clearTimeout(hung);
1888
- child.stdout.off("data", onData);
1889
- child.off("exit", onExit);
1890
- child.off("error", onSpawnError);
1891
- child.stdin.off("error", onPipeError);
1928
+ worker.off("message", onReply);
1929
+ worker.off("exit", onExit);
1930
+ worker.off("error", onWorkerError);
1892
1931
  };
1893
- const onData = (chunk) => {
1894
- out += chunk;
1895
- const end = out.indexOf(TABLE_END);
1896
- if (end !== -1) {
1897
- settle();
1898
- resolve(out.slice(0, end));
1899
- }
1900
- };
1901
- const onExit = (code, signal) => {
1902
- settle();
1903
- reject(new ProcessTableUnreadable(`the process table reader exited before it answered (${signal ?? `exit code ${code}`})`));
1904
- };
1905
- const onSpawnError = (err) => {
1932
+ const failed = (error) => {
1906
1933
  settle();
1907
- this.stop(child);
1908
- reject(new ProcessTableUnreadable(`the process table reader could not be started — ${err.message}`));
1934
+ this.stop(reader);
1935
+ reject(new ProcessTableUnreadable(error));
1909
1936
  };
1910
- const onPipeError = (err) => {
1911
- settle();
1912
- this.stop(child);
1913
- reject(new ProcessTableUnreadable(`the request could not be written to the process table reader — ${err.message}`));
1937
+ const onReply = (reply) => {
1938
+ if ("error" in reply) {
1939
+ failed(reply.error);
1940
+ }
1941
+ else {
1942
+ settle();
1943
+ resolve(reply.output);
1944
+ }
1914
1945
  };
1946
+ const onExit = (code) => failed(`the process table reader worker exited before it answered (exit code ${code})`);
1947
+ const onWorkerError = (err) => failed(`the process table reader worker failed — ${err.message}`);
1915
1948
  const hung = setTimeout(() => {
1916
- settle();
1917
- this.stop(child);
1918
- reject(new ProcessTableUnreadable(`the process table reader owed one answer for ${(this.bound * READER_HUNG_BOUNDS) / 1000} s and was stopped as hung`));
1949
+ failed(`the process table reader owed one answer for ${(this.bound * READER_HUNG_BOUNDS) / 1000} s and was stopped as hung`);
1919
1950
  }, this.bound * READER_HUNG_BOUNDS);
1920
- child.stdout.on("data", onData);
1921
- child.once("exit", onExit);
1922
- child.once("error", onSpawnError);
1923
- child.stdin.once("error", onPipeError);
1924
- child.stdin.write(`${request}\n`);
1951
+ worker.once("message", onReply).once("exit", onExit).once("error", onWorkerError);
1952
+ worker.unref();
1953
+ worker.postMessage(request);
1925
1954
  });
1926
1955
  }
1927
1956
  async start() {
1928
- const { file, args, env } = await this.launch();
1957
+ const launch = await this.launch();
1929
1958
  if (this.phase === "closed") {
1930
1959
  throw new ProcessTableUnreadable("the process table reader was closed while its launch was being resolved");
1931
1960
  }
1932
- const child = spawn(file, [...args], {
1933
- cwd: tmpdir(),
1934
- env: env ?? process.env,
1935
- windowsHide: true,
1936
- stdio: ["pipe", "pipe", "ignore"],
1937
- });
1938
- child.stdout.setEncoding("utf8");
1961
+ const launchState = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
1962
+ const workerData = { ...launch, cwd: tmpdir(), end: TABLE_END, launchState };
1963
+ const worker = new Worker(`(${serveTableReader.toString()})()`, { eval: true, workerData });
1964
+ const reader = { worker, launchState };
1939
1965
  const forget = () => {
1940
- if (this.child === child) {
1941
- this.child = undefined;
1966
+ if (this.reader === reader) {
1967
+ this.reader = undefined;
1942
1968
  }
1943
1969
  };
1944
1970
  // OWNER: a reader that ended or broke between reads answers nothing more — it is dropped, and the next read starts a fresh one.
1945
- child.on("exit", forget).on("error", forget);
1946
- // OWNER: a pipe broken under an idle reader is the same ended reader — dropped, and the next read starts a fresh one.
1947
- child.stdin.on("error", forget);
1948
- child.unref();
1949
- child.stdin.unref();
1950
- child.stdout.unref();
1951
- this.child = child;
1952
- return child;
1971
+ worker.once("exit", forget).once("error", forget);
1972
+ worker.unref();
1973
+ this.reader = reader;
1974
+ return reader;
1953
1975
  }
1954
- stop(child) {
1955
- if (this.child === child) {
1956
- this.child = undefined;
1976
+ stop(reader) {
1977
+ if (this.reader === reader) {
1978
+ this.reader = undefined;
1979
+ Atomics.store(reader.launchState, 0, 2);
1980
+ reader.worker.postMessage(null);
1957
1981
  }
1958
- child.kill();
1959
1982
  }
1960
1983
  }
1961
1984
  /** #3934 — whether this OS lets FleetView count the CPU of a process that ended between two readings: Windows, through each lane's kernel job; elsewhere a process is counted only while a reading sees it. */
@@ -663,8 +663,14 @@ function unreadRooms(reason) {
663
663
  /**
664
664
  * THE one pick of an agent CLI when the caller named none: of `order` the ones `startable` can run, a provider with room
665
665
  * first. An automatic conversation can draw on keys only when the eligible subscriptions are spent and DeepAgent's fallback is enabled for a compatible funded key.
666
+ *
667
+ * 🔴 #14742 — MENI'S OWN RULING IS A THIRD WAY ONTO A KEY, and the caller that owns the story's priority and board says so
668
+ * with `permittedFundedKey`: he ruled 2026-11-28 that a funded API key may start a P0 money-path story while his Claude
669
+ * subscription is at its weekly limit. It stands in for "every eligible subscription is spent" and nothing else — a
670
+ * subscription with room still wins, DeepAgent's fallback box must still be on for that provider, and the key must still
671
+ * have usable funds, so the allowance can only ever reach a key that was already permitted and funded.
666
672
  * @param {readonly string[]} order @param {ProviderRooms} rooms @param {readonly string[]} startable
667
- * @param {{ home: string, usesKey: (provider: string) => boolean, confirmedRoom?: boolean }} [billing]
673
+ * @param {{ home: string, usesKey: (provider: string) => boolean, confirmedRoom?: boolean, permittedFundedKey?: boolean }} [billing]
668
674
  * @returns {string | undefined}
669
675
  */
670
676
  function autoProvider(order, rooms, startable, billing) {
@@ -674,7 +680,7 @@ function autoProvider(order, rooms, startable, billing) {
674
680
  const paid = candidates.filter((p) => !metered.has(p));
675
681
  const withRoom = paid.filter((p) => rooms[p]?.state === "room");
676
682
  const unread = paid.filter((p) => rooms[p]?.state !== "room" && rooms[p]?.state !== "out");
677
- const allSpent = candidates.every((p) => metered.has(p) && runsOnKeys(p) || rooms[p]?.state === "out");
683
+ const allSpent = billing.permittedFundedKey === true || candidates.every((p) => metered.has(p) && runsOnKeys(p) || rooms[p]?.state === "out");
678
684
  const allowedKey = (p) => metered.has(p) && readByokFallback(billing.home, AGENT_CLIS.find((cli) => cli.id === p).subscriptionProvider) && rooms[p]?.keys?.some((k) => k.funds === "usable");
679
685
  candidates = withRoom.length > 0 ? withRoom : unread.length > 0 && !billing.confirmedRoom ? unread : allSpent ? candidates.filter(allowedKey) : [];
680
686
  if (billing.confirmedRoom)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.471",
3
+ "version": "1.3.472",
4
4
  "homepage": "https://www.npmjs.com/package/omni-notify-mcp",
5
5
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
6
6
  "main": "dist/daemon.js",
@@ -1,665 +0,0 @@
1
- // OWNER-BOUND JOB (#1968, #1983): the ONE source of the kill-on-close Job Object that ends a process tree
2
- // with its owner. Loaded by ownerGuard.ps1 through Add-Type and called as OwnerJob.Run(...) for FleetView's
3
- // own launches.
4
- //
5
- // #2925: it is NO LONGER compiled into ~/.bullseye/bin/ownerGuard.exe for `claudeCode.claudeProcessWrapper`.
6
- // That build ran the .NET Framework's csc.exe at every activation, which made a compiler a dependency of a
7
- // marketplace install; the wrapper is now POSIX-only (media/shared/claudeWrapper.sh, a shell script that needs
8
- // nothing but /bin/sh) and Windows installs none. Nothing in this file may be re-wired into that setting.
9
- // Language level is C# 5 (the csc.exe that ships with Windows).
10
- //
11
- // THE MECHANISM: the target is created SUSPENDED, assigned to a job carrying KILL_ON_JOB_CLOSE, and only then
12
- // resumed, so no child can be born outside the job. The guard waits on the owner and the target and, when
13
- // EITHER ends, terminates the job. BREAKAWAY_OK is set on purpose and SILENT_BREAKAWAY is not: a process that
14
- // asks for CREATE_BREAKAWAY_FROM_JOB may leave, but nothing leaves by accident - except under `contain`, which leaves
15
- // BREAKAWAY_OK off because the msys2 runtime asks to break away from every job that allows it (spawn.cc), so a
16
- // Git Bash tree would otherwise leave the job whole. A child that asks then stays (Microsoft, "Nested Jobs").
17
- //
18
- // usage (wrapper mode, owner = the parent process, which is the extension host): ownerGuard.exe <exe> [args...]
19
- // (explicit owner): ownerGuard.exe --owner <pid> <exe> [args...]
20
- using System;
21
- using System.Collections.Generic;
22
- using System.IO;
23
- using System.Runtime.InteropServices;
24
- using System.Text;
25
- using System.Text.RegularExpressions;
26
- using System.Threading;
27
-
28
- public static class OwnerJob
29
- {
30
- const uint KILL_ON_JOB_CLOSE = 0x2000;
31
- const uint BREAKAWAY_OK = 0x800;
32
- const int EXTENDED_LIMIT_INFORMATION = 9;
33
- const uint CREATE_SUSPENDED = 0x00000004;
34
- const int STARTF_USESTDHANDLES = 0x00000100;
35
- const uint SYNCHRONIZE = 0x00100000;
36
- const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
37
- const uint INFINITE = 0xFFFFFFFF;
38
-
39
- public const int EXIT_NO_TARGET = 90;
40
- public const int EXIT_NO_JOB = 91;
41
- public const int EXIT_NO_LIMIT = 92;
42
- public const int EXIT_NOT_CREATED = 93;
43
- public const int EXIT_NOT_ASSIGNED = 94;
44
- public const int EXIT_OWNER_GONE = 95;
45
- public const int EXIT_NOT_FOUND = 96;
46
- public const int EXIT_BATCH_LINE_BREAK = 97;
47
- public const int EXIT_NOT_RESUMED = 98;
48
- public const int EXIT_WAIT_FAILED = 99;
49
- public const int EXIT_NO_EXIT_CODE = 100;
50
- public const int EXIT_DEADLINE = 101;
51
- public const int EXIT_ALREADY_RUNNING = 102;
52
- public const int FRAME_OWNERS = -1;
53
- const uint WAIT_TIMEOUT = 0x102;
54
- const uint STILL_ACTIVE = 259;
55
- const int ERROR_INVALID_PARAMETER = 87;
56
-
57
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
58
- struct STARTUPINFO
59
- {
60
- public int cb;
61
- public string lpReserved;
62
- public string lpDesktop;
63
- public string lpTitle;
64
- public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
65
- public short wShowWindow, cbReserved2;
66
- public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
67
- }
68
-
69
- [StructLayout(LayoutKind.Sequential)]
70
- struct PROCESS_INFORMATION
71
- {
72
- public IntPtr hProcess, hThread;
73
- public int dwProcessId, dwThreadId;
74
- }
75
-
76
- [StructLayout(LayoutKind.Sequential)]
77
- struct IO_COUNTERS
78
- {
79
- public ulong a, b, c, d, e, f;
80
- }
81
-
82
- [StructLayout(LayoutKind.Sequential)]
83
- struct JOBOBJECT_BASIC_LIMIT_INFORMATION
84
- {
85
- public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
86
- public uint LimitFlags;
87
- public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
88
- public uint ActiveProcessLimit;
89
- public UIntPtr Affinity;
90
- public uint PriorityClass, SchedulingClass;
91
- }
92
-
93
- [StructLayout(LayoutKind.Sequential)]
94
- struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
95
- {
96
- public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
97
- public IO_COUNTERS IoInfo;
98
- public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
99
- }
100
-
101
- [StructLayout(LayoutKind.Sequential)]
102
- struct PROCESS_BASIC_INFORMATION
103
- {
104
- public IntPtr ExitStatus, PebBaseAddress, AffinityMask, BasePriority, UniqueProcessId, InheritedFromUniqueProcessId;
105
- }
106
-
107
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
108
- static extern IntPtr CreateJobObject(IntPtr attributes, string name);
109
- [DllImport("kernel32.dll", SetLastError = true)]
110
- static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length);
111
- [DllImport("kernel32.dll", SetLastError = true)]
112
- static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
113
- [DllImport("kernel32.dll", SetLastError = true)]
114
- static extern bool TerminateJobObject(IntPtr job, uint exitCode);
115
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
116
- static extern bool CreateProcess(string application, string commandLine, IntPtr processAttributes, IntPtr threadAttributes,
117
- bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo,
118
- out PROCESS_INFORMATION processInformation);
119
- [DllImport("kernel32.dll", SetLastError = true)]
120
- static extern IntPtr GetStdHandle(int which);
121
- [DllImport("kernel32.dll", SetLastError = true)]
122
- static extern bool CloseHandle(IntPtr handle);
123
- [DllImport("kernel32.dll", SetLastError = true)]
124
- static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool waitAll, uint milliseconds);
125
- [DllImport("kernel32.dll", SetLastError = true)]
126
- static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
127
- [DllImport("kernel32.dll", SetLastError = true)]
128
- static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
129
- [DllImport("kernel32.dll", SetLastError = true)]
130
- static extern uint ResumeThread(IntPtr thread);
131
- [DllImport("kernel32.dll")]
132
- static extern IntPtr GetCurrentProcess();
133
- [DllImport("kernel32.dll")]
134
- static extern int GetCurrentProcessId();
135
- [DllImport("kernel32.dll", SetLastError = true)]
136
- static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
137
- [DllImport("ntdll.dll")]
138
- static extern int NtQueryInformationProcess(IntPtr process, int infoClass, ref PROCESS_BASIC_INFORMATION info, int length, out int returned);
139
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
140
- static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder name, ref int size);
141
-
142
- // One argument as CommandLineToArgvW reads it back: quoted only when it must be, a quote escaped by
143
- // backslashes per the Windows rules, so a path with spaces stays ONE argument.
144
- public static string QuoteArg(string arg)
145
- {
146
- if (arg.Length > 0 && arg.IndexOfAny(new char[] { ' ', '\t', '\n', '\v', '"' }) < 0)
147
- {
148
- return arg;
149
- }
150
- StringBuilder sb = new StringBuilder("\"");
151
- int slashes = 0;
152
- foreach (char ch in arg)
153
- {
154
- if (ch == '\\') { slashes++; continue; }
155
- if (ch == '"') { sb.Append('\\', 2 * slashes + 1); sb.Append('"'); }
156
- else { sb.Append('\\', slashes); sb.Append(ch); }
157
- slashes = 0;
158
- }
159
- sb.Append('\\', 2 * slashes);
160
- sb.Append('"');
161
- return sb.ToString();
162
- }
163
-
164
- // cmd.exe reads its command line by rules of its own: every character it treats as special, the quote and the
165
- // space included, is escaped with a caret so the whole argument is literal text to it.
166
- static string EscapeCmd(string text)
167
- {
168
- return Regex.Replace(text, "([()\\]\\[%!^\"`<>&|;, *?])", "^$1");
169
- }
170
-
171
- static int ParentOf(IntPtr process)
172
- {
173
- PROCESS_BASIC_INFORMATION info = new PROCESS_BASIC_INFORMATION();
174
- int returned;
175
- if (NtQueryInformationProcess(process, 0, ref info, Marshal.SizeOf(info), out returned) != 0)
176
- {
177
- return 0;
178
- }
179
- return (int)info.InheritedFromUniqueProcessId.ToInt64();
180
- }
181
-
182
- static int ParentPid()
183
- {
184
- return ParentOf(GetCurrentProcess());
185
- }
186
-
187
- static long StartOf(IntPtr process, int pid)
188
- {
189
- long start, ignored;
190
- if (!GetProcessTimes(process, out start, out ignored, out ignored, out ignored))
191
- {
192
- throw new InvalidOperationException("the start time of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
193
- }
194
- return start;
195
- }
196
-
197
- // A pid names an ancestor only if that process STARTED BEFORE the younger one: a recycled pid belongs to a
198
- // younger process, and then the real ancestor is already dead.
199
- static IntPtr OpenGone(int pid, uint access)
200
- {
201
- IntPtr process = OpenProcess(access, false, pid);
202
- if (process == IntPtr.Zero)
203
- {
204
- int why = Marshal.GetLastWin32Error();
205
- if (why != ERROR_INVALID_PARAMETER)
206
- {
207
- throw new InvalidOperationException("process " + pid + " could not be opened (win32 " + why + ")");
208
- }
209
- }
210
- return process;
211
- }
212
-
213
- static IntPtr OpenOlderThan(int pid, IntPtr younger, int youngerPid)
214
- {
215
- IntPtr process = OpenGone(pid, SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION);
216
- if (process == IntPtr.Zero)
217
- {
218
- return process;
219
- }
220
- if (StartOf(process, pid) > StartOf(younger, youngerPid))
221
- {
222
- CloseHandle(process);
223
- return IntPtr.Zero;
224
- }
225
- return process;
226
- }
227
-
228
- static IntPtr OpenOwner(int ownerPid, bool mustPredateSelf)
229
- {
230
- return mustPredateSelf
231
- ? OpenOlderThan(ownerPid, GetCurrentProcess(), GetCurrentProcessId())
232
- : OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, ownerPid);
233
- }
234
-
235
- static string ImageOf(IntPtr process, int pid)
236
- {
237
- StringBuilder name = new StringBuilder(1024);
238
- int size = name.Capacity;
239
- if (!QueryFullProcessImageName(process, 0, name, ref size))
240
- {
241
- throw new InvalidOperationException("the image of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
242
- }
243
- return name.ToString(0, size);
244
- }
245
-
246
- static List<IntPtr> ShellFrame()
247
- {
248
- List<IntPtr> frame = new List<IntPtr>();
249
- IntPtr child = GetCurrentProcess();
250
- int childPid = GetCurrentProcessId();
251
- while (true)
252
- {
253
- int parentPid = ParentOf(child);
254
- if (parentPid == 0)
255
- {
256
- throw new InvalidOperationException("the parent of process " + childPid + " could not be read");
257
- }
258
- IntPtr parent = OpenOlderThan(parentPid, child, childPid);
259
- if (parent == IntPtr.Zero)
260
- {
261
- return frame;
262
- }
263
- frame.Add(parent);
264
- string image = Path.GetFileName(ImageOf(parent, parentPid)).ToLowerInvariant();
265
- if (image != "bash.exe" && image != "sh.exe")
266
- {
267
- return frame;
268
- }
269
- child = parent;
270
- childPid = parentPid;
271
- }
272
- }
273
-
274
- static string ReadLock(string path)
275
- {
276
- try
277
- {
278
- using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)))
279
- {
280
- return reader.ReadToEnd().Trim();
281
- }
282
- }
283
- catch (FileNotFoundException)
284
- {
285
- return null;
286
- }
287
- }
288
-
289
- static bool StillHolds(int pid, long start)
290
- {
291
- IntPtr process = OpenGone(pid, PROCESS_QUERY_LIMITED_INFORMATION);
292
- if (process == IntPtr.Zero)
293
- {
294
- return false;
295
- }
296
- uint code;
297
- bool alive = StartOf(process, pid) == start && GetExitCodeProcess(process, out code) && code == STILL_ACTIVE;
298
- CloseHandle(process);
299
- return alive;
300
- }
301
-
302
- static bool ParseLock(string held, out int pid, out long start)
303
- {
304
- string[] parts = held.Split(' ');
305
- start = 0;
306
- pid = 0;
307
- return parts.Length == 2 && int.TryParse(parts[0], out pid) && long.TryParse(parts[1], out start);
308
- }
309
-
310
- static int TakeLock(string path, out string mine)
311
- {
312
- mine = GetCurrentProcessId() + " " + StartOf(GetCurrentProcess(), GetCurrentProcessId());
313
- for (int attempt = 0; attempt < 2; attempt++)
314
- {
315
- if (!File.Exists(path))
316
- {
317
- try
318
- {
319
- using (FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
320
- {
321
- byte[] bytes = Encoding.ASCII.GetBytes(mine);
322
- file.Write(bytes, 0, bytes.Length);
323
- }
324
- return 0;
325
- }
326
- catch (IOException)
327
- {
328
- if (!File.Exists(path))
329
- {
330
- throw;
331
- }
332
- }
333
- }
334
- string held = ReadLock(path);
335
- int pid;
336
- long start;
337
- if (held != null && !ParseLock(held, out pid, out start))
338
- {
339
- Thread.Sleep(1000);
340
- held = ReadLock(path);
341
- }
342
- if (held == null)
343
- {
344
- continue;
345
- }
346
- bool parsed = ParseLock(held, out pid, out start);
347
- if (parsed && StillHolds(pid, start))
348
- {
349
- Say("REFUSED - an earlier run (pid " + pid + ", started " + DateTime.FromFileTime(start).ToString("yyyy-MM-dd HH:mm:ss") + ") still holds " + path + " - this launch did not run");
350
- return EXIT_ALREADY_RUNNING;
351
- }
352
- try
353
- {
354
- File.Delete(path);
355
- }
356
- catch (IOException e)
357
- {
358
- Say("REFUSED - " + path + " named '" + held + "' and could not be replaced (" + e.Message + ") - this launch did not run");
359
- return EXIT_ALREADY_RUNNING;
360
- }
361
- Say("STALE LOCK - " + path + " named '" + held + "', which " + (parsed ? "no longer runs" : "is not a pid and start time") + " - taken over");
362
- }
363
- Say("REFUSED - " + path + " was taken by another launch while its stale holder was being replaced - this launch did not run");
364
- return EXIT_ALREADY_RUNNING;
365
- }
366
-
367
- static void ReleaseLock(string path, string mine)
368
- {
369
- if (ReadLock(path) == mine)
370
- {
371
- File.Delete(path);
372
- }
373
- }
374
-
375
- static void Say(string text)
376
- {
377
- Console.Error.WriteLine("ownerGuard: " + text);
378
- }
379
-
380
- // The target as the launch has always resolved it (Get-Command -CommandType Application): a name with a folder is
381
- // taken as given, a bare name is searched along PATH, and a name without a PATHEXT extension tries each one.
382
- static string Resolve(string exe)
383
- {
384
- List<string> extensions = new List<string>((Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD")
385
- .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
386
- List<string> folders = new List<string>();
387
- if (exe.IndexOfAny(new char[] { '\\', '/', ':' }) >= 0)
388
- {
389
- folders.Add(null);
390
- }
391
- else
392
- {
393
- foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
394
- {
395
- folders.Add(dir.Trim('"'));
396
- }
397
- }
398
- foreach (string folder in folders)
399
- {
400
- string stem = folder == null ? exe : Path.Combine(folder, exe);
401
- if (File.Exists(stem) && extensions.Exists(delegate(string e) { return stem.EndsWith(e, StringComparison.OrdinalIgnoreCase); }))
402
- {
403
- return Path.GetFullPath(stem);
404
- }
405
- foreach (string ext in extensions)
406
- {
407
- if (File.Exists(stem + ext))
408
- {
409
- return Path.GetFullPath(stem + ext);
410
- }
411
- }
412
- }
413
- return null;
414
- }
415
-
416
- // The command line the target is created with, or null (and a refusal said) when it cannot be carried.
417
- static string CommandLine(ref string exe, string[] args, out int refusal)
418
- {
419
- refusal = 0;
420
- string ext = Path.GetExtension(exe).ToLowerInvariant();
421
- StringBuilder line = new StringBuilder();
422
- if (ext == ".cmd" || ext == ".bat")
423
- {
424
- foreach (string arg in args)
425
- {
426
- if (arg.IndexOfAny(new char[] { '\r', '\n' }) >= 0)
427
- {
428
- Say("the target '" + exe + "' is a batch file and one of its arguments holds a line break, which cmd.exe cannot carry - nothing was started");
429
- refusal = EXIT_BATCH_LINE_BREAK;
430
- return null;
431
- }
432
- }
433
- StringBuilder inner = new StringBuilder(EscapeCmd(exe));
434
- foreach (string arg in args)
435
- {
436
- inner.Append(' ').Append(EscapeCmd(EscapeCmd(QuoteArg(arg))));
437
- }
438
- exe = Path.Combine(Environment.SystemDirectory, "cmd.exe");
439
- return QuoteArg(exe) + " /d /s /v:off /c \"" + inner + "\"";
440
- }
441
- line.Append(QuoteArg(exe));
442
- foreach (string arg in args)
443
- {
444
- line.Append(' ').Append(QuoteArg(arg));
445
- }
446
- return line.ToString();
447
- }
448
-
449
- public static int Run(int ownerPid, string exe, string[] args, string cwd)
450
- {
451
- return Run(ownerPid, exe, args, cwd, 0, false, null);
452
- }
453
-
454
- // Runs the target inside a kill-on-close job and answers the target's own exit code. ownerPid <= 0 means
455
- // "the parent process owns this launch", FRAME_OWNERS means "the shell frame owns it" (ShellFrame). cwd null or
456
- // empty starts the target where this process runs. deadlineSeconds > 0 ends the whole job at that age
457
- // (EXIT_DEADLINE). contain leaves BREAKAWAY_OK off, so no process inside can leave the job, Git Bash's
458
- // included. lockFile, when given, admits one launch at a time (TakeLock).
459
- public static int Run(int ownerPid, string exe, string[] args, string cwd, int deadlineSeconds, bool contain, string lockFile)
460
- {
461
- if (string.IsNullOrEmpty(exe) || exe.Trim().Length == 0)
462
- {
463
- Say("the target executable is empty - nothing was started");
464
- return EXIT_NO_TARGET;
465
- }
466
- if (string.IsNullOrEmpty(cwd))
467
- {
468
- cwd = null;
469
- }
470
- string resolved = Resolve(exe);
471
- if (resolved == null)
472
- {
473
- Say("the target '" + exe + "' is not an executable on PATH or on disk - nothing was started");
474
- return EXIT_NOT_FOUND;
475
- }
476
- exe = resolved;
477
- int refusal;
478
- string line = CommandLine(ref exe, args, out refusal);
479
- if (line == null)
480
- {
481
- return refusal;
482
- }
483
- string mine = null;
484
- if (!string.IsNullOrEmpty(lockFile))
485
- {
486
- int refused = TakeLock(lockFile, out mine);
487
- if (refused != 0)
488
- {
489
- return refused;
490
- }
491
- }
492
- try
493
- {
494
- return Launch(ownerPid, exe, line, cwd, deadlineSeconds, contain);
495
- }
496
- finally
497
- {
498
- if (mine != null)
499
- {
500
- ReleaseLock(lockFile, mine);
501
- }
502
- }
503
- }
504
-
505
- static int Launch(int ownerPid, string exe, string line, string cwd, int deadlineSeconds, bool contain)
506
- {
507
- bool frame = ownerPid == FRAME_OWNERS;
508
- bool viaParent = !frame && ownerPid <= 0;
509
- if (viaParent)
510
- {
511
- ownerPid = ParentPid();
512
- }
513
-
514
- IntPtr job = CreateJobObject(IntPtr.Zero, null);
515
- if (job == IntPtr.Zero)
516
- {
517
- Say("the job object could not be created (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
518
- return EXIT_NO_JOB;
519
- }
520
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
521
- limits.BasicLimitInformation.LimitFlags = contain ? KILL_ON_JOB_CLOSE : KILL_ON_JOB_CLOSE | BREAKAWAY_OK;
522
- int size = Marshal.SizeOf(limits);
523
- IntPtr buffer = Marshal.AllocHGlobal(size);
524
- try
525
- {
526
- Marshal.StructureToPtr(limits, buffer, false);
527
- if (!SetInformationJobObject(job, EXTENDED_LIMIT_INFORMATION, buffer, (uint)size))
528
- {
529
- Say("the job could not be told to kill on close (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
530
- CloseHandle(job);
531
- return EXIT_NO_LIMIT;
532
- }
533
- }
534
- finally
535
- {
536
- Marshal.FreeHGlobal(buffer);
537
- }
538
-
539
- STARTUPINFO startup = new STARTUPINFO();
540
- startup.cb = Marshal.SizeOf(startup);
541
- IntPtr stdin = GetStdHandle(-10), stdout = GetStdHandle(-11), stderr = GetStdHandle(-12);
542
- if (stdin != IntPtr.Zero && stdout != IntPtr.Zero && stderr != IntPtr.Zero)
543
- {
544
- startup.dwFlags = STARTF_USESTDHANDLES;
545
- startup.hStdInput = stdin;
546
- startup.hStdOutput = stdout;
547
- startup.hStdError = stderr;
548
- }
549
-
550
- PROCESS_INFORMATION process;
551
- if (!CreateProcess(exe, line, IntPtr.Zero, IntPtr.Zero, true, CREATE_SUSPENDED, IntPtr.Zero, cwd, ref startup, out process))
552
- {
553
- Say("the target could not be created (win32 " + Marshal.GetLastWin32Error() + ") - nothing was started");
554
- CloseHandle(job);
555
- return EXIT_NOT_CREATED;
556
- }
557
- if (!AssignProcessToJobObject(job, process.hProcess))
558
- {
559
- int error = Marshal.GetLastWin32Error();
560
- TerminateJobObject(job, EXIT_NOT_ASSIGNED);
561
- CloseHandle(process.hThread);
562
- CloseHandle(process.hProcess);
563
- CloseHandle(job);
564
- Say("the target could not be put under the job that ends it with its owner (win32 " + error + ") - it was stopped rather than left unguarded");
565
- return EXIT_NOT_ASSIGNED;
566
- }
567
-
568
- // The owner is opened AFTER the target sits in the job and BEFORE it runs, so a dead owner stops it unrun.
569
- List<IntPtr> owners = new List<IntPtr>();
570
- if (frame)
571
- {
572
- owners = ShellFrame();
573
- }
574
- else if (ownerPid > 0)
575
- {
576
- IntPtr owner = OpenOwner(ownerPid, viaParent);
577
- if (owner != IntPtr.Zero)
578
- {
579
- owners.Add(owner);
580
- }
581
- }
582
- if (owners.Count == 0)
583
- {
584
- int why = Marshal.GetLastWin32Error();
585
- TerminateJobObject(job, EXIT_OWNER_GONE);
586
- CloseHandle(process.hThread);
587
- CloseHandle(process.hProcess);
588
- CloseHandle(job);
589
- Say((frame ? "the shell frame above this guard" : "the owner process " + ownerPid) + " cannot be watched (win32 " + why + ") - the target was stopped before it ran");
590
- return EXIT_OWNER_GONE;
591
- }
592
-
593
- if (ResumeThread(process.hThread) == 0xFFFFFFFF)
594
- {
595
- int why = Marshal.GetLastWin32Error();
596
- TerminateJobObject(job, EXIT_NOT_RESUMED);
597
- Say("the target could not be resumed (win32 " + why + ") - it was stopped rather than left suspended");
598
- return EXIT_NOT_RESUMED;
599
- }
600
- CloseHandle(process.hThread);
601
-
602
- List<IntPtr> watched = new List<IntPtr>(owners);
603
- watched.Insert(0, process.hProcess);
604
- uint waited = WaitForMultipleObjects((uint)watched.Count, watched.ToArray(), false, deadlineSeconds > 0 ? (uint)deadlineSeconds * 1000 : INFINITE);
605
- int waitError = Marshal.GetLastWin32Error();
606
- foreach (IntPtr owner in owners)
607
- {
608
- CloseHandle(owner);
609
- }
610
- if (waited == 0xFFFFFFFF)
611
- {
612
- TerminateJobObject(job, EXIT_WAIT_FAILED);
613
- Say("the wait on the target and its owner failed (win32 " + waitError + ") - the target was stopped rather than left unwatched");
614
- return EXIT_WAIT_FAILED;
615
- }
616
- if (waited == WAIT_TIMEOUT)
617
- {
618
- TerminateJobObject(job, EXIT_DEADLINE);
619
- Say("DEADLINE - the target ran past its " + deadlineSeconds + " s; its whole job was ended");
620
- return EXIT_DEADLINE;
621
- }
622
- if (waited != 0)
623
- {
624
- TerminateJobObject(job, EXIT_OWNER_GONE);
625
- Say("OWNER GONE - a process this launch was bound to ended; the target's whole job was ended");
626
- return EXIT_OWNER_GONE;
627
- }
628
-
629
- uint code = 0;
630
- if (!GetExitCodeProcess(process.hProcess, out code))
631
- {
632
- int why = Marshal.GetLastWin32Error();
633
- TerminateJobObject(job, EXIT_NO_EXIT_CODE);
634
- Say("the target's exit code could not be read (win32 " + why + ") - the target was stopped");
635
- return EXIT_NO_EXIT_CODE;
636
- }
637
- TerminateJobObject(job, 1);
638
- CloseHandle(process.hProcess);
639
- CloseHandle(job);
640
- return (int)code;
641
- }
642
-
643
- public static int Main(string[] argv)
644
- {
645
- List<string> rest = new List<string>(argv);
646
- int ownerPid = 0;
647
- if (rest.Count >= 2 && rest[0] == "--owner")
648
- {
649
- if (!int.TryParse(rest[1], out ownerPid) || ownerPid <= 0)
650
- {
651
- Say("--owner needs a process id");
652
- return EXIT_NO_TARGET;
653
- }
654
- rest.RemoveRange(0, 2);
655
- }
656
- if (rest.Count == 0)
657
- {
658
- Say("usage: ownerGuard.exe [--owner <pid>] <exe> [args...]");
659
- return EXIT_NO_TARGET;
660
- }
661
- string exe = rest[0];
662
- rest.RemoveAt(0);
663
- return Run(ownerPid, exe, rest.ToArray(), null);
664
- }
665
- }
@@ -1,31 +0,0 @@
1
- # OWNER-BOUND LAUNCH (#1968): start one target so that it can never outlive its owner, and so that nothing it
2
- # started can outlive IT. This script is only the PowerShell door onto ownerGuard.cs, which holds the whole job.
3
- # #2925: the same source is no longer compiled into an ownerGuard.exe for `claudeCode.claudeProcessWrapper` — that
4
- # build ran csc.exe at every activation, and the .NET compiler is not a dependency a marketplace install may carry.
5
- # The target's own exit code is answered as this script's exit code.
6
- param(
7
- [Parameter(Mandatory = $true)][int]$OwnerPid,
8
- [Parameter(Mandatory = $true)][string]$ExeB64,
9
- [Parameter(Mandatory = $true)][string]$ArgsB64,
10
- [Parameter(Mandatory = $true)][AllowEmptyString()][string]$CwdB64,
11
- [switch]$ShellFrame,
12
- [int]$DeadlineSeconds = 0,
13
- [switch]$Contain,
14
- [string]$LockFile = ""
15
- )
16
-
17
- $ErrorActionPreference = "Stop"
18
-
19
- Add-Type -Path (Join-Path $PSScriptRoot "ownerGuard.cs")
20
-
21
- $exe = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ExeB64))
22
- # ConvertFrom-Json hands back the WHOLE array as one object on Windows PowerShell, so iterate it with
23
- # foreach: a one-element array arrives as the element itself and a longer one as the array, both right.
24
- $argv = New-Object System.Collections.Generic.List[string]
25
- foreach ($item in ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ArgsB64)) | ConvertFrom-Json)) {
26
- $argv.Add([string]$item)
27
- }
28
- $cwd = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($CwdB64))
29
-
30
- if ($ShellFrame) { $OwnerPid = [OwnerJob]::FRAME_OWNERS }
31
- exit ([OwnerJob]::Run($OwnerPid, $exe, $argv.ToArray(), $cwd, $DeadlineSeconds, $Contain.IsPresent, $LockFile))