omni-notify-mcp 1.3.311 → 1.3.312

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.
@@ -34,13 +34,16 @@ function activity(tool) {
34
34
  const mcp = /^mcp__([^_]+(?:_[^_]+)*)__/.exec(tool);
35
35
  return mcp ? `using ${mcp[1]}` : `using ${tool}`;
36
36
  }
37
+ function projectsDir() {
38
+ return join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
39
+ }
37
40
  /**
38
41
  * Whether the CLI has written this session's transcript. A first turn cut off before its result line (BN restarted
39
42
  * under it) leaves one behind with the record still unstarted, and the CLI then refuses `--session-id` for that id as
40
43
  * already in use: such a session is resumed, never created again.
41
44
  */
42
45
  function transcriptWritten(sessionId) {
43
- const projects = join(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
46
+ const projects = projectsDir();
44
47
  if (!existsSync(projects))
45
48
  return false;
46
49
  return readdirSync(projects).some((dir) => existsSync(join(projects, dir, `${sessionId}.jsonl`)));
@@ -315,15 +318,21 @@ class ClaudeSession {
315
318
  sink.layers(clock.finish(monotonicMs(), this.debugFile));
316
319
  this.sink = undefined;
317
320
  }
321
+ // A session that was ended reads no record: its answer is refused here, before any record is read for it.
322
+ if (this.warm.stopped)
323
+ throw this.spec.failures.fail("the agent's session was ended");
318
324
  // NULL-OK: field unsupported is OPTIONAL and therefore it is ok to check for NULL
319
325
  if (this.unsupported !== undefined)
320
326
  throw this.spec.failures.fail(`the agent asked BN for "${this.unsupported}", which BN does not answer — the session was ended.`);
321
327
  if (result.stdout === "") {
328
+ const exited = `the agent exited (code ${result.code ?? "none"}) without an answer while ${this.resumes ? "resuming" : "creating"} session ${this.spec.sessionId}${result.stderr.trim() ? `: ${result.stderr.trim().slice(-300)}` : ""}`;
329
+ if (this.resumes && !transcriptWritten(this.spec.sessionId))
330
+ throw this.lost(exited, sink);
322
331
  // A first turn that died before the CLI wrote its session leaves a half-made id: the retry starts a new one, and
323
332
  // a session the record already holds is never overwritten by it.
324
333
  if (!this.spec.isStarted() && !this.resumes)
325
334
  sink.sessionId(randomUUID(), false);
326
- throw this.spec.failures.fail(`the agent exited (code ${result.code ?? "none"}) without an answer${result.stderr.trim() ? `: ${result.stderr.trim().slice(-300)}` : ""}`);
335
+ throw this.spec.failures.fail(exited);
327
336
  }
328
337
  let parsed;
329
338
  try {
@@ -336,8 +345,14 @@ class ClaudeSession {
336
345
  throw new AgentTurnFailed(text, `❌ The agent's answer was unreadable: ${result.stdout.slice(0, 200)}`);
337
346
  }
338
347
  if (parsed.is_error === true) {
339
- const text = `the agent reported an error (${parsed.subtype ?? "error"}): ${String(parsed.result ?? "").slice(0, 300)}`;
340
- throw new AgentTurnFailed(text, `❌ The agent reported an error (${parsed.subtype ?? "error"}): ${String(parsed.result ?? "").slice(0, 300)}`);
348
+ const subtype = parsed.subtype ?? "error";
349
+ const parts = [...new Set([String(parsed.result ?? ""), ...(Array.isArray(parsed.errors) ? parsed.errors.map(String) : []), result.stderr].map((part) => part.trim()).filter((part) => part !== ""))];
350
+ const said = parts.length === 0 ? "the CLI gave no reason on its result line or its stderr" : parts.join(" — ");
351
+ const how = this.resumes ? `resuming session ${this.spec.sessionId}` : `creating session ${this.spec.sessionId}`;
352
+ const detail = `the Claude CLI ended the turn with ${subtype} while ${how} in ${this.spec.project}: ${said.slice(0, 300)}`;
353
+ if (this.resumes && !transcriptWritten(this.spec.sessionId))
354
+ throw this.lost(detail, sink);
355
+ throw new AgentTurnFailed(detail, `❌ The agent reported an error (${subtype}) while ${how}: ${said.slice(0, 300)}`);
341
356
  }
342
357
  const answer = parsed.result;
343
358
  if (typeof answer !== "string") {
@@ -354,6 +369,12 @@ class ClaudeSession {
354
369
  }
355
370
  return answer;
356
371
  }
372
+ /** A resume the CLI could not make because the session's transcript is gone: the record moves to a new session id, so the next message creates one under this same conversation, and the turn fails saying so. */
373
+ lost(detail, sink) {
374
+ sink.sessionId(randomUUID(), false);
375
+ const lost = `this conversation's agent session ${this.spec.sessionId} cannot be resumed — its saved history is no longer on disk under ${projectsDir()} (${detail})`;
376
+ return new AgentTurnFailed(lost, `❌ ${lost[0].toUpperCase()}${lost.slice(1)}. Nothing was run. A message already waiting runs in a new agent session of this same conversation, and a message sent now does the same; that session starts without the earlier turns, so include what it needs to know.`);
377
+ }
357
378
  answerPermission(requestId, allow, refusal) {
358
379
  const response = allow ? { behavior: "allow", updatedInput: this.inputs.get(requestId) } : { behavior: "deny", message: `Refused over chat: ${refusal}` };
359
380
  this.inputs.delete(requestId);
@@ -161,10 +161,38 @@ function textAt(file) {
161
161
  throw err;
162
162
  }
163
163
  }
164
+ /** Whether a process id still names a live process: EPERM means it exists and this account may not signal it. */
165
+ export function pidAlive(pid) {
166
+ try {
167
+ process.kill(pid, 0);
168
+ return true;
169
+ }
170
+ catch (error) {
171
+ const code = error.code;
172
+ if (code === "EPERM")
173
+ return true;
174
+ if (code === "ESRCH")
175
+ return false;
176
+ throw error;
177
+ }
178
+ }
179
+ let sweptStaged = false;
180
+ /** Removes every <name>.json.<pid>.tmp of the agent store whose writer is no longer a live process: a BN killed between a staged write and its rename leaves one nothing else ever removes. Runs once per BN process, on the store's first listing at boot. */
181
+ function sweepDeadStaged() {
182
+ sweptStaged = true;
183
+ for (const name of readdirSync(agentDir())) {
184
+ const writer = /\.json\.(\d+)\.tmp$/.exec(name)?.[1];
185
+ // NULL-OK: field writer is OPTIONAL and therefore it is ok to check for NULL
186
+ if (writer !== undefined && !pidAlive(Number(writer)))
187
+ dropStaged(join(agentDir(), name));
188
+ }
189
+ }
164
190
  /** Every conversation, newest first. */
165
191
  export function listConversations(includeInteractive = false) {
166
192
  if (!existsSync(agentDir()))
167
193
  return [];
194
+ if (!sweptStaged)
195
+ sweepDeadStaged();
168
196
  return readdirSync(agentDir())
169
197
  .filter((name) => name.endsWith(".json") && UUID.test(name.slice(0, -5)))
170
198
  .flatMap((name) => recordAt(join(agentDir(), name)) ?? [])
@@ -101,9 +101,13 @@ function sameBoard(a, b) {
101
101
  function heldByWords(claim) {
102
102
  return `#${claim.storyId} is held by ${claim.name} (${String(claim.sessionId).replace(/^hold:/, "")}) — heartbeat ${claim.at}${claim.why === undefined ? "" : ` — why: ${claim.why}`}`;
103
103
  }
104
- /** The hold a conversation writes for a story: a `hold` in the conversation's own name, addressed by this machine and this process exactly as the board's engine writes one (#2838). */
105
- function holdOf(name, storyId, board, now) {
106
- return { storyId, name, sessionId: `hold:${hostname()}:${process.pid}`, at: boardStamp(now), kind: "hold", board };
104
+ /** The address every hold of this daemon is written under and released by (#2838). */
105
+ function holdAddress() {
106
+ return `hold:${hostname()}:${process.pid}`;
107
+ }
108
+ /** The hold a conversation writes for a story: a `hold` in the conversation's own name, addressed by this machine and this process exactly as the board's engine writes one (#2838). `drives` names the agent session this conversation runs, so a door can tell this hold from the work of the very session it holds for (#3850). */
109
+ function holdOf(name, storyId, board, now, drives) {
110
+ return { storyId, name, sessionId: holdAddress(), at: boardStamp(now), kind: "hold", board, drives };
107
111
  }
108
112
  /** The claims the file still holds at `now`, lapsed ones dropped exactly as every reader of the file drops them; a file that is not there is a machine that has claimed nothing. */
109
113
  function readClaims(file, now) {
@@ -207,14 +211,16 @@ function writeClaims(file, claims) {
207
211
  }
208
212
  }
209
213
  /** BN's conversation takes the story's hold: the holder's name IS the conversation's id, so every refusal and every door name this conversation. Another session's standing hold, or its fresh `taken` claim, refuses in the file's own words (#2838/#2040). */
210
- function holdStory(file, name, storyId, board, now) {
211
- const claim = holdOf(name, storyId, board, now);
214
+ function holdStory(file, name, storyId, board, now, drives) {
215
+ const claim = holdOf(name, storyId, board, now, drives);
212
216
  underClaimsLock(file, () => {
213
217
  const before = readClaims(file, now);
214
218
  const on = (c) => c.storyId === claim.storyId && sameBoard(c.board, board);
215
219
  const prior = before.find(on);
216
- // The derived sessionId is the same for every conversation of one daemon, so a DIFFERENT conversation in this process is another holder too — its own name is what tells two of them apart, and neither may overwrite the other.
217
- const mine = prior !== undefined && prior.sessionId === claim.sessionId && prior.name === claim.name;
220
+ if (prior !== undefined && prior.sessionId === drives)
221
+ return;
222
+ // The name IS the conversation's id, so a hold in it is this conversation's own even under the address of a BN process that died; a DIFFERENT conversation's hold has another name and neither may overwrite the other.
223
+ const mine = prior !== undefined && prior.kind === "hold" && prior.name === claim.name;
218
224
  if (prior !== undefined && !mine && (prior.kind === "hold" || claim.kind === "hold"))
219
225
  throw new GatewayError(409, heldByWords(prior));
220
226
  writeClaims(file, [...before.filter((c) => !on(c)), claim]);
@@ -222,7 +228,7 @@ function holdStory(file, name, storyId, board, now) {
222
228
  }
223
229
  /** BN drops the hold it wrote when the work on the story ends: only the claim under its own address AND its own name goes — a different conversation of this daemon shares the address and must keep its own claim (#2838). */
224
230
  function releaseStory(file, name, storyId, board, now) {
225
- const mine = holdOf(name, storyId, board, now).sessionId;
231
+ const mine = holdAddress();
226
232
  underClaimsLock(file, () => {
227
233
  const before = readClaims(file, now);
228
234
  const isMine = (c) => c.storyId === storyId && sameBoard(c.board, board) && c.sessionId === mine && c.name === name;
@@ -254,6 +260,10 @@ export class SessionDriver {
254
260
  archiveIdleMs;
255
261
  lives = new Map();
256
262
  driving = new Set();
263
+ /** Every conversation's queue loop still running: shutdown stops them and waits for each to finish. */
264
+ loops = new Set();
265
+ /** Set by shutdown: no queue loop begins another iteration, so none reads a record after the store was handed back. */
266
+ stopping = false;
257
267
  archiving = new Set();
258
268
  /** Conversations waiting for a slot, first come first served. */
259
269
  waiting = [];
@@ -291,6 +301,7 @@ export class SessionDriver {
291
301
  * cut off in the middle of is taken up again on the same session; then the store is read on a beat.
292
302
  */
293
303
  boot() {
304
+ this.stopping = false;
294
305
  if (this.watcher !== undefined)
295
306
  return;
296
307
  this.bootedAt = Date.now();
@@ -412,7 +423,8 @@ export class SessionDriver {
412
423
  return this.driving.size === 0 && this.waiting.length === 0;
413
424
  }
414
425
  /** Hands the store back: the beat stops and every held session's process is ended, its conversation left idle for the next owner to resume. */
415
- shutdown() {
426
+ async shutdown() {
427
+ this.stopping = true;
416
428
  this.watcher?.close();
417
429
  this.watcher = undefined;
418
430
  clearTimeout(this.dueTimer);
@@ -422,7 +434,8 @@ export class SessionDriver {
422
434
  this.spare = undefined;
423
435
  this.resuming.clear();
424
436
  for (const id of [...this.lives.keys()])
425
- this.free(id, "idle");
437
+ this.endLive(id);
438
+ await Promise.all([...this.loops]);
426
439
  }
427
440
  /** Closes the conversation and reaps its process tree at once. */
428
441
  stop(id) {
@@ -610,7 +623,9 @@ export class SessionDriver {
610
623
  }
611
624
  /** Runs a conversation's queue; a failure is written into its own log rather than left as an unhandled rejection. */
612
625
  driveNow(id) {
613
- void this.drive(id).catch((err) => {
626
+ if (this.stopping)
627
+ return;
628
+ const loop = this.drive(id).catch((err) => {
614
629
  process.stderr.write(`[agent-gateway] the driver of ${id} failed: ${err instanceof Error ? err.message : String(err)}
615
630
  `);
616
631
  const live = this.lives.get(id);
@@ -618,12 +633,16 @@ export class SessionDriver {
618
633
  this.emit(id, "system", "failed", `❌ The conversation could not carry on: ${err instanceof Error ? err.message : String(err)}`, turn, this.failureTiming(id, turn, Date.now()));
619
634
  this.release(id);
620
635
  });
636
+ this.loops.add(loop);
637
+ void loop.then(() => this.loops.delete(loop));
621
638
  }
622
639
  // OWNER: ITER/LOOP — one conversation's turns run one after another; a turn that fails is written into its own log as a failed event and the loop takes the next message.
623
640
  async drive(id) {
624
641
  this.driving.add(id);
625
642
  try {
626
643
  for (;;) {
644
+ if (this.stopping)
645
+ return;
627
646
  const c = readConversation(id);
628
647
  if (c.state === "closed" || conversationRefusal() !== undefined)
629
648
  return;
@@ -679,6 +698,7 @@ export class SessionDriver {
679
698
  let beat;
680
699
  if (hold !== undefined) {
681
700
  const held = hold;
701
+ this.refreshHold(c.id, held);
682
702
  beat = setInterval(() => this.refreshHold(c.id, held), HOLD_BEAT_MS);
683
703
  beat.unref();
684
704
  }
@@ -705,13 +725,13 @@ export class SessionDriver {
705
725
  // NULL-OK: field storyId is OPTIONAL and therefore it is ok to check for NULL
706
726
  if (storyId === undefined)
707
727
  return undefined;
708
- holdStory(claimsFile(), conversationId, storyId, project, Date.now());
728
+ holdStory(claimsFile(), conversationId, storyId, project, Date.now(), readConversation(conversationId).sessionId);
709
729
  return { storyId, board: project };
710
730
  }
711
731
  /** The hold is refreshed so it never lapses while the turn it belongs to runs. */
712
732
  refreshHold(conversationId, hold) {
713
733
  try {
714
- holdStory(claimsFile(), conversationId, hold.storyId, hold.board, Date.now());
734
+ holdStory(claimsFile(), conversationId, hold.storyId, hold.board, Date.now(), readConversation(conversationId).sessionId);
715
735
  }
716
736
  catch (err) {
717
737
  if (!(err instanceof Error))
@@ -775,6 +795,8 @@ export class SessionDriver {
775
795
  }
776
796
  /** A slot came free: the first conversation in line takes it. */
777
797
  drain() {
798
+ if (this.stopping)
799
+ return;
778
800
  const first = this.waiting[0];
779
801
  // NULL-OK: field first is OPTIONAL and therefore it is ok to check for NULL
780
802
  if (first === undefined || this.driving.has(first))
@@ -852,6 +874,8 @@ export class SessionDriver {
852
874
  catch (err) {
853
875
  if (!(err instanceof AgentTurnFailed))
854
876
  throw err;
877
+ process.stderr.write(`[agent-gateway] ${c.id} turn ${message.n} failed: ${err.message}
878
+ `);
855
879
  failure = err.shown ?? `❌ The agent could not answer: ${err.message}`;
856
880
  }
857
881
  const answeredAt = monotonicMs();
@@ -863,6 +887,10 @@ export class SessionDriver {
863
887
  return;
864
888
  const mark = { message, startEvent, startedAt, startedWall, askAt, answeredAt };
865
889
  this.answer(c.id, message.n, result, failure, (storeAt) => this.timing(c, live, opened, mark, storeAt));
890
+ if (live.rotated) {
891
+ this.free(c.id, "idle");
892
+ return;
893
+ }
866
894
  if (live.stalled) {
867
895
  // The CLI was killed at the silence bound: its slot goes to the message in line in the same step as that failure.
868
896
  this.free(c.id, "idle");
@@ -887,7 +915,9 @@ export class SessionDriver {
887
915
  updateConversation(id, { pid });
888
916
  },
889
917
  sessionId: (sessionId, written) => {
890
- updateConversation(id, written ? { sessionId, started: true } : { sessionId });
918
+ updateConversation(id, { sessionId, started: written });
919
+ if (!written)
920
+ live.rotated = true;
891
921
  },
892
922
  started: () => {
893
923
  updateConversation(id, { started: true });
@@ -1135,7 +1165,8 @@ export class SessionDriver {
1135
1165
  return event;
1136
1166
  }
1137
1167
  /** Ends a session's process and gives its slot back; `keep` leaves the record's own state to the caller that is handing the session over. */
1138
- free(id, state) {
1168
+ /** Ends the process of a live session and forgets the session; the record is left as its caller sets it. */
1169
+ endLive(id) {
1139
1170
  const live = this.lives.get(id);
1140
1171
  // NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
1141
1172
  if (live === undefined)
@@ -1148,6 +1179,13 @@ export class SessionDriver {
1148
1179
  if (unstopped)
1149
1180
  process.stderr.write(`[agent-gateway] the agent of ${id} was ended${unstopped}\n`);
1150
1181
  live.ended();
1182
+ }
1183
+ /** Ends a session's process and gives its slot back; `keep` leaves the record's own state to the caller that is handing the session over. */
1184
+ free(id, state) {
1185
+ // NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
1186
+ if (this.stopping || this.lives.get(id) === undefined)
1187
+ return;
1188
+ this.endLive(id);
1151
1189
  if (state !== "keep")
1152
1190
  updateConversation(id, { state, pid: undefined });
1153
1191
  this.drain();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.311",
3
+ "version": "1.3.312",
4
4
  "description": "Reach your AI agents from anywhere — and let them reach you. One stdio process 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.",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",