omni-notify-mcp 1.3.472 → 1.3.475

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/notify.js CHANGED
@@ -2195,7 +2195,8 @@ async function pollSlackOnce(token, channel) {
2195
2195
  .filter(m => !m.subtype && !m.bot_id && !m.app_id && m.user && String(m.text ?? "").trim())
2196
2196
  .sort((a, b) => Number(a.ts) - Number(b.ts));
2197
2197
  const isAsk = (m) => String(m.text ?? "").replace(/<@[A-Za-z0-9]+>/g, "").toLowerCase().trim().startsWith(AGENT_PREFIX);
2198
- const asks = human.filter(isAsk);
2198
+ // Every message meant for the agent — his own words and a '!'-prefixed ask — not bus commands or a message addressed to a connected client.
2199
+ const forAgent = human.filter((m) => !isSlackBusTraffic(m));
2199
2200
  // Meni is found before anything is taken off the channel, so a users.list that fails for a moment throws here and every message is read again; a poll with no human message and no open agent thread never asks.
2200
2201
  let owner;
2201
2202
  try {
@@ -2206,9 +2207,11 @@ async function pollSlackOnce(token, channel) {
2206
2207
  catch (err) {
2207
2208
  if (!(err instanceof SlackOwnerUnknown) && !(err instanceof SlackRefused && err.error === "missing_scope"))
2208
2209
  throw err;
2209
- // OWNER: the agent answers only Meni, and Slack will not name him until the app holds users:read — no agent message is answered, the cause is logged once, and the inbox goes on.
2210
- if (err.message !== slackOwnerRefusal)
2211
- log("·", "agent:slack", `${asks.length} agent message(s) not answered: ${err.message}`);
2210
+ // OWNER: the agent answers only Meni, and Slack will not name him until the app holds users:read — no message of his is answered, the reason is said once in the channel and logged once, and the bus goes on.
2211
+ if (err.message !== slackOwnerRefusal) {
2212
+ log("·", "agent:slack", `${forAgent.length} message(s) in ${channel} not answered: ${err.message}`);
2213
+ await reply(`⚠️ Nothing you post in this channel reaches an agent — ${err.message}. Tap Reinstall in BN once that is fixed.`);
2214
+ }
2212
2215
  slackOwnerRefusal = err.message;
2213
2216
  }
2214
2217
  for (const m of human) {
@@ -2216,12 +2219,16 @@ async function pollSlackOnce(token, channel) {
2216
2219
  try {
2217
2220
  // NULL-OK: field owner is OPTIONAL and therefore it is ok to check for NULL
2218
2221
  if (isAsk(m)) {
2222
+ // NULL-OK: field owner is OPTIONAL and therefore it is ok to check for NULL
2219
2223
  if (owner !== undefined)
2220
2224
  await answerSlackAgentMessage(token, channel, m, owner);
2221
2225
  }
2222
2226
  // NULL-OK: field owner is OPTIONAL and therefore it is ok to check for NULL
2223
2227
  else if (owner !== undefined && m.user === owner && !isSlackBusTraffic(m))
2224
2228
  takeSlackDmMessage(slackChannelChat(token, channel), owner, m);
2229
+ // The owner is unknown, so his words cannot be told apart from anyone else's and are answered by nobody — the channel already says why; never the misleading "No agents connected" reply.
2230
+ else if (owner === undefined && !isSlackBusTraffic(m))
2231
+ continue;
2225
2232
  else
2226
2233
  await routeSlackInbox(m, reply);
2227
2234
  }
@@ -2283,14 +2290,35 @@ const slackThreadCursor = (channel, threadTs) => POLL_CURSORS.cursor(`${SLACK_TH
2283
2290
  const slackDms = new Map();
2284
2291
  /** Why the direct message cannot be read with this bot token; it is not tried again until the token changes or BN restarts. */
2285
2292
  let slackDmOff;
2286
- /** Meni's direct-message chat with the bot: the workspace owner's, opened with conversations.open — a call Slack allows only once it has granted the app im:write. */
2293
+ /** The direct-message channel of the workspace owner: Slack's conversations.open once the app holds im:write, else opened by a post to his user id (chat:write alone) that is deleted at once, so his chat is left exactly as it was — no greeting, and the DM still works on a workspace that never granted im:write. */
2294
+ async function openSlackDm(token, owner) {
2295
+ try {
2296
+ return String((await slackCall(SLACK_API_BASE, token, "conversations.open", { users: owner })).channel.id);
2297
+ }
2298
+ catch (err) {
2299
+ if (!(err instanceof SlackRefused) || err.error !== "missing_scope")
2300
+ throw err;
2301
+ }
2302
+ const opened = await slackCall(SLACK_API_BASE, token, "chat.postMessage", { channel: owner, text: "." });
2303
+ const channel = String(opened.channel);
2304
+ try {
2305
+ await slackCall(SLACK_API_BASE, token, "chat.delete", { channel, ts: String(opened.ts) });
2306
+ }
2307
+ catch (err) {
2308
+ // OWNER: a Slack documented refusal or an unreachable Slack when deleting the opener must not cost him the whole direct message — the failure is logged and the DM is opened with the opener line left in place.
2309
+ if (!(err instanceof SlackRefused) && !(err instanceof SlackUnreachable) && !(err instanceof SlackUnknown))
2310
+ throw err;
2311
+ log("·", "slack:error", `the Slack direct message was opened by a post that could not be deleted: ${err.message}`);
2312
+ }
2313
+ return channel;
2314
+ }
2315
+ /** Meni's direct-message chat with the bot: the workspace owner's, opened once per token, its conversation keyed by the channel id. */
2287
2316
  async function slackDmOf(token, owner) {
2288
2317
  const known = slackDms.get(token);
2289
2318
  // NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
2290
2319
  if (known !== undefined)
2291
2320
  return known;
2292
- const opened = await slackCall(SLACK_API_BASE, token, "conversations.open", { users: owner });
2293
- const dm = new SlackMessenger(SLACK_API_BASE, token, String(opened.channel.id), slackSwitchedOn, undefined, undefined, (line) => log("→", "agent:slack", line), slackTappable);
2321
+ const dm = new SlackMessenger(SLACK_API_BASE, token, await openSlackDm(token, owner), slackSwitchedOn, undefined, undefined, (line) => log("→", "agent:slack", line), slackTappable);
2294
2322
  slackDms.set(token, dm);
2295
2323
  // The thread views post with the token they were made with: a new bot token starts them afresh.
2296
2324
  slackThreadViews.clear();
@@ -4194,6 +4194,41 @@ function movedWords(moved) {
4194
4194
  /** 🔴 #4123 — a parked worker's idle process is stopped at once, and a stop that did not take is tried again only after its wait. */
4195
4195
  // NULL-OK: field stoppedAt is OPTIONAL and therefore it is ok to check for NULL
4196
4196
  const stopDue = (worker, now) => worker.stoppedAt === undefined || now >= worker.stoppedAt + wakeDelayMs(worker.wakes ?? 0);
4197
+ /**
4198
+ * 🔴 #4559/#4587 — THE RUNNING LANE A CUT OF PRIORITY `cutPri` PAUSES, or undefined when none can be: the lowest priority first and never one above the
4199
+ * cut's own ({@link PRI_ORDER}), then the least progress — the lane's living number, tool steps a minute — then the newest start; and only a worker whose
4200
+ * stop is asked at its next tool call, never one already pausing, parked, on another box, or ended by ⛔ Kill, so nothing is ever killed and the cut is never
4201
+ * itself. ONE chooser, so a ⚡ Force start and a BN chat's request that reaches the queue from outside it pick the same lane.
4202
+ */
4203
+ export function yieldLaneFor(entries, cutStoryId, cutPri, progress) {
4204
+ const rank = (x) => rankIn(PRI_ORDER, x.pri);
4205
+ const cut = rankIn(PRI_ORDER, cutPri);
4206
+ const pausable = (x) => x.storyId !== cutStoryId && x.state === "running" && x.handStop === undefined && x.worker !== undefined && x.worker.parkedAt === undefined && x.worker.box === undefined && stopRouteOf(x.worker).stop === "asked" && rank(x) >= cut;
4207
+ return entries.filter(pausable).sort((a, b) => rank(b) - rank(a) || progress(a.storyId) - progress(b.storyId) || b.worker.startedAt - a.worker.startedAt)[0];
4208
+ }
4209
+ /**
4210
+ * 🔴 #4587 items 8–11 — A REQUEST THAT REACHES THE QUEUE FROM OUTSIDE IT TAKES ITS SLOT, THE WORKING LANE IS PUT BACK INTACT. A BN chat's lane works a story
4211
+ * of this board directly (outside the queue), so FleetView injects it as a first-class queue row ({@link gateStoryHolders}) and, once that lane takes the
4212
+ * workspace past its lane limit, pauses the lane this request outranks that has made the least progress — the SAME pause a ⚡ Force start makes
4213
+ * ({@link yieldLaneFor}), never a second preemption. The paused lane keeps its story, its worktree, its branch and its worker's own session, goes back in line
4214
+ * with exactly the progress it had, and is woken in its own session when a lane frees. Answers what it did, in words naming both lanes.
4215
+ */
4216
+ export async function yieldLaneForRequest(board, storyId, pri, progress, now, by) {
4217
+ return withQueueLock(board, now, async () => {
4218
+ const store = readQueueStore(board);
4219
+ const lane = yieldLaneFor(store.entries, storyId, pri, progress);
4220
+ // NULL-OK: field lane is OPTIONAL and therefore it is ok to check for NULL
4221
+ if (lane === undefined)
4222
+ return `#${storyId} (${pri}) takes a lane from no running lane — none on this board is of its priority or lower with a stop asked at its next step`;
4223
+ lane.handStop = { at: now, by, yieldFor: storyId };
4224
+ delete lane.pauseCancelled;
4225
+ const known = progress(lane.storyId);
4226
+ lane.why = `${stopNamed(lane.handStop)}: #${storyId} (${pri}) outranks it and takes its lane, and it is the ${lane.pri} lane with the least progress (${Number.isFinite(known) ? `${known.toFixed(1)} tool steps a minute` : "no transcript reading"}) — its worker ${lane.worker.jobId} is asked to finish its step, write its progress and end its turn, then it keeps its worktree, its branch and its session, goes back in line and is woken in its own session`;
4227
+ step(lane, now, "stop-asked", lane.why);
4228
+ writeStore(board, store);
4229
+ return `#${storyId} (${pri}) takes the lane of #${lane.storyId}, the ${lane.pri} lane with the least progress — its worker ${lane.worker.jobId} is paused at its next step and put back in the queue with its worktree, branch and progress kept`;
4230
+ });
4231
+ }
4197
4232
  /**
4198
4233
  * 🔴 ONE PASS OF FLEETVIEW'S STORY QUEUE ON ONE BOARD, under its lock: every request derived from the board's startable read is applied,
4199
4234
  * every worker is checked (a story shipped closes its entry; a worker that ended with the story still open is started
@@ -5043,12 +5078,9 @@ async function passHeld(board, world, now) {
5043
5078
  // NULL-OK: field short is OPTIONAL and therefore it is ok to check for NULL
5044
5079
  if (!overLimit && short === undefined)
5045
5080
  return;
5046
- const rank = (x) => rankIn(PRI_ORDER, x.pri);
5047
5081
  // NULL-OK: field progressOf is OPTIONAL and therefore it is ok to check for NULL
5048
- const progress = (x) => world.progressOf?.(x.storyId) ?? Number.POSITIVE_INFINITY;
5049
- // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
5050
- const pausable = (x) => x !== cut && x.state === "running" && x.handStop === undefined && x.worker !== undefined && x.worker.parkedAt === undefined && x.worker.box === undefined && stopRouteOf(x.worker).stop === "asked" && rank(x) >= rank(cut);
5051
- const lane = store.entries.filter(pausable).sort((a, b) => rank(b) - rank(a) || progress(a) - progress(b) || b.worker.startedAt - a.worker.startedAt)[0];
5082
+ const progress = (storyId) => world.progressOf?.(storyId) ?? Number.POSITIVE_INFINITY;
5083
+ const lane = yieldLaneFor(store.entries, cut.storyId, cut.pri, progress);
5052
5084
  const over = overLimit ? `${running} lanes run past this workspace's limit of ${lanes.limit}` : short.why;
5053
5085
  // NULL-OK: field lane is OPTIONAL and therefore it is ok to check for NULL
5054
5086
  if (lane === undefined) {
@@ -5057,7 +5089,7 @@ async function passHeld(board, world, now) {
5057
5089
  }
5058
5090
  lane.handStop = { at: now, by: `${by} ⚡ Force start of #${cut.storyId}`, yieldFor: cut.storyId };
5059
5091
  delete lane.pauseCancelled;
5060
- const known = progress(lane);
5092
+ const known = progress(lane.storyId);
5061
5093
  lane.why = `${stopNamed(lane.handStop)}: ${over}, and it is the ${lane.pri} lane with the least progress (${Number.isFinite(known) ? `${known.toFixed(1)} tool steps a minute` : "no transcript reading"}) — its worker ${lane.worker.jobId} is asked to finish its step, write its progress and end its turn, then it waits in line and is woken in its own session`;
5062
5094
  step(lane, now, "stop-asked", lane.why);
5063
5095
  step(cut, now, "started", `its ⚡ Force start runs past the limit (${over}), so #${lane.storyId}, the ${lane.pri} lane with the least progress, is paused at its next step for it`);
@@ -15,6 +15,7 @@ import { EventEmitter } from "events";
15
15
  import { homedir } from "os";
16
16
  import { basename, dirname, join, resolve } from "path";
17
17
  import autoSwitch from "../webhost/autoSwitch.cjs";
18
+ import { proveStartProviders } from "./providerProof.js";
18
19
  import { workspacesFile, workspacesHere } from "../webhost/workspaceList.js";
19
20
  import { CLUSTER_OWNER, OwnershipUnreadable, startOwnerOf } from "../providerOwnership.js";
20
21
  /** Thrown for a request the caller got wrong; the door turns it into the status code. */
@@ -722,12 +723,21 @@ export function createConversationStore(host, registry) {
722
723
  * The agent CLI a session is CREATED on (#3640): the one its creation named, or — named none (#4157) — the shared
723
724
  * subscription-first pick (`autoProvider`, the one FleetView's AUTO runs) over every CLI this gateway runs — at the
724
725
  * workspace root only those that load every project's rules there — weighed by DeepAgent's `provider_room` read for the folder.
726
+ *
727
+ * #4621 — AND PINGED FIRST, BY CONSTRUCTION. A provider that reads roomy is not a provider that ANSWERS. The ping rides
728
+ * the ONE reading every picker already takes (`readProviderRooms` asks DeepAgent's door with `prove: true`, and the shared
729
+ * reading treats a provider whose route did not answer as `out`), so this pick — and FleetView's queue and any other app's
730
+ * picker over the same reading — skip a route that does not answer with no second check here. A provider he NAMED by hand
731
+ * takes no room read, so it is proved directly and a refusal is said plainly, never silently swapped for another CLI.
725
732
  */
726
733
  async function pickedCli(provider, folder, model) {
727
734
  if (provider !== undefined && provider !== "auto" && !(typeof provider === "string" && provider.trim() === "")) {
728
735
  const named = namedProvider(provider);
729
736
  if (heldElsewhere(host.startOwner, named))
730
737
  throw heldBy(host.startOwner, named);
738
+ const [proof] = await proveStartProviders(folder, [named], deepagentDoor());
739
+ if (proof !== undefined && proof.state === "failed")
740
+ throw new GatewayError(503, `${named} does not answer now — ${proof.line}. Your choice was not replaced with another CLI: pick a different provider, or repair this one in DeepAgent, and start again.`);
731
741
  return { provider: named };
732
742
  }
733
743
  const startable = (isRootFolder(folder) ? registry().names.filter((name) => registry().get(name).routesAtRoot === true) : registry().names).filter((name) => !heldElsewhere(host.startOwner, name));
@@ -749,11 +759,13 @@ export function createConversationStore(host, registry) {
749
759
  home: homedir(),
750
760
  usesKey: (name) => registry().get(name)?.usesKey?.(folder, model) ?? false,
751
761
  });
762
+ // #4621 — a provider whose route the ping refused reads `out` on its own reading, so the pick has already moved past it; name every refusal so a start that lands nowhere says why.
763
+ const refused = Object.entries(rooms).flatMap(([id, r]) => (r?.proof?.state === "failed" ? [`${id} does not answer now — ${r.proof.line}`] : []));
752
764
  if (picked === undefined)
753
- throw new GatewayError(503, "Auto has no subscription with room and no permitted, funded key for the eligible CLIs.");
765
+ throw new GatewayError(503, refused.length > 0 ? `no agent CLI answers now: ${refused.join("; ")}` : "Auto has no subscription with room and no permitted, funded key for the eligible CLIs.");
754
766
  const unread = [...new Set(Object.values(rooms).flatMap((r) => (r?.state === "unread" ? [r.reason] : [])))];
755
767
  const words = Object.entries(rooms).map(([id, r]) => `${id} ${r?.state}`).join(", ") + (unread.length === 0 ? "" : ` — unread: ${unread.join("; ")}`);
756
- process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}\n`);
768
+ process.stderr.write(`[agent-gateway] no provider named for ${folder}: ${picked} of ${startable.join("/")}, the subscription-first pick over ${words}${refused.length === 0 ? "" : ` — refused by the ping: ${refused.join("; ")}`}\n`);
757
769
  return { provider: picked, ...(unreadBecause === undefined ? {} : { unreadBecause }) };
758
770
  }
759
771
  /** #4157 — the creations still waiting on their CLI pick, by the chat they are made for: an ask from that chat routes only once they exist, so it is never doubled beside one nor sent past it. */
@@ -0,0 +1,75 @@
1
+ /**
2
+ * #4621 — THE PING GATE BEFORE AN AGENT IS CREATED.
3
+ *
4
+ * Meni: *"flawless transition between agentic provider/sub/key at all time"*. A provider's room reading
5
+ * (`provider_room`) says an account has room LEFT; it never says the route ANSWERS — a funded key the provider
6
+ * gates, a revoked login, or a provider whose tool enum refuses the client all read as room with no call ever
7
+ * made. So the start door pings each candidate BEFORE it creates the agent: DeepAgent runs one real model call
8
+ * per provider on the very combination (provider, subscription or key, model) a new agent there would run on,
9
+ * and this returns one row per provider saying whether it answered.
10
+ *
11
+ * A provider the call refused is dropped and the pick moves on; one DeepAgent cannot call right now (its own
12
+ * door gave no answer) is `untestable`, never a failure — an untaken reading is not the same as one that failed.
13
+ *
14
+ * The call goes over DeepAgent's MCP door, the same door `autoSwitch.readProviderRooms` reads room from. The
15
+ * address is mirrored here rather than shared because that module was held by another lane when this landed.
16
+ */
17
+ const DEEPAGENT_MCP_URL = "http://127.0.0.1:7473/mcp";
18
+ // GATE: how long one `provider_prove` read may take before every row reads untestable — DeepAgent pings its
19
+ // providers in parallel, each bounded at its own 30s, so 45s clears the slowest single pass and no more.
20
+ const PROVE_READ_TIMEOUT_MS = 45_000;
21
+ /**
22
+ * Pings the named providers over DeepAgent's `provider_prove` door and returns one row each. A door that gives
23
+ * no answer, a non-200, or a body that is no reading makes every row `untestable` with the reason — a reading
24
+ * this gate could not take never silently passes a provider as working, and never blocks a start either.
25
+ */
26
+ export async function proveStartProviders(project, providers, url) {
27
+ const door = url ?? DEEPAGENT_MCP_URL;
28
+ const everyUntestable = (why) => providers.map((provider) => ({ provider, state: "untestable", line: why }));
29
+ let res;
30
+ try {
31
+ res = await fetch(door, {
32
+ method: "POST",
33
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-deepagent-project": project },
34
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_prove", arguments: { providers: [...providers] } } }),
35
+ signal: AbortSignal.timeout(PROVE_READ_TIMEOUT_MS),
36
+ });
37
+ }
38
+ catch (err) {
39
+ if (!(err instanceof TypeError) && !(err instanceof Error && err.name === "TimeoutError"))
40
+ throw err;
41
+ const cause = err instanceof Error && err.cause instanceof Error ? ` (${err.cause.message})` : "";
42
+ return everyUntestable(`DeepAgent's ping door at ${door} gave no answer: ${err instanceof Error ? err.message : String(err)}${cause}`);
43
+ }
44
+ if (res.status !== 200)
45
+ return everyUntestable(`provider_prove answered HTTP ${res.status}`);
46
+ let reply;
47
+ try {
48
+ reply = JSON.parse(await res.text());
49
+ }
50
+ catch (err) {
51
+ if (!(err instanceof SyntaxError))
52
+ throw err;
53
+ return everyUntestable("provider_prove's reply is not JSON");
54
+ }
55
+ const body = reply.result?.content?.[0]?.text;
56
+ if (reply.result === undefined || reply.result.isError === true || typeof body !== "string") {
57
+ return everyUntestable(`provider_prove gave no reading: ${String(body ?? reply.error?.message ?? "").slice(0, 200)}`);
58
+ }
59
+ let reading;
60
+ try {
61
+ reading = JSON.parse(body);
62
+ }
63
+ catch (err) {
64
+ if (!(err instanceof SyntaxError))
65
+ throw err;
66
+ return everyUntestable("provider_prove's reading is not JSON");
67
+ }
68
+ const rows = Array.isArray(reading.proofs) ? reading.proofs : [];
69
+ return providers.map((provider) => {
70
+ const found = rows.find((row) => row?.provider === provider);
71
+ return found !== undefined && typeof found.state === "string" && typeof found.line === "string"
72
+ ? { provider, state: found.state, line: found.line }
73
+ : { provider, state: "untestable", line: "provider_prove did not answer for this provider" };
74
+ });
75
+ }
@@ -551,7 +551,7 @@ class RoomReadError extends Error {
551
551
  /**
552
552
  * @typedef {{ label: string, roomPct: number | undefined, resetsAt: number | undefined, refused: boolean, unread?: string }} AccountRoom
553
553
  * @typedef {{ label: string, funds: string }} KeyRoom
554
- * @typedef {{ live?: string, accounts?: AccountRoom[], keys?: KeyRoom[] }} RoomDetail
554
+ * @typedef {{ live?: string, accounts?: AccountRoom[], keys?: KeyRoom[], proof?: { state: string, line: string } }} RoomDetail
555
555
  * @typedef {({ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }) & RoomDetail} RoomReading
556
556
  * @typedef {Partial<Record<string, RoomReading>>} ProviderRooms
557
557
  */
@@ -569,7 +569,9 @@ function roomDetailOf(provider, keys, id) {
569
569
  }));
570
570
  // NULL-OK: field keys is OPTIONAL and therefore it is ok to check for NULL
571
571
  const runs = keys === undefined ? {} : { keys: keys.filter((k) => Array.isArray(k.agents) && k.agents.includes(id)).map((k) => ({ label: String(k.label ?? k.id), funds: String(k.funds) })) };
572
- return { ...(typeof provider.live === "string" ? { live: provider.live } : {}), accounts, ...runs };
572
+ // #4621 — the one real call that proved this provider's live route, carried onto the reading so a picker that lands elsewhere can say WHY.
573
+ const proof = provider.proof && typeof provider.proof.state === "string" ? { proof: { state: String(provider.proof.state), line: String(provider.proof.line ?? "") } } : {};
574
+ return { ...(typeof provider.live === "string" ? { live: provider.live } : {}), accounts, ...runs, ...proof };
573
575
  }
574
576
  /** @param {string} provider */
575
577
  function runsOnKeys(provider) {
@@ -635,6 +637,11 @@ function roomReadingOf(provider, now, keys, id) {
635
637
  }
636
638
  const accounts = provider.accounts;
637
639
  const detail = roomDetailOf(provider, keys, id);
640
+ // #4621 — A PROVIDER THAT DID NOT ANSWER IS NOT ROOM, whatever its room says: the ping gate, folded into the ONE
641
+ // reading every picker already takes, so a route that refuses a real call is never picked — by construction, with
642
+ // no second check in any door. `state: "out"` is what every picker already treats as "not this one".
643
+ if (provider.proof && provider.proof.state === "failed")
644
+ return { state: "out", resetsAtMs: undefined, ...detail };
638
645
  if (accounts.some((a) => a.state === "read" && a.refused !== true && (a.unlimited === true || (typeof a.roomPct === "number" && a.roomPct > 0))))
639
646
  return { state: "room", ...detail };
640
647
  if (accounts.length === 0 || !accounts.every((a) => a.state === "read" && typeof a.roomPct === "number"))
@@ -698,7 +705,7 @@ async function roomDoorAnswer(url, project) {
698
705
  const res = await fetch(url, {
699
706
  method: "POST",
700
707
  headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "x-deepagent-project": project },
701
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_room", arguments: {} } }),
708
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "provider_room", arguments: { prove: true } } }),
702
709
  signal: AbortSignal.timeout(ROOM_READ_TIMEOUT_MS),
703
710
  });
704
711
  return { status: res.status, body: await res.text() };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.472",
3
+ "version": "1.3.475",
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",
@@ -0,0 +1,665 @@
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
+ }
@@ -0,0 +1,31 @@
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))