omni-notify-mcp 1.3.460 → 1.3.461

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.
@@ -15,7 +15,7 @@ import { homedir } from "os";
15
15
  import { join } from "path";
16
16
  import { splitForNotify } from "./chunk.js";
17
17
  import { choicesOf, StreamedReply } from "./messaging/messenger.js";
18
- import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, updateConversation, } from "./gateway/conversationOwner.js";
18
+ import { appendEvent, archiveConversation, conversationRefusal, openConversation, readConversation, createdIn, creationPending, creationsPending, editOwed, GatewayError, listConversations, monotonicMs, openConversationOf, openConversationsOf, queueNoticeOf, readEvents, resolveProject, rootFolder, routeAsk, stopTargetOf, sendToConversation, startConversation, turnInFlight, updateConversation, } from "./gateway/conversationOwner.js";
19
19
  import { conversationOwner } from "./gateway/conversationOwner.js";
20
20
  import { clearOpenCodeLogs } from "./gateway/conversationOwner.js";
21
21
  import { resendUndelivered, turnEnded } from "./gateway/mcpEvents.js";
@@ -29,7 +29,7 @@ async function endNewest(key, _platform, end) {
29
29
  const stay = this.allOf(key).length;
30
30
  return stay === 0 ? "🆕 New conversation. Your next ! message starts it." : `🆕 Newest conversation ended. ${stay} other conversation${stay === 1 ? " stays" : "s stay"} open.`;
31
31
  }
