omni-notify-mcp 1.3.459 → 1.3.460

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.
@@ -8,6 +8,7 @@ import { createHash } from "crypto";
8
8
  import { existsSync, mkdirSync, readFileSync } from "fs";
9
9
  import { dirname, join } from "path";
10
10
  import { CONFIG_DIR, deliveryReport, isDndActive } from "../notify.js";
11
+ import { MESSENGER_SETUPS } from "../messaging/setup.js";
11
12
  import { extensionModule } from "./extensionModule.js";
12
13
  import { GatewayError, conversationEnabled, setConversationEnabled, writeRecordFile } from "./conversationOwner.js";
13
14
  import { TELEGRAM_PARSE_MODES } from "../messaging/telegramFormat.js";
@@ -24,14 +25,15 @@ export const SETTINGS = [
24
25
  { path: ["desktop", "tts"], label: "Read aloud", kind: "toggle", hint: "On speaks each desktop notification out loud." },
25
26
  { path: ["desktop", "ttsVoice"], label: "Voice", kind: "text", hint: "Edge voice name, e.g. en-US-GuyNeural. Empty uses the default voice." },
26
27
  ] },
27
- { guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "Paste the token below — that switches Telegram on.", "Send your bot any message: BN binds that chat to you, and the chat is your BN agent from then on."], need: [["telegram.token"], ["telegram.chatIds"]] }, title: "✈️ Telegram", rows: [
28
+ { guide: { summary: "Create a bot (2 min)", steps: ["Open Telegram, search `@BotFather`.", "Send `/newbot` and follow the prompts; copy the token it gives you.", "Paste the token below — that switches Telegram on.", "Send your bot any message: BN binds that chat to you, and the chat is your BN agent from then on."], need: [["telegram.token"], ["telegram.chatIds"]] }, messenger: "telegram", title: "✈️ Telegram", rows: [
28
29
  { path: ["telegram", "enabled"], label: "Enabled", kind: "toggle" },
29
30
  { path: ["telegram", "token"], label: "Bot token", kind: "secret", hint: "From @BotFather after /newbot, shaped like 123456:ABC-DEF... Pasting it switches Telegram on; the first message you send the bot binds your chat." },
30
31
  { path: ["telegram", "parseMode"], label: "Formatting", kind: "choice", choices: TELEGRAM_PARSE_MODES, fallback: "HTML", hint: "HTML (default) turns an agent's markdown bold, italics, code, links and bullets into Telegram formatting. MarkdownV2 sends the text as written for Telegram's own markdown. none sends plain text." },
31
32
  ] },
32
- { guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, title: "💬 Slack", rows: [
33
+ { guide: { summary: "Connect Slack", steps: ["Go to api.slack.com/apps, open your app (or Create New App).", "Easiest: Incoming Webhooks, Add New Webhook to Workspace, pick the channel, copy the URL into Webhook URL.", "Or: OAuth & Permissions, add the chat:write scope, install the app, copy the Bot User OAuth Token (xoxb-), invite the bot to the channel, and list the channel id.", "Switch Enabled to On."], need: [["slack.botToken", "slack.webhookUrl"]] }, messenger: "slack", title: "💬 Slack", rows: [
33
34
  { path: ["slack", "enabled"], label: "Enabled", kind: "toggle" },
34
35
  { path: ["slack", "botToken"], label: "Bot token", kind: "secret", hint: "Starts with xoxb-. api.slack.com/apps, your app, OAuth & Permissions, Bot User OAuth Token. Needs the chat:write scope. Use this with Channels, or use the Webhook URL instead." },
36
+ { path: ["slack", "configToken"], label: "Configuration token", kind: "secret", hint: "Lets BN repair its own Slack app (scopes, the Messages tab). api.slack.com/apps, Your App Configuration Tokens, Generate Token." },
35
37
  { path: ["slack", "channels"], label: "Channels (comma-separated)", kind: "list", hint: "Channel ids like C0123ABCD (Slack: channel name, View channel details, bottom of the About tab). Invite the bot to each channel first." },
36
38
  { path: ["slack", "webhookUrl"], label: "Webhook URL", kind: "secret", hint: "Simplest option: https://hooks.slack.com/services/... from your app, Incoming Webhooks, Add New Webhook to Workspace." },
37
39
  ] },
@@ -277,6 +279,8 @@ export function panelState() {
277
279
  conversation: conversationSwitchRead(),
278
280
  groups: unreadable !== undefined ? [] : SETTINGS.map((g) => ({
279
281
  title: g.title,
282
+ setup: g.messenger === undefined ? undefined : MESSENGER_SETUPS.view(g.messenger),
283
+ messenger: g.messenger,
280
284
  guide: g.guide === undefined ? undefined : { summary: g.guide.summary, steps: g.guide.steps, next: nextStep(g, cfg) },
281
285
  rows: g.rows.map((r) => ({ path: r.path, label: r.label, kind: r.kind, hint: r.hint, choices: r.choices, value: readAt(cfg, r.path) ?? r.fallback })),
282
286
  })),
@@ -301,3 +305,9 @@ export function saveConversationSwitch(enabled) {
301
305
  setConversationEnabled(enabled);
302
306
  return { enabled };
303
307
  }
308
+ /** The Reinstall press: the same reconcile BN runs at its start, run now for one messenger, answered with what is intended, installed, repaired and still missing. */
309
+ export async function reinstallMessenger(messenger) {
310
+ if (messenger !== "slack" && messenger !== "telegram")
311
+ throw new GatewayError(400, "expected slack or telegram");
312
+ return MESSENGER_SETUPS.reconcile(messenger);
313
+ }
@@ -203,6 +203,19 @@ function control(row) {
203
203
  }
204
204
  return wrap;
205
205
  }
206
+ function setupText(r) { return ["Intent:"].concat(r.intent.map(function (x) { return "• " + x; }), ["Installed:"], r.installed.length ? r.installed.map(function (x) { return "• " + x; }) : ["• nothing yet"], r.repaired.length ? ["Repaired just now:"].concat(r.repaired.map(function (x) { return "• " + x; })) : [], r.gaps.length ? ["Still missing:"].concat(r.gaps.map(function (x) { return "• " + x; })) : []).join("\n"); }
207
+ function setupRow(g) {
208
+ var row = el("tr"), cell = el("td"), button = el("button", "", "🔁 Reinstall"), detail = el("pre", "hint");
209
+ button.title = "Makes what is installed match what is set above, and shows both";
210
+ detail.textContent = g.setup && g.setup.last ? setupText({ intent: g.setup.intent, installed: g.setup.last.installed, repaired: g.setup.last.repaired, gaps: g.setup.last.gaps }) : "Intent:\n" + (g.setup ? g.setup.intent.map(function (x) { return "• " + x; }).join("\n") : "");
211
+ button.onclick = async function () {
212
+ button.disabled = true;
213
+ try { var r = await call("POST", "/v1/messenger-setup", { messenger: g.messenger }); detail.textContent = setupText(r); say(r.gaps.length ? "error" : "good", r.gaps.length ? "⚠️ " + g.title + " still lacks " + r.gaps.length + " thing(s) — see the list" : "✅ " + g.title + " installed to match your settings"); }
214
+ catch (e) { say("error", "❌ " + g.title + " reinstall failed — " + plainWhy(e)); }
215
+ button.disabled = false;
216
+ };
217
+ cell.colSpan = 2; cell.append(button, detail); row.append(cell); return row;
218
+ }
206
219
  function shownOf(s) { return JSON.stringify([s.state, s.conversation, s.groups, s.configPath]); }
207
220
  function draw(s) {
208
221
  drawn = shownOf(s);
@@ -224,6 +237,7 @@ function draw(s) {
224
237
  var d = el("details"); d.append(el("summary", "", g.guide.summary)); var ol = el("ol"); g.guide.steps.forEach(function (t) { ol.append(el("li", "", t.replace(/\`/g, ""))); }); d.append(ol);
225
238
  td.append(d, el("div", "next", g.guide.next)); tr.append(td); table.append(tr);
226
239
  }
240
+ if (g.messenger) table.append(setupRow(g));
227
241
  g.rows.forEach(function (r) {
228
242
  var row = el("tr"), name = el("td", "name", r.label), cell = el("td"); cell.append(control(r));
229
243
  if (r.hint) cell.append(el("div", "hint", r.hint));
@@ -16,7 +16,7 @@ import { handleMcp } from "./mcpDoor.js";
16
16
  import { MCP_PATH, accessGranted, challenge, handleOAuth, isOAuthPath, publicBase } from "./oauthDoor.js";
17
17
  import { bearer, bearerAdmitted, fromThisMachine, handlePasskey, isPasskeyPath, localOnly, refusalOfRequest } from "./passkeyDoor.js";
18
18
  import { terminalConsole, terminalFile, terminalRoute, terminalSockets } from "./terminalDoor.js";
19
- import { configFile, conversationSwitchRead, panelState, saveConfigFile, saveConversationSwitch, saveSetting } from "./panel.js";
19
+ import { configFile, conversationSwitchRead, panelState, reinstallMessenger, saveConfigFile, saveConversationSwitch, saveSetting } from "./panel.js";
20
20
  import { PANEL_PAGES, panelHtml } from "./panelPage.js";
21
21
  import { configureMcpHosts } from "./mcpHosts.js";
22
22
  import { readGatewayInstall, readNewestGatewayInstall, startGatewayInstall } from "./gatewayInstall.js";
@@ -117,6 +117,8 @@ async function route(req, url, arrivedAt) {
117
117
  return { status: 200, body: parts.length === 3 ? saveConfigFile(body.text, body.opened) : saveSetting(body.path, body.value) };
118
118
  }
119
119
  }
120
+ if (resource === "messenger-setup" && parts.length === 2 && method === "POST")
121
+ return { status: 200, body: await reinstallMessenger((await readJson(req)).messenger) };
120
122
  if (resource === "conversation-switch" && parts.length === 2) {
121
123
  if (method === "GET")
122
124
  return { status: 200, body: conversationSwitchRead() };
@@ -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 };
@@ -0,0 +1,31 @@
1
+ /** The one setup path both messengers use: BN's start and the UI's Reinstall run the same reconcile. */
2
+ class MessengerSetups {
3
+ setups = new Map();
4
+ lastReports = new Map();
5
+ add(setup) {
6
+ this.setups.set(setup.name, setup);
7
+ }
8
+ of(name) {
9
+ const setup = this.setups.get(name);
10
+ if (setup === undefined)
11
+ throw new Error(`no messenger named ${name} has a setup; known: ${[...this.setups.keys()].join(", ")}`);
12
+ return setup;
13
+ }
14
+ /** The intent of one messenger beside its last report, for the page to draw. */
15
+ view(name) {
16
+ const setup = this.setups.get(name);
17
+ return setup === undefined ? undefined : { intent: setup.intent(), last: this.lastReports.get(name) };
18
+ }
19
+ async reconcile(name) {
20
+ const report = await this.of(name).reconcile();
21
+ this.lastReports.set(name, report);
22
+ return report;
23
+ }
24
+ async reconcileAll() {
25
+ const reports = [];
26
+ for (const name of this.setups.keys())
27
+ reports.push(await this.reconcile(name));
28
+ return reports;
29
+ }
30
+ }
31
+ export const MESSENGER_SETUPS = new MessengerSetups();
@@ -0,0 +1,61 @@
1
+ import { SlackRefused, slackCall } from "./messenger.js";
2
+ /** Every bot scope BN's Slack side uses: the DM chat (im:*, chat:write), the bus channel (channels:*, groups:*) and finding Meni (users:read). */
3
+ export const SLACK_BOT_SCOPES = ["chat:write", "channels:history", "channels:read", "channels:join", "groups:history", "groups:read", "im:history", "im:read", "im:write", "users:read", "incoming-webhook"];
4
+ /** The app BN needs, as Slack's manifest states it: a bot user people can message from the App Home Messages tab, with every scope above. */
5
+ export function slackAppManifest(name) {
6
+ return {
7
+ display_information: { name, description: "Talk to your agents from Slack" },
8
+ features: {
9
+ bot_user: { display_name: name, always_online: true },
10
+ app_home: { home_tab_enabled: false, messages_tab_enabled: true, messages_tab_read_only_enabled: false },
11
+ },
12
+ oauth_config: { scopes: { bot: [...SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook")] } },
13
+ settings: { org_deploy_enabled: false, socket_mode_enabled: false, token_rotation_enabled: false },
14
+ };
15
+ }
16
+ /** The things the Slack setup still lacks after every repair BN can make itself; each names the one act left. */
17
+ export class SlackSetupGaps extends Error {
18
+ gaps;
19
+ constructor(gaps) {
20
+ super(gaps.join("; "));
21
+ this.gaps = gaps;
22
+ }
23
+ }
24
+ /** Reads who the token is and what it may do: auth.test's granted scopes (a response header), then the app behind the bot. */
25
+ export async function slackStanding(base, token) {
26
+ const auth = await fetch(`${base}/auth.test`, { method: "POST", headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(15_000) });
27
+ const body = await auth.json();
28
+ if (body.ok !== true)
29
+ throw new SlackRefused("auth.test", String(body.error ?? "unknown"));
30
+ const granted = String(auth.headers.get("x-oauth-scopes") ?? "").split(",").map((s) => s.trim()).filter((s) => s !== "");
31
+ const bot = (await slackCall(base, token, "bots.info", { bot: String(body.bot_id) })).bot;
32
+ return { appId: bot.app_id, botName: bot.name, granted };
33
+ }
34
+ /**
35
+ * Brings the Slack app to the manifest above through Slack's own app-configuration API, which needs the configuration token of BN settings.
36
+ * Slack asks the workspace owner to approve changed scopes, so a repair that changed them names the one tap left: the reinstall.
37
+ */
38
+ async function repairManifest(base, configToken, standing, wanted) {
39
+ const current = (await slackCall(base, configToken, "apps.manifest.export", { app_id: standing.appId })).manifest;
40
+ const declared = current.oauth_config?.scopes?.bot ?? [];
41
+ const scopesWhole = wanted.oauth_config.scopes.bot.every((s) => declared.includes(s));
42
+ const messagesOpen = current.features?.app_home?.messages_tab_enabled === true && current.features?.app_home?.messages_tab_read_only_enabled === false;
43
+ if (scopesWhole && messagesOpen && current.features?.bot_user !== undefined)
44
+ return [];
45
+ const merged = { ...current, features: { ...current.features, bot_user: current.features?.bot_user ?? wanted.features.bot_user, app_home: { ...current.features?.app_home, ...wanted.features.app_home } }, oauth_config: { ...current.oauth_config, scopes: { ...current.oauth_config?.scopes, bot: [...new Set([...declared, ...wanted.oauth_config.scopes.bot])] } } };
46
+ await slackCall(base, configToken, "apps.manifest.update", { app_id: standing.appId, manifest: JSON.stringify(merged) });
47
+ return [`the Slack app ${standing.botName} was updated to hold every scope and the Messages tab; Slack needs the workspace owner to approve it once: open https://api.slack.com/apps/${standing.appId}/install-on-team and tap Reinstall`];
48
+ }
49
+ /**
50
+ * The check BN makes of its own Slack setup: the token's standing, then the repair of what is missing through the same code. Returns what is still
51
+ * missing, each item naming the one act left — empty when the setup is whole.
52
+ */
53
+ export async function slackVerifyAndRepair(base, token, configToken, appName) {
54
+ const standing = await slackStanding(base, token);
55
+ const missing = SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook" && !standing.granted.includes(s));
56
+ if (configToken === undefined) {
57
+ const gaps = missing.length === 0 ? [] : [`the Slack app ${standing.botName} lacks the scopes ${missing.join(", ")} and BN holds no Slack configuration token to repair it: create one at https://api.slack.com/apps (Your App Configuration Tokens) and paste it into BN settings, Slack, Configuration token`];
58
+ return { standing, gaps };
59
+ }
60
+ return { standing, gaps: await repairManifest(base, configToken, standing, slackAppManifest(appName)) };
61
+ }
package/dist/notify.js CHANGED
@@ -25,6 +25,8 @@ import { postTelegramMessage, telegramParseMode } from "./messaging/telegramForm
25
25
  import { splitForNotify, withLead } from "./chunk.js";
26
26
  import { idleNow, playVoice, showBanner } from "./desk.js";
27
27
  import { AgentGateway, AGENT_PREFIX, chatTurnText, SLACK_DM, streamedChat } from "./agentGateway.js";
28
+ import { slackVerifyAndRepair } from "./messaging/slackSetup.js";
29
+ import { MESSENGER_SETUPS } from "./messaging/setup.js";
28
30
  import { SlackMessenger, SlackRefused, SlackUnknown, SlackUnreachable, slackCall, TelegramMessenger, TelegramRefused, TelegramUnknown, TelegramUnreachable, telegramCall } from "./messaging/messenger.js";
29
31
  import { PollCursors, DiscordPlatform, TeamsPlatform, NtfyPlatform, SmsPlatform, listenForever, pollForever } from "./messaging/chatInbound.js";
30
32
  import { EmailAgentInbox } from "./messaging/emailInbound.js";
@@ -1536,7 +1538,8 @@ function slackCreds(secrets = loadSecrets()) {
1536
1538
  const token = (process.env.SLACK_BOT_TOKEN ?? s.botToken ?? cfgSlack.botToken ?? "").trim() || undefined;
1537
1539
  const channel = (process.env.SLACK_CHANNEL_ID ?? s.channelId ?? "").trim() || undefined;
1538
1540
  const webhook = (s.webhookUrl ?? cfgSlack.webhookUrl ?? "").trim() || undefined;
1539
- return { token, channel, webhook };
1541
+ const configToken = (process.env.SLACK_CONFIG_TOKEN ?? s.configToken ?? cfgSlack.configToken ?? "").trim() || undefined;
1542
+ return { token, channel, webhook, configToken };
1540
1543
  }
1541
1544
  // Brainless config: on startup, copy any credentials already present in the
1542
1545
  // secrets file (decoded) into config.json's EMPTY fields, so a user who has the
@@ -2115,14 +2118,44 @@ const slackSwitchedOn = () => loadConfig().slack?.enabled === true;
2115
2118
  const slackDms = new Map();
2116
2119
  /** Why the direct message cannot be read with this bot token; it is not tried again until the token changes or BN restarts. */
2117
2120
  let slackDmOff;
2121
+ /** Slack's standing of each bot token as the setup check found it, read once per process; what the setup still lacks is logged once and kept for the status surface. */
2122
+ const slackSetupChecked = new Map();
2123
+ function slackSetupOf(token) {
2124
+ const known = slackSetupChecked.get(token);
2125
+ // NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
2126
+ if (known !== undefined)
2127
+ return known;
2128
+ const checked = slackVerifyAndRepair(SLACK_API_BASE, token, slackCreds().configToken, "BN").then(({ standing, gaps }) => {
2129
+ log("·", "slack", `setup: app ${standing.botName} holds ${standing.granted.length} scopes${gaps.length === 0 ? ", nothing missing" : ""}`);
2130
+ for (const gap of gaps)
2131
+ log("·", "slack:error", `setup incomplete: ${gap}`);
2132
+ if (gaps.length > 0)
2133
+ slackLastError = gaps.join("; ");
2134
+ return standing;
2135
+ });
2136
+ slackSetupChecked.set(token, checked);
2137
+ // OWNER: the setup check is read once per token — a check that failed is forgotten so the next poll asks Slack again, and its failure reaches the poll loop that awaits it.
2138
+ checked.catch(() => slackSetupChecked.delete(token));
2139
+ return checked;
2140
+ }
2141
+ /** Opens the direct message with the owner: conversations.open when the app holds im:write, else Slack's own opening by a first post to his id, which needs only chat:write. */
2142
+ async function openSlackDm(token, owner, standing) {
2143
+ if (standing.granted.includes("im:write"))
2144
+ return String((await slackCall(SLACK_API_BASE, token, "conversations.open", { users: owner })).channel.id);
2145
+ const opened = await slackCall(SLACK_API_BASE, token, "chat.postMessage", { channel: owner, text: "Hi Meni, this is your BN chat. Type here to talk to your agents." });
2146
+ return String(opened.channel);
2147
+ }
2118
2148
  /** Meni's direct-message chat with the bot: the workspace owner's, opened with conversations.open. */
2119
2149
  async function slackDmOf(token, owner) {
2120
2150
  const known = slackDms.get(token);
2121
2151
  // NULL-OK: field known is OPTIONAL and therefore it is ok to check for NULL
2122
2152
  if (known !== undefined)
2123
2153
  return known;
2124
- const opened = await slackCall(SLACK_API_BASE, token, "conversations.open", { users: owner });
2125
- const dm = new SlackMessenger(SLACK_API_BASE, token, String(opened.channel.id), slackSwitchedOn);
2154
+ const standing = await slackSetupOf(token);
2155
+ const remembered = POLL_CURSORS.get(`slack-dm-channel:${owner}`);
2156
+ const channel = remembered ?? await openSlackDm(token, owner, standing);
2157
+ POLL_CURSORS.set(`slack-dm-channel:${owner}`, channel);
2158
+ const dm = new SlackMessenger(SLACK_API_BASE, token, channel, slackSwitchedOn);
2126
2159
  slackDms.set(token, dm);
2127
2160
  log("·", "slack", `direct message ${dm.channel} with the workspace owner is a BN conversation: every message he sends the bot there reaches it`);
2128
2161
  return dm;
@@ -2250,6 +2283,113 @@ function smsPlatform() {
2250
2283
  const queue = () => new SQSClient(awsCredentials(loadConfig()));
2251
2284
  return new SmsPlatform(settings, queue, send, e164, log);
2252
2285
  }
2286
+ // ── Messenger setup: what is installed reconciled against what Meni configured ─────────────────
2287
+ const freshReport = (messenger, intent) => ({ messenger, intent, installed: [], repaired: [], gaps: [], at: Date.now() });
2288
+ const slackSetup = {
2289
+ name: "slack",
2290
+ intent() {
2291
+ const c = loadConfig().slack ?? {};
2292
+ if (c.enabled !== true)
2293
+ return ["Slack is switched off"];
2294
+ return ["Slack is switched on", `the bus channel ${[...new Set([...(c.channels ?? []), slackCreds().channel].filter((x) => x))].join(", ") || "(none chosen)"}`, "a direct message between the bot and the workspace owner"];
2295
+ },
2296
+ async reconcile() {
2297
+ const report = freshReport("slack", this.intent());
2298
+ if (!slackSwitchedOn())
2299
+ return report;
2300
+ const { token, configToken } = slackCreds();
2301
+ if (token === undefined) {
2302
+ report.gaps.push("no Slack bot token is set in BN settings");
2303
+ return report;
2304
+ }
2305
+ slackSetupChecked.delete(token);
2306
+ slackDmOff = undefined;
2307
+ const { standing, gaps } = await slackVerifyAndRepair(SLACK_API_BASE, token, configToken, "BN");
2308
+ slackSetupChecked.set(token, Promise.resolve(standing));
2309
+ report.installed.push(`the Slack app ${standing.botName} holds ${standing.granted.length} scopes`);
2310
+ report.gaps.push(...gaps);
2311
+ try {
2312
+ const owner = await slackOwner(token);
2313
+ const had = POLL_CURSORS.get(`slack-dm-channel:${owner}`) !== undefined;
2314
+ const dm = await slackDmOf(token, owner);
2315
+ (had ? report.installed : report.repaired).push(`the direct message ${dm.channel} between the bot and the workspace owner is open`);
2316
+ }
2317
+ catch (err) {
2318
+ if (!(err instanceof SlackOwnerUnknown) && !(err instanceof SlackRefused))
2319
+ throw err;
2320
+ // OWNER: the setup pass is its own trigger root — a refusal Slack documents is a gap in the report, naming what Slack said.
2321
+ report.gaps.push(err.message);
2322
+ }
2323
+ for (const channel of [...new Set([...(loadConfig().slack?.channels ?? []), slackCreds().channel].filter((x) => !!x))]) {
2324
+ try {
2325
+ await slackCall(SLACK_API_BASE, token, "conversations.history", { channel, limit: 1 });
2326
+ report.installed.push(`the bot is in the bus channel ${channel}`);
2327
+ }
2328
+ catch (err) {
2329
+ if (!(err instanceof SlackRefused) || err.error !== "not_in_channel") {
2330
+ if (err instanceof SlackRefused) {
2331
+ report.gaps.push(err.message);
2332
+ continue;
2333
+ }
2334
+ throw err;
2335
+ }
2336
+ // OWNER: the setup pass is its own trigger root — a bot outside its bus channel joins it, or the gap names the scope or invitation that is missing.
2337
+ if (standing.granted.includes("channels:join")) {
2338
+ await slackCall(SLACK_API_BASE, token, "conversations.join", { channel });
2339
+ report.repaired.push(`the bot joined the bus channel ${channel}`);
2340
+ }
2341
+ else
2342
+ report.gaps.push(`the bot is not in the bus channel ${channel}: invite it there, or let BN add the channels:join scope`);
2343
+ }
2344
+ }
2345
+ return report;
2346
+ },
2347
+ };
2348
+ const telegramSetup = {
2349
+ name: "telegram",
2350
+ intent() {
2351
+ const c = loadConfig().telegram ?? {};
2352
+ return c.enabled !== true ? ["Telegram is switched off"] : ["Telegram is switched on", `his chat with the bot (${(c.chatIds ?? []).length === 0 ? "the first chat that writes" : c.chatIds.join(", ")})`, "the bot reads by polling, so no webhook stands in its way"];
2353
+ },
2354
+ async reconcile() {
2355
+ const report = freshReport("telegram", this.intent());
2356
+ const c = loadConfig().telegram ?? {};
2357
+ if (c.enabled !== true)
2358
+ return report;
2359
+ const token = String(c.token ?? "").trim();
2360
+ if (token === "") {
2361
+ report.gaps.push("no Telegram bot token is set in BN settings");
2362
+ return report;
2363
+ }
2364
+ const me = await telegramCall(tgApi(token, "getMe"), "getMe");
2365
+ report.installed.push(`the bot @${me.username} answers`);
2366
+ const hook = await telegramCall(tgApi(token, "getWebhookInfo"), "getWebhookInfo");
2367
+ if (String(hook.url ?? "") === "")
2368
+ report.installed.push("no webhook stands in the way of polling");
2369
+ else {
2370
+ await telegramCall(tgApi(token, "deleteWebhook"), "deleteWebhook");
2371
+ report.repaired.push("a webhook that blocked polling was removed");
2372
+ }
2373
+ return report;
2374
+ },
2375
+ };
2376
+ MESSENGER_SETUPS.add(slackSetup);
2377
+ MESSENGER_SETUPS.add(telegramSetup);
2378
+ /** The one start-time pass: every messenger's setup reconciles once, each report logged; a refusal or an unreachable service is said and the daemon goes on. */
2379
+ async function reconcileMessengersAtStart() {
2380
+ for (const name of ["slack", "telegram"]) {
2381
+ try {
2382
+ const r = await MESSENGER_SETUPS.reconcile(name);
2383
+ log("·", name, `setup: ${r.installed.length} in place, ${r.repaired.length} repaired, ${r.gaps.length} missing${r.gaps.length > 0 ? ` — ${r.gaps.join("; ")}` : ""}`);
2384
+ if (name === "slack" && r.gaps.length > 0)
2385
+ slackRecordFailed(new Error(r.gaps.join("; ")));
2386
+ }
2387
+ catch (err) {
2388
+ // OWNER: the daemon's start is the trigger root of this pass — a messenger whose setup could not be read (Slack or Telegram out of reach, a revoked token) is logged with its reason and the others still reconcile.
2389
+ log("·", `${name}:error`, `setup could not be checked: ${err instanceof Error ? err.message : String(err)}`);
2390
+ }
2391
+ }
2392
+ }
2253
2393
  // ── The channel pollers: run by the gateway owner, and stopped when it hands the gateway over ────────────────
2254
2394
  let pollersWanted = false;
2255
2395
  let pollerRuns = [];
@@ -2257,6 +2397,7 @@ let inboundPlatforms;
2257
2397
  let mailInbox;
2258
2398
  function startPollers() {
2259
2399
  pollersWanted = true;
2400
+ void reconcileMessengersAtStart();
2260
2401
  inboundPlatforms ??= [[discordPlatform(), 2000], [teamsPlatform(), 5000], [ntfyPlatform(), 2000], [smsPlatform(), 0]];
2261
2402
  const inbox = (mailInbox ??= emailAgentInbox());
2262
2403
  pollerRuns = [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.459",
3
+ "version": "1.3.460",
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))