32
- const stoppedOfMany = (stopped, others) => others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`;
32
+ const stoppedOfMany = ([stopped], others) => others === 0 ? "⏹ Conversation ended. Your next ! message opens a new one." : `⏹ Conversation ${stopped.id.slice(0, 8)} ended. ${others} other conversation${others === 1 ? " stays" : "s stay"} open.`;
33
33
  /** Each carried event of a turn sent as its parts. */
34
34
  function partsRelay(reply, carriage) {
35
35
  return {
@@ -45,32 +45,55 @@ function partsRelay(reply, carriage) {
45
45
  const CHAT = {
46
46
  conversationOf: openConversationOf,
47
47
  routeOf: routeAsk,
48
- stopOf: stopTargetOf,
48
+ stopOf: (key) => [stopTargetOf(key)].filter((c) => c !== undefined),
49
49
  allOf: openConversationsOf,
50
50
  carries: (kind) => kind !== "returned",
51
51
  parts: (event) => (event.kind === "answer" ? splitForNotify(event.text) : [event.text]),
52
52
  stopped: stoppedOfMany,
53
53
  renew: endNewest,
54
54
  folderOf: (text) => resolveProject(undefined, text),
55
+ forkOf: () => undefined,
55
56
  };
56
- /** Meni's one private chat with the bot (#4453): its newest conversation not deleted — an idle archive keeps it bound, only /new replaces it. */
57
- const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted");
58
- /** The bound chat: ONE conversation at the workspace root, every message goes on with it, a stop pauses it, /new opens the next one at once. */
57
+ /** Meni's one private chat with the bot (#4453): its main conversation, the newest not deleted and not forked beside another — an idle archive keeps it bound, only /new replaces it. */
58
+ const boundOf = (key) => listConversations().find((c) => c.chat === key && c.shelf !== "deleted" && c.forkOf === undefined);
59
+ /** The conversations forked beside the bound chat's main one while it was busy (#4584), newest first; a stopped or put-away one is done. */
60
+ const sidesOf = (key) => listConversations().filter((c) => c.chat === key && c.forkOf !== undefined && c.state !== "closed" && c.shelf === undefined);
61
+ /** A conversation in the middle of a turn, or holding a message stored for its next one. */
62
+ const busy = (c) => turnInFlight(readEvents(c.id), c) !== undefined;
63
+ /** The bound chat's main conversation while it is free (#4584); while it is busy undefined, so the message runs at once in a new conversation forked from it and never waits behind the reply under way. */
64
+ const freeBound = (key) => {
65
+ const main = boundOf(key);
66
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
67
+ return main === undefined || !busy(main) ? main : undefined;
68
+ };
69
+ /** The bound chat: ONE main conversation at the workspace root, every message goes on with it, or beside it in a fork while it is busy (#4584); a stop pauses the one at work, /new opens the next one at once. */
59
70
  const ONE = {
60
71
  conversationOf: boundOf,
61
- routeOf: boundOf,
62
- stopOf: boundOf,
63
- allOf: (key) => [boundOf(key)].filter((c) => c !== undefined),
72
+ routeOf: freeBound,
73
+ stopOf: (key) => {
74
+ const working = ONE.allOf(key).filter(busy);
75
+ return working.length > 0 ? working : [boundOf(key)].filter((c) => c !== undefined);
76
+ },
77
+ allOf: (key) => [boundOf(key), ...sidesOf(key)].filter((c) => c !== undefined),
64
78
  carries: CHAT.carries,
65
79
  parts: CHAT.parts,
66
- stopped: () => "⏹ Stopped. Your next message picks the conversation up where it stopped.",
80
+ stopped: (stopped) => {
81
+ const forks = stopped.filter((c) => c.forkOf !== undefined).length;
82
+ const parallel = `${forks} parallel conversation${forks === 1 ? "" : "s"}`;
83
+ if (forks === stopped.length)
84
+ return `⏹ Stopped ${parallel}.`;
85
+ return `⏹ Stopped${forks === 0 ? "" : `, with ${parallel}`}. Your next message picks the conversation up where it stopped.`;
86
+ },
67
87
  folderOf: () => rootFolder(),
88
+ forkOf: (key) => {
89
+ const main = boundOf(key);
90
+ // NULL-OK: field main is OPTIONAL and therefore it is ok to check for NULL
91
+ return main !== undefined && busy(main) ? main.sessionId : undefined;
92
+ },
68
93
  async renew(key, platform, end) {
69
- const bound = boundOf(key);
70
- // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
71
- if (bound !== undefined) {
72
- end(bound.id);
73
- archiveConversation(bound.id);
94
+ for (const c of ONE.allOf(key)) {
95
+ end(c.id);
96
+ archiveConversation(c.id);
74
97
  }
75
98
  const { notice } = await createdIn(rootFolder(), undefined, () => key, (on) => openConversation({ platform, chat: key, ...on }));
76
99
  // NULL-OK: field notice is OPTIONAL and therefore it is ok to check for NULL
@@ -83,13 +106,14 @@ const THREADS_ONE = (key) => listConversations().find((c) => c.chat === key);
83
106
  const MAIL = {
84
107
  conversationOf: THREADS_ONE,
85
108
  routeOf: THREADS_ONE,
86
- stopOf: THREADS_ONE,
109
+ stopOf: (key) => [THREADS_ONE(key)].filter((c) => c !== undefined),
87
110
  allOf: (key) => listConversations().filter((c) => c.chat === key),
88
111
  carries: (kind) => MAILED_KINDS.has(kind),
89
112
  parts: (event) => [event.text],
90
113
  stopped: stoppedOfMany,
91
114
  renew: endNewest,
92
115
  folderOf: (text) => resolveProject(undefined, text),
116
+ forkOf: () => undefined,
93
117
  };
94
118
  const CARRIAGE = { telegram: ONE, slack: CHAT, discord: CHAT, teams: CHAT, ntfy: CHAT, sms: CHAT, email: MAIL };
95
119
  /** The key of Meni's direct-message chat with the bot on Slack (#4453): one conversation, as his Telegram chat is; a Slack channel thread keeps its own. */
@@ -227,18 +251,20 @@ export class AgentGateway {
227
251
  await pending;
228
252
  const open = carriage.conversationOf(key);
229
253
  if (act.kind === "stop") {
230
- const stopped = carriage.stopOf(key);
231
- // NULL-OK: field stopped is OPTIONAL and therefore it is ok to check for NULL
232
- if (stopped === undefined)
254
+ const pressed = carriage.allOf(key).filter((c) => c.id === act.conversation);
255
+ const stopped = pressed.length > 0 ? pressed : carriage.stopOf(key);
256
+ if (stopped.length === 0)
233
257
  return reply("Nothing to stop here — no conversation is open.");
234
- this.end(stopped.id);
235
- return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => c.id !== stopped.id).length));
258
+ for (const c of stopped)
259
+ this.end(c.id);
260
+ return reply(carriage.stopped(stopped, carriage.allOf(key).filter((c) => !stopped.includes(c)).length));
236
261
  }
237
262
  if (act.kind === "new")
238
263
  return reply(await carriage.renew(key, platform, (id) => this.end(id)));
239
264
  if (act.text === "")
240
265
  return reply("Send `! <your message>` to talk to the agent.");
241
266
  const target = carriage.routeOf(key, act.text);
267
+ const forkOf = carriage.forkOf(key);
242
268
  // NULL-OK: field target is OPTIONAL and therefore it is ok to check for NULL
243
269
  if (target === undefined) {
244
270
  let project;
@@ -256,7 +282,7 @@ export class AgentGateway {
256
282
  const slack = origin.slack !== undefined && open?.slack !== undefined ? { ...origin.slack, readTs: open.slack.readTs } : origin.slack;
257
283
  const turn = {};
258
284
  const [creation] = await Promise.allSettled([createdIn(project, undefined, () => key, (on) => {
259
- const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, text: act.text, receivedMs: monotonicMs() - arrived });
285
+ const created = startConversation({ platform, chat: key, slack, email: origin.email, ...on, forkOf, text: act.text, receivedMs: monotonicMs() - arrived });
260
286
  // NULL-OK: field open is OPTIONAL and therefore it is ok to check for NULL
261
287
  const told = open === undefined ? [] : [this.told(created.id, 1, `🆕 An independent ask: it runs in its own conversation ${created.id.slice(0, 8)} while ${open.id.slice(0, 8)} keeps working.`)];
262
288
  turn.answered = this.awaitTurn(created.id, 1, relayOf(created.id, 1, false), told);
@@ -362,12 +388,27 @@ const chatBrief = (messenger) => `You are BN's agent in Meni's one ${messenger}
362
388
  Start every reply with a short bracketed label for the work it is about — the story id ([#4453]), the project ([AlphaWave]) or a few words — so he never has to pick a thread: you decide which work each message is about.
363
389
  The chat shows bold, italic, code, links, bullets and emojis, never tables; keep replies short. Your reply already reaches the chat — never also send it with the notify tool.
364
390
  Never use the AskUserQuestion tool here: its question stays on a screen he cannot see. To ask him, end the reply with the question and one line per choice starting with 🔘 — each becomes a choice he taps, and he may answer in his own words instead.`;
365
- /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, then what the chat knows around it, then his own words, last. */
391
+ /** What a message forked beside the busy main conversation is told (#4584), about 70 tokens. */
392
+ const BESIDE = "(BN: the main conversation of this chat is still busy on an earlier message of his, so this one runs at once beside it, in a parallel conversation. Answer this message only, under its own label, and leave the work under way to the main conversation.)";
393
+ /** The answers his chat got from the forked conversations since the main one last heard from him (#4584): the main one, and each new fork of it, reads them as part of the chat. */
394
+ function answeredBeside(key, main) {
395
+ const heard = readEvents(main.id).filter((e) => e.role === "user").at(-1)?.ts ?? main.createdAt;
396
+ const answers = listConversations()
397
+ .filter((c) => c.chat === key && c.forkOf !== undefined && c.shelf !== "deleted")
398
+ .flatMap((c) => readEvents(c.id).filter((e) => e.kind === "answer" && e.ts > heard))
399
+ .sort((x, y) => x.ts.localeCompare(y.ts));
400
+ return answers.length === 0 ? [] : [`(BN: while the main conversation worked, these answers reached his chat from conversations running beside it — read them as part of this chat:\n${answers.map((e) => `• «${e.text}»`).join("\n")})`];
401
+ }
402
+ /** The text one message of the bound chat is sent as: the brief on the conversation's first turn, what the chat was answered beside it and whether this one runs beside it, then what the chat knows around it, then his own words, last. */
366
403
  export function chatTurnText(key, text, context) {
404
+ const brief = chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram");
367
405
  const bound = boundOf(key);
368
406
  // NULL-OK: field bound is OPTIONAL and therefore it is ok to check for NULL
369
- const first = bound === undefined || !readEvents(bound.id).some((e) => e.role === "user");
370
- return [...(first ? [chatBrief(key.startsWith(SLACK_DM) ? "Slack" : "Telegram")] : []), ...context, text].join("\n\n");
407
+ if (bound === undefined)
408
+ return [brief, ...context, text].join("\n\n");
409
+ // A message beside a main conversation whose session is not written yet runs in a session of its own, which has not had the brief.
410
+ const first = !readEvents(bound.id).some((e) => e.role === "user") || (busy(bound) && !bound.started);
411
+ return [...(first ? [brief] : []), ...answeredBeside(key, bound), ...(busy(bound) ? [BESIDE] : []), ...context, text].join("\n\n");
371
412
  }
372
413
  /** The Claude CLI's own folder of session transcripts. */
373
414
  function claudeProjects() {
@@ -505,18 +546,30 @@ class TranscriptTail {
505
546
  }
506
547
  /** The draft of each streamed turn this process shows, one id per turn so no turn's preview lands on another's. */
507
548
  let draftIds = 0;
549
+ /** The conversation each draft still streaming belongs to, so his stop on one of the parallel replies stops that reply's conversation (#4584). */
550
+ const drafts = new Map();
551
+ /** The conversation whose reply streams in this draft, or undefined once its turn ended or when an earlier BN process drew it. */
552
+ export function conversationOfDraft(draft) {
553
+ return drafts.get(draft);
554
+ }
508
555
  /** The bound chat's turns as they happen (#4453): the working state at once, the agent's text and steps as a paced preview, the answer with its choices as buttons. */
509
556
  export function streamedChat(messenger, log) {
510
557
  return {
511
558
  say: (text) => messenger.send(text),
512
559
  turn(id, _n, queued) {
513
- const reply = new StreamedReply(messenger, ++draftIds, log);
560
+ const draft = ++draftIds;
561
+ drafts.set(draft, id);
562
+ const reply = new StreamedReply(messenger, draft, log);
514
563
  let tail;
515
564
  if (!queued)
516
565
  reply.begin();
517
- const close = () => {
566
+ const ended = () => {
567
+ drafts.delete(draft);
518
568
  // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
519
569
  tail?.stop();
570
+ };
571
+ const close = () => {
572
+ ended();
520
573
  reply.close();
521
574
  };
522
575
  return {
@@ -529,8 +582,7 @@ export function streamedChat(messenger, log) {
529
582
  tail ??= TranscriptTail.of(id, reply, log);
530
583
  return;
531
584
  case "answer": {
532
- // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
533
- tail?.stop();
585
+ ended();
534
586
  const { text, choices } = choicesOf(event.text);
535
587
  return reply.finish(text, choices.map((label, i) => ({ label, data: `b|${id.slice(0, 8)}|${i}` })));
536
588
  }
@@ -538,8 +590,7 @@ export function streamedChat(messenger, log) {
538
590
  case "stopped":
539
591
  case "archived":
540
592
  case "deleted":
541
- // NULL-OK: field tail is OPTIONAL and therefore it is ok to check for NULL
542
- tail?.stop();
593
+ ended();
543
594
  return reply.finish(event.text);
544
595
  case "returned":
545
596
  case "resumed":
@@ -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 };
@@ -54,7 +54,7 @@ export async function slackVerifyAndRepair(base, token, configToken, appName) {
54
54
  const standing = await slackStanding(base, token);
55
55
  const missing = SLACK_BOT_SCOPES.filter((s) => s !== "incoming-webhook" && !standing.granted.includes(s));
56
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`];
57
+ const gaps = missing.length === 0 ? [] : [`the Slack app ${standing.botName} lacks the scopes ${missing.join(", ")}, and BN cannot see or open its App Home Messages tab (without it Slack refuses a direct message to the bot with \"failed to send\"), because 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
58
  return { standing, gaps };
59
59
  }
60
60
  return { standing, gaps: await repairManifest(base, configToken, standing, slackAppManifest(appName)) };
package/dist/notify.js CHANGED
@@ -24,7 +24,7 @@ import { telegramSendErrorHint } from "./messaging/telegramError.js";
24
24
  import { postTelegramMessage, telegramParseMode } from "./messaging/telegramFormat.js";
25
25
  import { splitForNotify, withLead } from "./chunk.js";
26
26
  import { idleNow, playVoice, showBanner } from "./desk.js";
27
- import { AgentGateway, AGENT_PREFIX, chatTurnText, SLACK_DM, streamedChat } from "./agentGateway.js";
27
+ import { AgentGateway, AGENT_PREFIX, chatTurnText, conversationOfDraft, SLACK_DM, streamedChat } from "./agentGateway.js";
28
28
  import { slackVerifyAndRepair } from "./messaging/slackSetup.js";
29
29
  import { MESSENGER_SETUPS } from "./messaging/setup.js";
30
30
  import { SlackMessenger, SlackRefused, SlackUnknown, SlackUnreachable, slackCall, TelegramMessenger, TelegramRefused, TelegramUnknown, TelegramUnreachable, telegramCall } from "./messaging/messenger.js";
@@ -1205,7 +1205,7 @@ async function takeTelegramUpdate(token, update) {
1205
1205
  if (update.stopped_message_generation !== undefined) {
1206
1206
  const chat = String(update.stopped_message_generation.chat?.id ?? chatIds[0]);
1207
1207
  if (chatIds.includes(chat))
1208
- toTelegramConversation(token, chat, { kind: "stop" });
1208
+ toTelegramConversation(token, chat, { kind: "stop", conversation: conversationOfDraft(Number(update.stopped_message_generation.draft_id)) });
1209
1209
  return;
1210
1210
  }
1211
1211
  const msg = update.message;
@@ -1820,11 +1820,15 @@ function warnIfNoChannelConfigured(cfg) {
1820
1820
  // reply returned having sent nothing (#771).
1821
1821
  async function slackSend(text) {
1822
1822
  const { webhook, token, channel } = slackCreds();
1823
+ let webhookFailure = "";
1823
1824
  if (webhook) {
1824
1825
  const r = await fetch(webhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) });
1825
- if (!r.ok)
1826
- throw new Error(`slack webhook answered HTTP ${r.status} ${(await r.text().catch(() => "")).slice(0, 200)}`);
1827
- return;
1826
+ if (r.ok)
1827
+ return;
1828
+ webhookFailure = `slack webhook answered HTTP ${r.status} ${(await r.text().catch(() => "")).slice(0, 200)}`;
1829
+ if (!token || !(channel ?? (loadConfig().slack?.channels ?? [])[0]))
1830
+ throw new Error(webhookFailure);
1831
+ log("·", "slack:error", `${webhookFailure} — the reply goes through the bot token instead`);
1828
1832
  }
1829
1833
  // The bot token the Connect button saves has no channel of its own, so the
1830
1834
  // reply goes to the channel this config names for the app.
@@ -3263,12 +3263,12 @@ export function readQueueStore(board) {
3263
3263
  // NULL-OK: field stored is OPTIONAL and therefore it is ok to check for NULL
3264
3264
  return stored === undefined ? { v: STORY_QUEUE_WIRE, nextSeq: 1, entries: [] } : withoutRepeatedSteps(stored);
3265
3265
  }
3266
- /** 🔴 #4581 — the two ways work stands still that ask FleetView's stuck-work probe: Meni, 2026-11-27, *"fv for queue without agents and for bb stories without agents or queue"*. */
3266
+ /** 🔴 #4581 — the two ways work stands still that ask FleetView's progress checker: Meni, 2026-11-27, *"fv for queue without agents and for bb stories without agents or queue"*. */
3267
3267
  export const CLOG_TRIGGERS = ["queue without agents", "stories without agents or queue"];
3268
- // GATE: how long a stuck set must stand before the probe is asked — a pass about to start it, or a hand-over in flight, is never probed
3268
+ // GATE: how long a stuck set must stand before the progress check is asked — a pass about to start it, or a hand-over in flight, is never checked
3269
3269
  export const CLOG_SETTLE_MS = 5 * 60_000;
3270
3270
  const clogFile = (board, trigger) => path.join(storyQueueDir(board), "clog", `${trigger === "queue without agents" ? "fleetview" : "backlog"}.json`);
3271
- /** 🔴 #4581 — a trigger reports what stands still; its own file, its one writer. The set's `since` holds while the set is unchanged, so the probe sees how long it has stood; nothing is written when nothing changed. */
3271
+ /** 🔴 #4581 — a trigger reports what stands still; its own file, its one writer. The set's `since` holds while the set is unchanged, so the progress check sees how long it has stood; nothing is written when nothing changed. */
3272
3272
  export function reportClog(board, trigger, stuck, now) {
3273
3273
  const file = clogFile(board, trigger);
3274
3274
  const ids = [...new Set(stuck)].sort((a, b) => a - b);
@@ -3292,6 +3292,12 @@ export function queueClog(store) {
3292
3292
  return [];
3293
3293
  return store.entries.filter((e) => e.state === "queued" || e.state === "retrying" || e.state === "failed").map((e) => e.storyId);
3294
3294
  }
3295
+ /** 🔴 #4581 — the story's standing request is his Start press, still asking: a FleetView restart keeps its row in line, and AUTO START off still holds a row whose worker his press already started. */
3296
+ function inLineByHisPress(board, storyId) {
3297
+ const r = readableRequestView(board, storyId);
3298
+ // NULL-OK: field r is OPTIONAL and therefore it is ok to check for NULL
3299
+ return r !== undefined && r.origin === "press" && r.eligible;
3300
+ }
3295
3301
  function withdrawUntilAsked(board, e, now, why) {
3296
3302
  delete e.forced;
3297
3303
  delete e.forcedBy;
@@ -3313,9 +3319,10 @@ export async function clearStoryQueue(board, since) {
3313
3319
  // NULL-OK: field pressedAt is OPTIONAL and therefore it is ok to check for NULL
3314
3320
  return r !== undefined && r.origin === "press" && r.eligible && r.pressedAt !== undefined && (r.forced ?? r.pressedAt) > priorAuthorityOf(store.entries.find((e) => e.storyId === id));
3315
3321
  }));
3322
+ const pressedInLine = new Set(store.entries.filter((e) => IN_LINE.has(e.state) && inLineByHisPress(board, e.storyId)));
3316
3323
  // NULL-OK: field worker/archivedSessions/lastSession/handStop is OPTIONAL and therefore it is ok to check for NULL
3317
- const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.lastSession !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e));
3318
- const working = new Set([...kept.filter((e) => e.state === "starting" || e.state === "running" || (e.forceEventAt ?? 0) >= since || his.has(e)).map((e) => e.storyId), ...untaken]);
3324
+ const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.lastSession !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e) || pressedInLine.has(e));
3325
+ const working = new Set([...kept.filter((e) => e.state === "starting" || e.state === "running" || (e.forceEventAt ?? 0) >= since || his.has(e)).map((e) => e.storyId), ...[...pressedInLine].map((e) => e.storyId), ...untaken]);
3319
3326
  let removed = store.entries.length - kept.length;
3320
3327
  const now = Date.now();
3321
3328
  for (const e of kept) {
@@ -214,7 +214,7 @@ export function createClaudeDriver(runtime) {
214
214
  ...(atRoot ? runtime.store.listedFolders().flatMap((folder) => ["--add-dir", folder]) : []),
215
215
  ...(spec.model === undefined ? [] : ["--model", spec.model]),
216
216
  ...(spec.title === undefined || this.resumes ? [] : ["--name", spec.title]),
217
- ...(this.resumes ? ["--resume", spec.sessionId] : ["--session-id", spec.sessionId]),
217
+ ...(this.resumes ? ["--resume", spec.sessionId] : spec.forkOf !== undefined && transcriptWritten(spec.forkOf) ? ["--resume", spec.forkOf, "--fork-session", "--session-id", spec.sessionId] : ["--session-id", spec.sessionId]),
218
218
  "--permission-mode", "bypassPermissions", "--disallowedTools", BN_REACHES_HIM_ON_THE_PAGE, "--settings", settings,
219
219
  ], { CLAUDE_CODE_NO_FLICKER: "1", ...(atRoot ? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: "1" } : {}) });
220
220
  let draw;
@@ -831,7 +831,7 @@ export function createConversationStore(host, registry) {
831
831
  const beside = input.chat === undefined ? undefined : openConversationOf(input.chat)?.id;
832
832
  const meta = {
833
833
  id: randomUUID(), platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project: input.project, provider: input.provider, model: input.model,
834
- state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside,
834
+ state: input.state, createdAt: now, updatedAt: now, lastMessageAt: now, sessionId: randomUUID(), started: false, consumed: 0, beside, forkOf: input.forkOf,
835
835
  };
836
836
  writeMeta(meta);
837
837
  return meta;
@@ -841,7 +841,7 @@ export function createConversationStore(host, registry) {
841
841
  requireConversationEnabled();
842
842
  const project = createdFolder(input.project);
843
843
  const provider = namedProvider(input.provider);
844
- const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, provider, model: input.model, state: "queued" });
844
+ const meta = newConversation({ platform: input.platform, technical: input.technical, chat: input.chat, slack: input.slack, email: input.email, project, provider, model: input.model, forkOf: input.forkOf, state: "queued" });
845
845
  appendEvent(meta.id, { role: "user", text: input.text, receivedMs: input.receivedMs, ...input.arrival });
846
846
  return meta;
847
847
  }
@@ -253,7 +253,7 @@ export function sessionDriverClass(runtime) {
253
253
  };
254
254
  let session;
255
255
  try {
256
- session = claude.open(this.specFor({ project, sessionId, started: false, name: "bn-warm", title: undefined, model: undefined, provider: claude, target }));
256
+ session = claude.open(this.specFor({ project, sessionId, started: false, forkOf: undefined, name: "bn-warm", title: undefined, model: undefined, provider: claude, target }));
257
257
  }
258
258
  catch (err) {
259
259
  if (!(err instanceof AgentTurnFailed))
@@ -268,7 +268,7 @@ export function sessionDriverClass(runtime) {
268
268
  /** The spare, if it fits this conversation's first turn in `project`; it is taken out of the pool and the record is given its session id. */
269
269
  takeSpare(c, provider, project) {
270
270
  const spare = this.spare;
271
- if (spare === undefined || provider.name !== "claude" || c.started || this.resuming.has(c.id) || c.model !== undefined || project !== spare.project)
271
+ if (spare === undefined || provider.name !== "claude" || c.started || c.forkOf !== undefined || this.resuming.has(c.id) || c.model !== undefined || project !== spare.project)
272
272
  return undefined;
273
273
  this.spare = undefined;
274
274
  updateConversation(c.id, { sessionId: spare.sessionId });
@@ -459,7 +459,7 @@ export function sessionDriverClass(runtime) {
459
459
  if (c.providerArchived !== true || !c.started || unarchive === undefined)
460
460
  return;
461
461
  const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
462
- const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
462
+ const spec = this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
463
463
  await unarchive(spec, c.sessionId).then(() => { updateConversation(c.id, { providerArchived: undefined }); }, (error) => {
464
464
  appendEvent(c.id, { role: "system", kind: "status", text: `${provider.label} history could not be restored from its archive: ${error.message}` });
465
465
  });
@@ -482,7 +482,7 @@ export function sessionDriverClass(runtime) {
482
482
  this.free(c.id, "idle");
483
483
  const target = { id: c.id, onGone: () => { }, isStarted: () => c.started };
484
484
  const archived = Promise.resolve().then(() => {
485
- const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
485
+ const spec = this.specFor({ project: allowedFolder(c.project), sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: undefined, model: c.model, provider, target });
486
486
  return archive(spec, c.sessionId);
487
487
  }).then(() => { updateConversation(c.id, { providerArchived: true }); shelve(); }, (error) => {
488
488
  appendEvent(c.id, { role: "system", kind: "status", text: "Codex history could not be archived: " + error.message });
@@ -687,6 +687,7 @@ export function sessionDriverClass(runtime) {
687
687
  project: o.project,
688
688
  sessionId: o.sessionId,
689
689
  started: o.started,
690
+ forkOf: o.forkOf,
690
691
  isStarted: () => target.isStarted(),
691
692
  name: o.name,
692
693
  title: o.title,
@@ -710,7 +711,7 @@ export function sessionDriverClass(runtime) {
710
711
  if (live !== undefined)
711
712
  this.gone(c.id, live);
712
713
  };
713
- const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, provider, target }));
714
+ const session = spare?.session ?? provider.open(this.specFor({ project, sessionId: c.sessionId, started: c.started, forkOf: c.forkOf, name: c.chat ?? c.id, title: titleOf({ ...c, project }, transcript(c.id)), model: c.model, provider, target }));
714
715
  live = {
715
716
  session, provider, project, busy: true, usedAt: Date.now(), turn: 0, turnStartedAt: Date.now(), logAt: transcript(c.id).at(-1)?.n ?? 0,
716
717
  ended: () => { }, settleStalled: () => { }, stalled: false, lastOutputAt: Date.now(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.460",
3
+ "version": "1.3.461",
4
4
  "homepage": "https://www.npmjs.com/package/omni-notify-mcp",
5
5
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
6
6
  "main": "dist/daemon.js",
@@ -1,665 +0,0 @@
1
- // OWNER-BOUND JOB (#1968, #1983): the ONE source of the kill-on-close Job Object that ends a process tree
2
- // with its owner. Loaded by ownerGuard.ps1 through Add-Type and called as OwnerJob.Run(...) for FleetView's
3
- // own launches.
4
- //
5
- // #2925: it is NO LONGER compiled into ~/.bullseye/bin/ownerGuard.exe for `claudeCode.claudeProcessWrapper`.
6
- // That build ran the .NET Framework's csc.exe at every activation, which made a compiler a dependency of a
7
- // marketplace install; the wrapper is now POSIX-only (media/shared/claudeWrapper.sh, a shell script that needs
8
- // nothing but /bin/sh) and Windows installs none. Nothing in this file may be re-wired into that setting.
9
- // Language level is C# 5 (the csc.exe that ships with Windows).
10
- //
11
- // THE MECHANISM: the target is created SUSPENDED, assigned to a job carrying KILL_ON_JOB_CLOSE, and only then
12
- // resumed, so no child can be born outside the job. The guard waits on the owner and the target and, when
13
- // EITHER ends, terminates the job. BREAKAWAY_OK is set on purpose and SILENT_BREAKAWAY is not: a process that
14
- // asks for CREATE_BREAKAWAY_FROM_JOB may leave, but nothing leaves by accident - except under `contain`, which leaves
15
- // BREAKAWAY_OK off because the msys2 runtime asks to break away from every job that allows it (spawn.cc), so a
16
- // Git Bash tree would otherwise leave the job whole. A child that asks then stays (Microsoft, "Nested Jobs").
17
- //
18
- // usage (wrapper mode, owner = the parent process, which is the extension host): ownerGuard.exe <exe> [args...]
19
- // (explicit owner): ownerGuard.exe --owner <pid> <exe> [args...]
20
- using System;
21
- using System.Collections.Generic;
22
- using System.IO;
23
- using System.Runtime.InteropServices;
24
- using System.Text;
25
- using System.Text.RegularExpressions;
26
- using System.Threading;
27
-
28
- public static class OwnerJob
29
- {
30
- const uint KILL_ON_JOB_CLOSE = 0x2000;
31
- const uint BREAKAWAY_OK = 0x800;
32
- const int EXTENDED_LIMIT_INFORMATION = 9;
33
- const uint CREATE_SUSPENDED = 0x00000004;
34
- const int STARTF_USESTDHANDLES = 0x00000100;
35
- const uint SYNCHRONIZE = 0x00100000;
36
- const uint PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
37
- const uint INFINITE = 0xFFFFFFFF;
38
-
39
- public const int EXIT_NO_TARGET = 90;
40
- public const int EXIT_NO_JOB = 91;
41
- public const int EXIT_NO_LIMIT = 92;
42
- public const int EXIT_NOT_CREATED = 93;
43
- public const int EXIT_NOT_ASSIGNED = 94;
44
- public const int EXIT_OWNER_GONE = 95;
45
- public const int EXIT_NOT_FOUND = 96;
46
- public const int EXIT_BATCH_LINE_BREAK = 97;
47
- public const int EXIT_NOT_RESUMED = 98;
48
- public const int EXIT_WAIT_FAILED = 99;
49
- public const int EXIT_NO_EXIT_CODE = 100;
50
- public const int EXIT_DEADLINE = 101;
51
- public const int EXIT_ALREADY_RUNNING = 102;
52
- public const int FRAME_OWNERS = -1;
53
- const uint WAIT_TIMEOUT = 0x102;
54
- const uint STILL_ACTIVE = 259;
55
- const int ERROR_INVALID_PARAMETER = 87;
56
-
57
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
58
- struct STARTUPINFO
59
- {
60
- public int cb;
61
- public string lpReserved;
62
- public string lpDesktop;
63
- public string lpTitle;
64
- public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
65
- public short wShowWindow, cbReserved2;
66
- public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
67
- }
68
-
69
- [StructLayout(LayoutKind.Sequential)]
70
- struct PROCESS_INFORMATION
71
- {
72
- public IntPtr hProcess, hThread;
73
- public int dwProcessId, dwThreadId;
74
- }
75
-
76
- [StructLayout(LayoutKind.Sequential)]
77
- struct IO_COUNTERS
78
- {
79
- public ulong a, b, c, d, e, f;
80
- }
81
-
82
- [StructLayout(LayoutKind.Sequential)]
83
- struct JOBOBJECT_BASIC_LIMIT_INFORMATION
84
- {
85
- public long PerProcessUserTimeLimit, PerJobUserTimeLimit;
86
- public uint LimitFlags;
87
- public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize;
88
- public uint ActiveProcessLimit;
89
- public UIntPtr Affinity;
90
- public uint PriorityClass, SchedulingClass;
91
- }
92
-
93
- [StructLayout(LayoutKind.Sequential)]
94
- struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
95
- {
96
- public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
97
- public IO_COUNTERS IoInfo;
98
- public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed;
99
- }
100
-
101
- [StructLayout(LayoutKind.Sequential)]
102
- struct PROCESS_BASIC_INFORMATION
103
- {
104
- public IntPtr ExitStatus, PebBaseAddress, AffinityMask, BasePriority, UniqueProcessId, InheritedFromUniqueProcessId;
105
- }
106
-
107
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
108
- static extern IntPtr CreateJobObject(IntPtr attributes, string name);
109
- [DllImport("kernel32.dll", SetLastError = true)]
110
- static extern bool SetInformationJobObject(IntPtr job, int infoClass, IntPtr info, uint length);
111
- [DllImport("kernel32.dll", SetLastError = true)]
112
- static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
113
- [DllImport("kernel32.dll", SetLastError = true)]
114
- static extern bool TerminateJobObject(IntPtr job, uint exitCode);
115
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
116
- static extern bool CreateProcess(string application, string commandLine, IntPtr processAttributes, IntPtr threadAttributes,
117
- bool inheritHandles, uint creationFlags, IntPtr environment, string currentDirectory, ref STARTUPINFO startupInfo,
118
- out PROCESS_INFORMATION processInformation);
119
- [DllImport("kernel32.dll", SetLastError = true)]
120
- static extern IntPtr GetStdHandle(int which);
121
- [DllImport("kernel32.dll", SetLastError = true)]
122
- static extern bool CloseHandle(IntPtr handle);
123
- [DllImport("kernel32.dll", SetLastError = true)]
124
- static extern uint WaitForMultipleObjects(uint count, IntPtr[] handles, bool waitAll, uint milliseconds);
125
- [DllImport("kernel32.dll", SetLastError = true)]
126
- static extern IntPtr OpenProcess(uint access, bool inherit, int pid);
127
- [DllImport("kernel32.dll", SetLastError = true)]
128
- static extern bool GetExitCodeProcess(IntPtr process, out uint exitCode);
129
- [DllImport("kernel32.dll", SetLastError = true)]
130
- static extern uint ResumeThread(IntPtr thread);
131
- [DllImport("kernel32.dll")]
132
- static extern IntPtr GetCurrentProcess();
133
- [DllImport("kernel32.dll")]
134
- static extern int GetCurrentProcessId();
135
- [DllImport("kernel32.dll", SetLastError = true)]
136
- static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
137
- [DllImport("ntdll.dll")]
138
- static extern int NtQueryInformationProcess(IntPtr process, int infoClass, ref PROCESS_BASIC_INFORMATION info, int length, out int returned);
139
- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
140
- static extern bool QueryFullProcessImageName(IntPtr process, int flags, StringBuilder name, ref int size);
141
-
142
- // One argument as CommandLineToArgvW reads it back: quoted only when it must be, a quote escaped by
143
- // backslashes per the Windows rules, so a path with spaces stays ONE argument.
144
- public static string QuoteArg(string arg)
145
- {
146
- if (arg.Length > 0 && arg.IndexOfAny(new char[] { ' ', '\t', '\n', '\v', '"' }) < 0)
147
- {
148
- return arg;
149
- }
150
- StringBuilder sb = new StringBuilder("\"");
151
- int slashes = 0;
152
- foreach (char ch in arg)
153
- {
154
- if (ch == '\\') { slashes++; continue; }
155
- if (ch == '"') { sb.Append('\\', 2 * slashes + 1); sb.Append('"'); }
156
- else { sb.Append('\\', slashes); sb.Append(ch); }
157
- slashes = 0;
158
- }
159
- sb.Append('\\', 2 * slashes);
160
- sb.Append('"');
161
- return sb.ToString();
162
- }
163
-
164
- // cmd.exe reads its command line by rules of its own: every character it treats as special, the quote and the
165
- // space included, is escaped with a caret so the whole argument is literal text to it.
166
- static string EscapeCmd(string text)
167
- {
168
- return Regex.Replace(text, "([()\\]\\[%!^\"`<>&|;, *?])", "^$1");
169
- }
170
-
171
- static int ParentOf(IntPtr process)
172
- {
173
- PROCESS_BASIC_INFORMATION info = new PROCESS_BASIC_INFORMATION();
174
- int returned;
175
- if (NtQueryInformationProcess(process, 0, ref info, Marshal.SizeOf(info), out returned) != 0)
176
- {
177
- return 0;
178
- }
179
- return (int)info.InheritedFromUniqueProcessId.ToInt64();
180
- }
181
-
182
- static int ParentPid()
183
- {
184
- return ParentOf(GetCurrentProcess());
185
- }
186
-
187
- static long StartOf(IntPtr process, int pid)
188
- {
189
- long start, ignored;
190
- if (!GetProcessTimes(process, out start, out ignored, out ignored, out ignored))
191
- {
192
- throw new InvalidOperationException("the start time of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
193
- }
194
- return start;
195
- }
196
-
197
- // A pid names an ancestor only if that process STARTED BEFORE the younger one: a recycled pid belongs to a
198
- // younger process, and then the real ancestor is already dead.
199
- static IntPtr OpenGone(int pid, uint access)
200
- {
201
- IntPtr process = OpenProcess(access, false, pid);
202
- if (process == IntPtr.Zero)
203
- {
204
- int why = Marshal.GetLastWin32Error();
205
- if (why != ERROR_INVALID_PARAMETER)
206
- {
207
- throw new InvalidOperationException("process " + pid + " could not be opened (win32 " + why + ")");
208
- }
209
- }
210
- return process;
211
- }
212
-
213
- static IntPtr OpenOlderThan(int pid, IntPtr younger, int youngerPid)
214
- {
215
- IntPtr process = OpenGone(pid, SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION);
216
- if (process == IntPtr.Zero)
217
- {
218
- return process;
219
- }
220
- if (StartOf(process, pid) > StartOf(younger, youngerPid))
221
- {
222
- CloseHandle(process);
223
- return IntPtr.Zero;
224
- }
225
- return process;
226
- }
227
-
228
- static IntPtr OpenOwner(int ownerPid, bool mustPredateSelf)
229
- {
230
- return mustPredateSelf
231
- ? OpenOlderThan(ownerPid, GetCurrentProcess(), GetCurrentProcessId())
232
- : OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, ownerPid);
233
- }
234
-
235
- static string ImageOf(IntPtr process, int pid)
236
- {
237
- StringBuilder name = new StringBuilder(1024);
238
- int size = name.Capacity;
239
- if (!QueryFullProcessImageName(process, 0, name, ref size))
240
- {
241
- throw new InvalidOperationException("the image of process " + pid + " could not be read (win32 " + Marshal.GetLastWin32Error() + ")");
242
- }
243
- return name.ToString(0, size);
244
- }
245
-
246
- static List<IntPtr> ShellFrame()
247
- {
248
- List<IntPtr> frame = new List<IntPtr>();
249
- IntPtr child = GetCurrentProcess();
250
- int childPid = GetCurrentProcessId();
251
- while (true)
252
- {
253
- int parentPid = ParentOf(child);
254
- if (parentPid == 0)
255
- {
256
- throw new InvalidOperationException("the parent of process " + childPid + " could not be read");
257
- }
258
- IntPtr parent = OpenOlderThan(parentPid, child, childPid);
259
- if (parent == IntPtr.Zero)
260
- {
261
- return frame;
262
- }
263
- frame.Add(parent);
264
- string image = Path.GetFileName(ImageOf(parent, parentPid)).ToLowerInvariant();
265
- if (image != "bash.exe" && image != "sh.exe")
266
- {
267
- return frame;
268
- }
269
- child = parent;
270
- childPid = parentPid;
271
- }
272
- }
273
-
274
- static string ReadLock(string path)
275
- {
276
- try
277
- {
278
- using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)))
279
- {
280
- return reader.ReadToEnd().Trim();
281
- }
282
- }
283
- catch (FileNotFoundException)
284
- {
285
- return null;
286
- }
287
- }
288
-
289
- static bool StillHolds(int pid, long start)
290
- {
291
- IntPtr process = OpenGone(pid, PROCESS_QUERY_LIMITED_INFORMATION);
292
- if (process == IntPtr.Zero)
293
- {
294
- return false;
295
- }
296
- uint code;
297
- bool alive = StartOf(process, pid) == start && GetExitCodeProcess(process, out code) && code == STILL_ACTIVE;
298
- CloseHandle(process);
299
- return alive;
300
- }
301
-
302
- static bool ParseLock(string held, out int pid, out long start)
303
- {
304
- string[] parts = held.Split(' ');
305
- start = 0;
306
- pid = 0;
307
- return parts.Length == 2 && int.TryParse(parts[0], out pid) && long.TryParse(parts[1], out start);
308
- }
309
-
310
- static int TakeLock(string path, out string mine)
311
- {
312
- mine = GetCurrentProcessId() + " " + StartOf(GetCurrentProcess(), GetCurrentProcessId());
313
- for (int attempt = 0; attempt < 2; attempt++)
314
- {
315
- if (!File.Exists(path))
316
- {
317
- try
318
- {
319
- using (FileStream file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
320
- {
321
- byte[] bytes = Encoding.ASCII.GetBytes(mine);
322
- file.Write(bytes, 0, bytes.Length);
323
- }
324
- return 0;
325
- }
326
- catch (IOException)
327
- {
328
- if (!File.Exists(path))
329
- {
330
- throw;
331
- }
332
- }
333
- }
334
- string held = ReadLock(path);
335
- int pid;
336
- long start;
337
- if (held != null && !ParseLock(held, out pid, out start))
338
- {
339
- Thread.Sleep(1000);
340
- held = ReadLock(path);
341
- }
342
- if (held == null)
343
- {
344
- continue;
345
- }
346
- bool parsed = ParseLock(held, out pid, out start);
347
- if (parsed && StillHolds(pid, start))
348
- {
349
- Say("REFUSED - an earlier run (pid " + pid + ", started " + DateTime.FromFileTime(start).ToString("yyyy-MM-dd HH:mm:ss") + ") still holds " + path + " - this launch did not run");
350
- return EXIT_ALREADY_RUNNING;
351
- }
352
- try
353
- {
354
- File.Delete(path);
355
- }
356
- catch (IOException e)
357
- {
358
- Say("REFUSED - " + path + " named '" + held + "' and could not be replaced (" + e.Message + ") - this launch did not run");
359
- return EXIT_ALREADY_RUNNING;
360
- }
361
- Say("STALE LOCK - " + path + " named '" + held + "', which " + (parsed ? "no longer runs" : "is not a pid and start time") + " - taken over");
362
- }
363
- Say("REFUSED - " + path + " was taken by another launch while its stale holder was being replaced - this launch did not run");
364
- return EXIT_ALREADY_RUNNING;
365
- }
366
-
367
- static void ReleaseLock(string path, string mine)
368
- {
369
- if (ReadLock(path) == mine)
370
- {
371
- File.Delete(path);
372
- }
373
- }
374
-
375
- static void Say(string text)
376
- {
377
- Console.Error.WriteLine("ownerGuard: " + text);
378
- }
379
-
380
- // The target as the launch has always resolved it (Get-Command -CommandType Application): a name with a folder is
381
- // taken as given, a bare name is searched along PATH, and a name without a PATHEXT extension tries each one.
382
- static string Resolve(string exe)
383
- {
384
- List<string> extensions = new List<string>((Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD")
385
- .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
386
- List<string> folders = new List<string>();
387
- if (exe.IndexOfAny(new char[] { '\\', '/', ':' }) >= 0)
388
- {
389
- folders.Add(null);
390
- }
391
- else
392
- {
393
- foreach (string dir in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
394
- {
395
- folders.Add(dir.Trim('"'));
396
- }
397
- }
398
- foreach (string folder in folders)
399
- {
400
- string stem = folder == null ? exe : Path.Combine(folder, exe);
401
- if (File.Exists(stem) && extensions.Exists(delegate(string e) { return stem.EndsWith(e, StringComparison.OrdinalIgnoreCase); }))
402
- {
403
- return Path.GetFullPath(stem);
404
- }
405
- foreach (string ext in extensions)
406
- {
407
- if (File.Exists(stem + ext))
408
- {
409
- return Path.GetFullPath(stem + ext);
410
- }
411
- }
412
- }
413
- return null;
414
- }
415
-
416
- // The command line the target is created with, or null (and a refusal said) when it cannot be carried.
417
- static string CommandLine(ref string exe, string[] args, out int refusal)
418
- {
419
- refusal = 0;
420
- string ext = Path.GetExtension(exe).ToLowerInvariant();
421
- StringBuilder line = new StringBuilder();
422
- if (ext == ".cmd" || ext == ".bat")
423
- {
424
- foreach (string arg in args)
425
- {
426
- if (arg.IndexOfAny(new char[] { '\r', '\n' }) >= 0)
427
- {
428
- Say("the target '" + exe + "' is a batch file and one of its arguments holds a line break, which cmd.exe cannot carry - nothing was started");
429
- refusal = EXIT_BATCH_LINE_BREAK;
430
- return null;
431
- }
432
- }
433
- StringBuilder inner = new StringBuilder(EscapeCmd(exe));
434
- foreach (string arg in args)
435
- {
436
- inner.Append(' ').Append(EscapeCmd(EscapeCmd(QuoteArg(arg))));
437
- }
438
- exe = Path.Combine(Environment.SystemDirectory, "cmd.exe");
439
- return QuoteArg(exe) + " /d /s /v:off /c \"" + inner + "\"";
440
- }
441
- line.Append(QuoteArg(exe));
442
- foreach (string arg in args)
443
- {
444
- line.Append(' ').Append(QuoteArg(arg));
445
- }
446
- return line.ToString();
447
- }
448
-
449
- public static int Run(int ownerPid, string exe, string[] args, string cwd)
450
- {
451
- return Run(ownerPid, exe, args, cwd, 0, false, null);
452
- }
453
-
454
- // Runs the target inside a kill-on-close job and answers the target's own exit code. ownerPid <= 0 means
455
- // "the parent process owns this launch", FRAME_OWNERS means "the shell frame owns it" (ShellFrame). cwd null or
456
- // empty starts the target where this process runs. deadlineSeconds > 0 ends the whole job at that age
457
- // (EXIT_DEADLINE). contain leaves BREAKAWAY_OK off, so no process inside can leave the job, Git Bash's
458
- // included. lockFile, when given, admits one launch at a time (TakeLock).
459
- public static int Run(int ownerPid, string exe, string[] args, string cwd, int deadlineSeconds, bool contain, string lockFile)
460
- {
461
- if (string.IsNullOrEmpty(exe) || exe.Trim().Length == 0)
462
- {
463
- Say("the target executable is empty - nothing was started");
464
- return EXIT_NO_TARGET;
465
- }
466
- if (string.IsNullOrEmpty(cwd))
467
- {
468
- cwd = null;
469
- }
470
- string resolved = Resolve(exe);
471
- if (resolved == null)
472
- {
473
- Say("the target '" + exe + "' is not an executable on PATH or on disk - nothing was started");
474
- return EXIT_NOT_FOUND;
475
- }
476
- exe = resolved;
477
- int refusal;
478
- string line = CommandLine(ref exe, args, out refusal);
479
- if (line == null)
480
- {
481
- return refusal;
482
- }
483
- string mine = null;
484
- if (!string.IsNullOrEmpty(lockFile))
485
- {
486
- int refused = TakeLock(lockFile, out mine);
487
- if (refused != 0)
488
- {
489
- return refused;
490
- }
491
- }
492
- try
493
- {
494
- return Launch(ownerPid, exe, line, cwd, deadlineSeconds, contain);
495
- }
496
- finally
497
- {
498
- if (mine != null)
499
- {
500
- ReleaseLock(lockFile, mine);
501
- }
502
- }
503
- }
504
-
505
- static int Launch(int ownerPid, string exe, string line, string cwd, int deadlineSeconds, bool contain)
506
- {
507
- bool frame = ownerPid == FRAME_OWNERS;
508
- bool viaParent = !frame && ownerPid <= 0;
509
- if (viaParent)
510
- {
511
- ownerPid = ParentPid();
512
- }
513
-
514
- IntPtr job = CreateJobObject(IntPtr.Zero, null);
515
- if (job == IntPtr.Zero)
516
- {
517
- Say("the job object could not be created (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
518
- return EXIT_NO_JOB;
519
- }
520
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
521
- limits.BasicLimitInformation.LimitFlags = contain ? KILL_ON_JOB_CLOSE : KILL_ON_JOB_CLOSE | BREAKAWAY_OK;
522
- int size = Marshal.SizeOf(limits);
523
- IntPtr buffer = Marshal.AllocHGlobal(size);
524
- try
525
- {
526
- Marshal.StructureToPtr(limits, buffer, false);
527
- if (!SetInformationJobObject(job, EXTENDED_LIMIT_INFORMATION, buffer, (uint)size))
528
- {
529
- Say("the job could not be told to kill on close (win32 " + Marshal.GetLastWin32Error() + ") - the target was NOT started unguarded");
530
- CloseHandle(job);
531
- return EXIT_NO_LIMIT;
532
- }
533
- }
534
- finally
535
- {
536
- Marshal.FreeHGlobal(buffer);
537
- }
538
-
539
- STARTUPINFO startup = new STARTUPINFO();
540
- startup.cb = Marshal.SizeOf(startup);
541
- IntPtr stdin = GetStdHandle(-10), stdout = GetStdHandle(-11), stderr = GetStdHandle(-12);
542
- if (stdin != IntPtr.Zero && stdout != IntPtr.Zero && stderr != IntPtr.Zero)
543
- {
544
- startup.dwFlags = STARTF_USESTDHANDLES;
545
- startup.hStdInput = stdin;
546
- startup.hStdOutput = stdout;
547
- startup.hStdError = stderr;
548
- }
549
-
550
- PROCESS_INFORMATION process;
551
- if (!CreateProcess(exe, line, IntPtr.Zero, IntPtr.Zero, true, CREATE_SUSPENDED, IntPtr.Zero, cwd, ref startup, out process))
552
- {
553
- Say("the target could not be created (win32 " + Marshal.GetLastWin32Error() + ") - nothing was started");
554
- CloseHandle(job);
555
- return EXIT_NOT_CREATED;
556
- }
557
- if (!AssignProcessToJobObject(job, process.hProcess))
558
- {
559
- int error = Marshal.GetLastWin32Error();
560
- TerminateJobObject(job, EXIT_NOT_ASSIGNED);
561
- CloseHandle(process.hThread);
562
- CloseHandle(process.hProcess);
563
- CloseHandle(job);
564
- Say("the target could not be put under the job that ends it with its owner (win32 " + error + ") - it was stopped rather than left unguarded");
565
- return EXIT_NOT_ASSIGNED;
566
- }
567
-
568
- // The owner is opened AFTER the target sits in the job and BEFORE it runs, so a dead owner stops it unrun.
569
- List<IntPtr> owners = new List<IntPtr>();
570
- if (frame)
571
- {
572
- owners = ShellFrame();
573
- }
574
- else if (ownerPid > 0)
575
- {
576
- IntPtr owner = OpenOwner(ownerPid, viaParent);
577
- if (owner != IntPtr.Zero)
578
- {
579
- owners.Add(owner);
580
- }
581
- }
582
- if (owners.Count == 0)
583
- {
584
- int why = Marshal.GetLastWin32Error();
585
- TerminateJobObject(job, EXIT_OWNER_GONE);
586
- CloseHandle(process.hThread);
587
- CloseHandle(process.hProcess);
588
- CloseHandle(job);
589
- Say((frame ? "the shell frame above this guard" : "the owner process " + ownerPid) + " cannot be watched (win32 " + why + ") - the target was stopped before it ran");
590
- return EXIT_OWNER_GONE;
591
- }
592
-
593
- if (ResumeThread(process.hThread) == 0xFFFFFFFF)
594
- {
595
- int why = Marshal.GetLastWin32Error();
596
- TerminateJobObject(job, EXIT_NOT_RESUMED);
597
- Say("the target could not be resumed (win32 " + why + ") - it was stopped rather than left suspended");
598
- return EXIT_NOT_RESUMED;
599
- }
600
- CloseHandle(process.hThread);
601
-
602
- List<IntPtr> watched = new List<IntPtr>(owners);
603
- watched.Insert(0, process.hProcess);
604
- uint waited = WaitForMultipleObjects((uint)watched.Count, watched.ToArray(), false, deadlineSeconds > 0 ? (uint)deadlineSeconds * 1000 : INFINITE);
605
- int waitError = Marshal.GetLastWin32Error();
606
- foreach (IntPtr owner in owners)
607
- {
608
- CloseHandle(owner);
609
- }
610
- if (waited == 0xFFFFFFFF)
611
- {
612
- TerminateJobObject(job, EXIT_WAIT_FAILED);
613
- Say("the wait on the target and its owner failed (win32 " + waitError + ") - the target was stopped rather than left unwatched");
614
- return EXIT_WAIT_FAILED;
615
- }
616
- if (waited == WAIT_TIMEOUT)
617
- {
618
- TerminateJobObject(job, EXIT_DEADLINE);
619
- Say("DEADLINE - the target ran past its " + deadlineSeconds + " s; its whole job was ended");
620
- return EXIT_DEADLINE;
621
- }
622
- if (waited != 0)
623
- {
624
- TerminateJobObject(job, EXIT_OWNER_GONE);
625
- Say("OWNER GONE - a process this launch was bound to ended; the target's whole job was ended");
626
- return EXIT_OWNER_GONE;
627
- }
628
-
629
- uint code = 0;
630
- if (!GetExitCodeProcess(process.hProcess, out code))
631
- {
632
- int why = Marshal.GetLastWin32Error();
633
- TerminateJobObject(job, EXIT_NO_EXIT_CODE);
634
- Say("the target's exit code could not be read (win32 " + why + ") - the target was stopped");
635
- return EXIT_NO_EXIT_CODE;
636
- }
637
- TerminateJobObject(job, 1);
638
- CloseHandle(process.hProcess);
639
- CloseHandle(job);
640
- return (int)code;
641
- }
642
-
643
- public static int Main(string[] argv)
644
- {
645
- List<string> rest = new List<string>(argv);
646
- int ownerPid = 0;
647
- if (rest.Count >= 2 && rest[0] == "--owner")
648
- {
649
- if (!int.TryParse(rest[1], out ownerPid) || ownerPid <= 0)
650
- {
651
- Say("--owner needs a process id");
652
- return EXIT_NO_TARGET;
653
- }
654
- rest.RemoveRange(0, 2);
655
- }
656
- if (rest.Count == 0)
657
- {
658
- Say("usage: ownerGuard.exe [--owner <pid>] <exe> [args...]");
659
- return EXIT_NO_TARGET;
660
- }
661
- string exe = rest[0];
662
- rest.RemoveAt(0);
663
- return Run(ownerPid, exe, rest.ToArray(), null);
664
- }
665
- }
@@ -1,31 +0,0 @@
1
- # OWNER-BOUND LAUNCH (#1968): start one target so that it can never outlive its owner, and so that nothing it
2
- # started can outlive IT. This script is only the PowerShell door onto ownerGuard.cs, which holds the whole job.
3
- # #2925: the same source is no longer compiled into an ownerGuard.exe for `claudeCode.claudeProcessWrapper` — that
4
- # build ran csc.exe at every activation, and the .NET compiler is not a dependency a marketplace install may carry.
5
- # The target's own exit code is answered as this script's exit code.
6
- param(
7
- [Parameter(Mandatory = $true)][int]$OwnerPid,
8
- [Parameter(Mandatory = $true)][string]$ExeB64,
9
- [Parameter(Mandatory = $true)][string]$ArgsB64,
10
- [Parameter(Mandatory = $true)][AllowEmptyString()][string]$CwdB64,
11
- [switch]$ShellFrame,
12
- [int]$DeadlineSeconds = 0,
13
- [switch]$Contain,
14
- [string]$LockFile = ""
15
- )
16
-
17
- $ErrorActionPreference = "Stop"
18
-
19
- Add-Type -Path (Join-Path $PSScriptRoot "ownerGuard.cs")
20
-
21
- $exe = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ExeB64))
22
- # ConvertFrom-Json hands back the WHOLE array as one object on Windows PowerShell, so iterate it with
23
- # foreach: a one-element array arrives as the element itself and a longer one as the array, both right.
24
- $argv = New-Object System.Collections.Generic.List[string]
25
- foreach ($item in ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($ArgsB64)) | ConvertFrom-Json)) {
26
- $argv.Add([string]$item)
27
- }
28
- $cwd = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($CwdB64))
29
-
30
- if ($ShellFrame) { $OwnerPid = [OwnerJob]::FRAME_OWNERS }
31
- exit ([OwnerJob]::Run($OwnerPid, $exe, $argv.ToArray(), $cwd, $DeadlineSeconds, $Contain.IsPresent, $LockFile))